Jump to content

Emby API in PHP


SilvorMike1

Recommended Posts

PenkethBoy

you only need to get the auth key once - as you login with a user

 

then use it on each subsequent call

  • Like 1
Link to comment
Share on other sites

SilvorMike

you only need to get the auth key once - as you login with a user

 

then use it on each subsequent call

 

Thanks mate - where do you obtain your auth key once logged in - I got one from the chrome debugger in the authenticatebyuser POST command...

But not sure if the key will last or whether it will expire?

 

And it was within the headers. 

Link to comment
Share on other sites

The auth token is created when you post credentials to "/Users/AuthenticateByName" with the proper headers mentioned above.

 

But as PenkethBoy mentioned, I wouldn't authenticate on each request... 

 

the other way to use the api, is to send the url request with "&api_key=" then the api key you create in the dashboard.

 

To best test and understand the api, I would work with the Swagger docs first.

 

click the "api" link at the bottom of the dashboard page.

 

The wiki has the work flow, but here is a quick refresher:

 

1. UDP broadcast on port 7359  "who is EmbyServer?"  to everything on the network.

2. response is ip and port data

3. request "users/public" to get a list of  users

4. get user ID you want

5. Using the  "X-Emby-Authorization" headers, POST headers, userName, password (encrypted in MD5 and Sha1) to "/Users/AuthenticateByName"

6. get access token

7. use access token in subsequent requests to the server under the header "X-Emby-Token".

 

There are ways to refresh the token, but off hand I can't remember, you'd have to reference the github wiki.

Edited by chef
Link to comment
Share on other sites

SilvorMike

Thanks Chef.

 

Got that working. I'll look at how to refresh token

 

The password doesn't seem to change using just ?api_key=key

Link to comment
Share on other sites

  • 2 months later...
maxt.v

Hi guys, 

I have this code in PHP

 

$name="NewUser";

$arrapre = array('Name'=>$name);

$datapost = json_encode($arrapre);
echo $datapost;
 
what I get is this
 
{"Name":"NewUser"}
 
when I send the POST to server.com:8096/emby/Users/New
 
adding this headders:
 
      'User-Agent : Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36',
      'Content-Type : application/x-www-form-urlencoded',
      'X-Emby-Token : embyAPIfromDashboard',
      'X-Emby-Client : Emby Web',
 
I got this error on server log
 
2020-04-07 05:58:36.456 Info HttpServer: HTTP POST http://server.com:8096/emby/Users/New. UserAgent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36
2020-04-07 05:58:36.459 Error HttpServer: Error processing request
    *** Error Report ***
    Version: 4.4.0.40
    Command line: /opt/emby-server/system/EmbyServer.dll -programdata /var/lib/emby -ffdetect /opt/emby-server/bin/ffdetect -ffmpeg /opt/emby-server/bin/ffmpeg -ffprobe /opt/emby-server/bin/ffprobe -restartexitcode 3 -updatepackage emby-server-deb_{version}_amd64.deb
    Operating system: Unix 4.15.0.91
    64-Bit OS: True
    64-Bit Process: True
    User Interactive: True
    Runtime: file:///opt/emby-server/system/System.Private.CoreLib.dll
    System.Environment.Version: 3.1.2
    Processor count: 8
    Program data path: /var/lib/emby
    Application directory: /opt/emby-server/system
    System.ArgumentNullException: System.ArgumentNullException: Value cannot be null. (Parameter 'name')
     at Emby.Server.Implementations.Library.UserManager.CreateUser(String name, UserPolicy userPolicy)
     at MediaBrowser.Api.UserService.Post(CreateUserByName request)
     at Emby.Server.Implementations.Services.ServiceController.GetTaskResult(Task task)
     at Emby.Server.Implementations.Services.ServiceHandler.ProcessRequestAsync(HttpListenerHost appHost, IRequest httpReq, IResponse httpRes, RestPath restPath, String responseContentType, CancellationToken cancellationToken)
     at Emby.Server.Implementations.HttpServer.HttpListenerHost.RequestHandler(IRequest httpReq, ReadOnlyMemory`1 urlString, ReadOnlyMemory`1 localPath, CancellationToken cancellationToken)
    Source: Emby.Server.Implementations
    TargetSite: Void MoveNext()
    
2020-04-07 05:58:36.459 Info HttpServer: HTTP Response 400 to x.x.x.x. Time: 3ms. http://server.com:8096/emby/Users/New
 
 
what I'm missing or what I need to send to the server to add the user ?
Link to comment
Share on other sites

SilvorMike

The error suggests the user isn't being passed...

Although it's a long way around it, try

$arrapre = array('Name'=>''.$name.'');
$datapost = json_encode(''.$arrapre.'');
Link to comment
Share on other sites

maxt.v

Thankyou SilvorMike, but is not working, I got the same result adding this code, I found a way using curl command, but is not what I want...

Link to comment
Share on other sites

msmcpeake

Here's my curl code I made just last week, hope it saves you some struggle!

 

$ch = curl_init();

	curl_setopt($ch, CURLOPT_URL, 'http://<Emby IP/hostname>:8096/emby/Users/New?api_key=<API Key>');
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"Name\":\"{$name}\"}");

	$headers = array();
	$headers[] = 'Accept: application/json';
	$headers[] = 'Content-Type: application/json';
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

	$result = curl_exec($ch);



	if (curl_errno($ch)) {
		echo 'Error:' . curl_error($ch);
	}
curl_close($ch);



$json = json_decode($result, true);


$userid = $json['Id'];


$ch = curl_init();

	curl_setopt($ch, CURLOPT_URL, "http://<Emby IP/hostname>:8096/emby/Users/{$userid}/Connect/Link?api_key=<API Key>");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"ConnectUsername\":\"{$email}\"}");

	$headers = array();
	$headers[] = 'Accept: application/json';
	$headers[] = 'Content-Type: application/json';
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

	$result2 = curl_exec($ch);
	if (curl_errno($ch)) {
		echo 'Error:' . curl_error($ch);
	}
curl_close($ch);

$json2 = json_decode($result2, true);

$ch = curl_init();

	curl_setopt($ch, CURLOPT_URL, "http://<Emby IP/hostname>:8096/emby/Users/{$userid}/Policy?api_key=<API Key>");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"IsAdministrator\":false,\"IsHidden\":true,\"IsHiddenRemotely\":true,\"IsDisabled\":false,\"MaxParentalRating\":0,\"BlockedTags\":[\"\"],\"IsTagBlockingModeInclusive\":false,\"EnableUserPreferenceAccess\":true,\"AccessSchedules\":[\"\"],\"BlockUnratedItems\":[\"\"],\"EnableRemoteControlOfOtherUsers\":false,\"EnableSharedDeviceControl\":true,\"EnableRemoteAccess\":true,\"EnableLiveTvManagement\":true,\"EnableLiveTvAccess\":true,\"EnableMediaPlayback\":true,\"EnableAudioPlaybackTranscoding\":true,\"EnableVideoPlaybackTranscoding\":true,\"EnablePlaybackRemuxing\":true,\"EnableContentDeletion\":false,\"EnableContentDeletionFromFolders\":[\"\"],\"EnableContentDownloading\":false,\"EnableSubtitleDownloading\":false,\"EnableSubtitleManagement\":false,\"EnableSyncTranscoding\":true,\"EnableMediaConversion\":true,\"EnabledDevices\":[\"string\"],\"EnableAllDevices\":true,\"EnabledChannels\":[\"\"],\"EnableAllChannels\":true,\"EnabledFolders\":[\"\"],\"EnableAllFolders\":true,\"InvalidLoginAttemptCount\":0,\"EnablePublicSharing\":true,\"BlockedMediaFolders\":[\"\"],\"BlockedChannels\":[\"\"],\"RemoteClientBitrateLimit\":0,\"AuthenticationProviderId\":\"Emby.Server.Implementations.Library.DefaultAuthenticationProvider\",\"ExcludedSubFolders\":[\"\"],\"DisablePremiumFeatures\":false,\"SimultaneousStreamLimit\":0}");

	$headers = array();
	$headers[] = 'Accept: */*';
	$headers[] = 'Content-Type: application/json';
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

	$result4 = curl_exec($ch);
	if (curl_errno($ch)) {
		echo 'Error:' . curl_error($ch);
	}
curl_close($ch);

$json4 = json_decode($result4, true);

1st curl makes a new user, 2nd adds Emby Connect to that user, 3rd changes policies like hiding them from the login screen, etc.

Link to comment
Share on other sites

  • 2 weeks later...
symphonichorizon

Just a heads up, the add user then add emby connect sometimes messes up and you will end up with a blank user, safer to do one or the other ( either make a local user or use emby connect. )

Link to comment
Share on other sites

msmcpeake

Just a heads up, the add user then add emby connect sometimes messes up and you will end up with a blank user, safer to do one or the other ( either make a local user or use emby connect. )

 

I haven't had this happen yet.

Link to comment
Share on other sites

  • 1 month later...
maxt.v
On 4/8/2020 at 11:04 AM, msmcpeake said:

Here's my curl code I made just last week, hope it saves you some struggle!

 

1st curl makes a new user, 2nd adds Emby Connect to that user, 3rd changes policies like hiding them from the login screen, etc.

Hello msmcpeake, do you find any way to avoid users log on more than 1 device? I can't find a way to automate this, I have to go into the server daily to find if someone is using more than 1 device, then rename the device, delete, and so... this stuggling me because the emby prermiere limitations... any help will be appreciated

Link to comment
Share on other sites

18 hours ago, maxt.v said:

Hello msmcpeake, do you find any way to avoid users log on more than 1 device? I can't find a way to automate this, I have to go into the server daily to find if someone is using more than 1 device, then rename the device, delete, and so... this stuggling me because the emby prermiere limitations... any help will be appreciated

Best thing to do is take advantage of the simultaneous stream limit settings that we have.

Link to comment
Share on other sites

msmcpeake
18 hours ago, maxt.v said:

Hello msmcpeake, do you find any way to avoid users log on more than 1 device? I can't find a way to automate this, I have to go into the server daily to find if someone is using more than 1 device, then rename the device, delete, and so... this stuggling me because the emby prermiere limitations... any help will be appreciated

Sorry, for my setup I don't care about multiple devices per user.  As @Luke mentioned you can use the simultaneous stream limit setting available.  You can set that to be a certain number in the code for a new user creation.
 

"SimultaneousStreamLimit\":0

 

Link to comment
Share on other sites

maxt.v
4 hours ago, Luke said:

Best thing to do is take advantage of the simultaneous stream limit settings that we have.

This not avoid to user login and consume another space for my devices limits, it only prevent to play content on another device, but the devices-limit is consumed when sign in

Link to comment
Share on other sites

  • 2 weeks later...
fogpuppy

Also reaching out msmcpeake for similar "curl magic" to help me bypass the login page and automatically login a  specific user ...  I've opened a thread over in the web app area  If we find a solution I can post it over there as well.

I found some javascript in the UI at /opt/emby-server/system/dashboard-ui/startup/startuphelper.js that is what is actually called by the login UI when you click on a user. 

define(["connectionManager","loading","skinManager","globalize"],function(connectionManager,loading,skinManager,globalize){"use strict";return{authenticateUser:function(serverId,username,password){loading.show(),connectionManager.getApiClient(serverId).authenticateUserByName(username,password).then(function(result){loading.hide(),skinManager.loadUserSkin()},function(result){loading.hide(),require(["alert"],function(alert){alert({text:globalize.translate("MessageInvalidUser"),title:globalize.translate("HeaderSignInError")})})})}}})

The user does not have a password so that should not be an issue.  I'm hoping you can give me some curl equivalent that i could use in php would let me effectively "auto-login" a user named "Guest". with no password.  Or ... any solution really that I can run from a web page front ending emby.

 

Thanks for any help anyone can give ....

Link to comment
Share on other sites

fogpuppy

Ok I figured out how to call authenticate user and get it to return success and get the user id, etc.  My next challenge is how to then get the page to redirect to the home page of Emby with the right headers/parameters to get it to be home page for that user .....  Any ideas anyone... I may be missing something obvious.

Link to comment
Share on other sites

fogpuppy

Thanks, I was actually able to use the capabilities in Chrome to test the API and see that it was working and returning good values.  The problems is now that I can authenticate how to i pass that fact onto the next URL to cause the Home page to open for that user.  It's probably some parameter on the URL or value in the headers but I've not been able to capture/figure that one out yet ....

Edited by fogpuppy
Link to comment
Share on other sites

  • 2 weeks later...
maxt.v

Hi guys, now Im facing this problem:

I have a php script that get the list of users to get the emby-id, then i have another script to get the devices list, then i find every device and if a user have a duplicated device(means he is using the app in 2 devices) the scripts dissable all the devices and only allow connections for the last used device. The problem is that when I do that, the settings are correct, the user only can get acces from the last the device, but magicaly, only can see 60 items on every folder, IE 60 movies, 60 tvshows and 60 channels... what Im doing wrong ? I verify every request and all the requests are fine including the json pharsed, is that a bug on emby server itself?? it happends in LG and Roku app

Link to comment
Share on other sites

  • 2 weeks later...
On 7/16/2020 at 1:39 AM, maxt.v said:

Hi guys, now Im facing this problem:

I have a php script that get the list of users to get the emby-id, then i have another script to get the devices list, then i find every device and if a user have a duplicated device(means he is using the app in 2 devices) the scripts dissable all the devices and only allow connections for the last used device. The problem is that when I do that, the settings are correct, the user only can get acces from the last the device, but magicaly, only can see 60 items on every folder, IE 60 movies, 60 tvshows and 60 channels... what Im doing wrong ? I verify every request and all the requests are fine including the json pharsed, is that a bug on emby server itself?? it happends in LG and Roku app

Hi, I'm afraid I don't quite understand what you're trying to explain. We'd have to look at some code samples of what you're trying to do. Thanks.

Link to comment
Share on other sites

henzo800

Hi, 

I'm having a similar issue and the suggested headers and both methods of sending the API key do not seem to fix it. I can create users just fine and retrieve their id successfully but i get an error when i try to change their default password. From what i can gather it does seem to be a bug, i think the API is not sending the object to the system in the correct format (Even with json parameters missing this error will occur, but the API key seems to be accepted by the system). I have attached the relevant PHP code and the error in the embyserver.txt file. Any help would be great 😀.

2020-07-26 08:12:55.755 Info HttpServer: HTTP POST https://<DOMAIN>/emby/Users/<USER-ID>/Password. UserAgent: Mozilla/5.0 (compatible; Rigor/1.0.0; http://rigor.com)
2020-07-26 08:12:55.758 Error HttpServer: Error processing request
*** Error Report ***
Version: 4.4.3.0
Command line: /opt/emby-server/system/EmbyServer.dll -programdata /var/lib/emby -ffdetect /opt/emby-server/bin/ffdetect -ffmpeg /opt/emby-server/bin/ffmpeg -ffprobe /opt/emby-server/bin/ffprobe -restartexitcode 3 -updatepackage emby-server-deb_{version}_amd64.deb
Operating system: Unix 4.19.0.8
64-Bit OS: True
64-Bit Process: True
User Interactive: True
Runtime: file:///opt/emby-server/system/System.Private.CoreLib.dll
System.Environment.Version: 3.1.2
Processor count: 8
Program data path: /var/lib/emby
Application directory: /opt/emby-server/system
System.NullReferenceException: System.NullReferenceException: Object reference not set to an instance of an object.
at MediaBrowser.Api.BaseApiService.AssertCanUpdateUser(IAuthorizationContext authContext, IUserManager userManager, Int64 userId, Boolean restrictUserPreferences)
at MediaBrowser.Api.UserService.PostAsync(UpdateUserPassword request)
at Emby.Server.Implementations.Services.ServiceController.GetTaskResult(Task task)
at Emby.Server.Implementations.Services.ServiceHandler.ProcessRequestAsync(HttpListenerHost appHost, IRequest httpReq, IResponse httpRes, RestPath restPath, String responseContentType, CancellationToken cancellationToken)
at Emby.Server.Implementations.HttpServer.HttpListenerHost.RequestHandler(IRequest httpReq, ReadOnlyMemory`1 urlString, ReadOnlyMemory`1 localPath, CancellationToken cancellationToken)
Source: Emby.Api
TargetSite: Void AssertCanUpdateUser(MediaBrowser.Controller.Net.IAuthorizationContext, MediaBrowser.Controller.Library.IUserManager, Int64, Boolean)
2020-07-26 08:12:55.758 Info HttpServer: HTTP Response 500 to <IP>. Time: 3ms. https://<DOMAIN>/Users/<USER-ID>/Password
//create user
$url = "https://<DOMAIN>/emby/Users/New?api_key=".$apikey;
	$data = array(
		'Name' => $username
		);

	$options = array(
		'http' => array(
			'header'  => "Content-type: application/json\r\n",
			'method'  => 'POST',
			'content' => json_encode($data)
		)
	);
	$context  = stream_context_create($options);

	$result = @file_get_contents($url, false, $context);
	if ($result === FALSE) { 
		echo "Request Failed, Contact Support"; 
	}
	else {
		echo "User with name: ".$username. "has been created.";
	}
	$decode = json_decode($result, true);
	$media_id = $decode['Id'];
	$_SESSION["streaming"] = 1;
	echo "Id:".$media_id;
	//update default password
	$url = "https://<DOMAIN>/emby/Users/".$media_id."/Password?api_key=".$apikey;
	$data = array(
		'Id' => $media_id,
		'CurrentPw' => '',
		'NewPw' => $password,
		'ResetPassword' => true
		);
	echo var_dump(json_encode($data));
	$options = array(
		'http' => array(
			'header'  => "Content-type: application/json\r\n",
			'method'  => 'POST',
			'content' => json_encode($data)
		)
	);
	$context  = stream_context_create($options);

	$result = @file_get_contents($url, false, $context);
	if ($result === FALSE) { 
		echo "Request Failed, Contact Support"; 
	}
	else {
		echo "User with name: ".$username. "password set.";
	}
	$decode = json_decode($result, true);
	var_dump($decode);

 

Edited by henzo800
Hiding IP and Domain
Link to comment
Share on other sites

PenkethBoy

just tested via swagger - creating a new user and updating the password work fine - .15 beta via http

from a quick look at above -  it appears you are not defining $password

for

'NewPw' => $password,

 

ps. you are giving away your domain name and Ip address in the post above

Link to comment
Share on other sites

henzo800
17 hours ago, PenkethBoy said:

just tested via swagger - creating a new user and updating the password work fine - .15 beta via http

Ok, so i updated emby to the beta version (4.5.0.15) and the issue does not seem to be fixed. I am receiving an identical error. Could you send me an example of your query so i can make sure im not doing anything wrong. Also I only included the relevant PHP, $password is defined elsewhere. Any help would be appreciated.

Link to comment
Share on other sites

PenkethBoy

i just went into swagger

used the endpoint /users/new to create a new user

then used the id of that user with

/users/93b347e425584a8ba1b0f64b00be08f1/password end point

e.g.

{
  "Id": "93b347e425584a8ba1b0f64b00be08f1",
  "CurrentPw": "",
  "NewPw": "1234",
  "ResetPassword": true
}

you get a 204 response - which means "success no content returned"

if that does not work - try it without https and your domain name

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...