All Products
Search
Document Center

AppServer source code integration

Last Updated: May 27, 2020

Overview

This topic describes the methods of the Alibaba Cloud SmartVideo AppServer. You can use these methods to exchange data between the SmartVideo application and ApsaraVideo for VOD, process business logic, and manage operations data. For example, you can randomly generate users, obtain video lists, obtain credential information, upload videos, and process various callback events. The technologies involved include the Spring Boot microservice framework, ApsaraDB RDS for MySQL, and MyBatis persistence framework.

SmartVideo methods

Method type Method name Description
Credentials (AuthController) /vod/getSts Obtains the AccessKey ID, AccessKey secret, and security token for upload authorization.
Credentials /vod/getVideoUploadAuth Obtains the video upload URL and credential based on the information about a video, such as its title and mezzanine file name.
Credentials /vod/refreshVideoUploadAuth Updates the video upload credential based on the video ID.
Credentials /vod/getVideoPlayAuth Obtains the video playback credential based on the video ID. You can use the video playback credential to play the relevant video on the client.
Credentials /vod/getImageUploadAuth Obtains the image upload URL and credential based on the information about an image, such as the image type.
Users (UserProfileController) /user/randomUser Creates a random user and obtains the user token to display user logic.
Videos (VodController) Publishes videos, deletes videos, and obtains video lists on the client.
Business logic /vod/videoPublish Publishes a video.
Business logic /vod/getRecommendVideoList Obtains a list of recommended videos.
Business logic /vod/getPersonalVideoList Obtains a list of videos in the user center.
Business logic /vod/deleteVideoById Deletes a video based on the video ID.
Resources (ResourceMediaController) Obtains the information about motion graphics materials, subtitles, or other resources.
Business logic /resource/getPasterInfo Obtains the information about motion graphics materials.
Business logic /resource/getMv Obtains the information about music videos (MVs).
Business logic /resource/getTextPasterList Obtains the information about subtitles based on the subtitle ID.
Business logic /resource/getPasterList Obtains the information about motion graphics materials based on the motion graphics material ID.
Business logic /resource/getFrontPasterList Obtains a list of facial motion graphics materials.
Business logic /resource/getFont Obtains the font information based on the font ID.
Music (DmhController) Obtains a list of recommended music and obtains the music playback URL based on the music ID.
Business logic /music/getRecommendMusic Obtains a list of recommended music.
Business logic /music/getPlayPath Obtains the music playback URL based on the music ID.

For more information, see AppServer SmartVideo methods.

Console methods

Method type Method name Description
Console (ConsoleController) /console/vod/getVideos Obtains a list of videos based on query criteria.
Console /console/vod/getRecommendVideoById Obtains the details of a recommended video based on the video ID.
Console /console/vod/pushObjectCache Preloads the content of trending videos.
Console /console/vod/getRecommendVideos Obtains a list of recommended videos based on query criteria.
Console /console/vod/createAudit Manually reviews or blocks a video.
Console /console/vod/getVideoById Obtains the details of a video based on the video ID.
Console /console/vod/recommendVideo Adds a video in the user center to the list of recommended videos.
Console /console/vod/deleteRecommendById Removes a video from the list of recommended videos.
Console /console/vod/deleteVideoById Deletes a video based on the video ID.
Console /console/vod/submitTabTranscode Submits a Narrowband HD transcoding job based on the transcoding template ID.
Console /console/vod/submitTranscode Submits a non-Narrowband HD transcoding job based on the transcoding template ID.
Console users (ConsoleUserController) /console/user/login Logs on to the console.
Console users /console/user/signOut Logs off from the console.

For more information, see AppServer console methods.

Activate Alibaba Cloud services

The following Alibaba Cloud services are required: ECS, ApsaraDB for RDS, and ApsaraVideo for VOD.

Note: You must deploy all Alibaba Cloud services in the same region.

ECS

ECS is a computing service that features auto scaling. It can help you reduce IT costs and improve O&M efficiency, so that you can concentrate on core business innovation. You can visit the following website to activate the ECS service: ECS.

You need to set up a Java environment for ECS. We recommend that you install Java 1.8.

  1. [alivcsdk@ilvb-app-server-1 ~]$ java -version
  2. java version "1.8.0_191"
  3. Java(TM) SE Runtime Environment (build 1.8.0_191-b12)
  4. Java HotSpot(TM) 64-Bit Server VM (build 25.191-b12, mixed mode)

ApsaraDB for RDS

ApsaraDB for RDS is a database that is optimized or deployed in a virtual computing environment. It has advantages such as pay-as-you-go, on-demand scaling, high availability, and storage integration. This demo only supports ApsaraDB RDS for MySQL. Make sure that your ApsaraDB for RDS instance resides in the same region as your ECS instance. You can visit the following website to activate the ApsaraDB for RDS service: ApsaraDB for RDS.

ApsaraVideo for VOD

ApsaraVideo for VOD is an all-in-one audio- and video-on-demand solution. It integrates video collection, editing, and upload, media resource management, automatic transcoding (Narrowband HD™), video content moderation and analysis, and Content Delivery Network (CDN) for accelerated content delivery. You can visit the following website to activate the ApsaraVideo for VOD service: ApsaraVideo for VOD.

Configure Alibaba Cloud services

ApsaraVideo for VOD

ApsaraVideo for VOD provides a variety of media processing capabilities. With economic, elastic, and highly scalable audio and video conversion methods, ApsaraVideo for VOD helps you transcode your audio and videos to formats suitable for playback on PCs, TVs, and mobile devices. Based on the transcoding capability of ApsaraVideo for VOD, SmartVideo provides advanced capabilities such as secure watermark sharing, Narrowband HD, and AI media audit. To use SmartVideo, you need to configure domain names, transcoding templates, and callback events.

  1. Configure domain names.

To access videos or images in ApsaraVideo for VOD, you need to configure at least a domain name. This domain name is also required when you configure projects.

For more information about domain name configuration, see Add a domain name.

  1. Configure transcoding templates.

Considering user experience and security, you need to play short videos without watermarks on an application or webpage, but add watermarks to downloaded videos and shared videos. We also recommend that you configure the same resolution for played videos and downloaded videos. You can implement these features by using the transcoding service of ApsaraVideo for VOD. The configuration procedure is as follows: Log on to the ApsaraVideo for VOD console. In the left-side navigation pane, choose Configuration Management > Media Processing > Transcode. On the Transcode page, click Create Template to create two transcoding templates and set Definition to Low Definition and Standard Definition, respectively.

  • Low Definition: 720p without watermarks
  • Standard Definition: 720p with watermarks

For more information, see Transcoding settings.

  1. Configure callback events.

Video processing services such as AI media audit, video snapshot, and transcoding jobs are processed asynchronously. ApsaraVideo for VOD notifies business parties of all the status updates and processing results by sending asynchronous messages or callback event notifications. This SmartVideo demo uses HTTP requests as the callback method to send callback event notifications. The configuration procedure is as follows:Log on to the ApsaraVideo for VOD console. In the left-side navigation pane, choose Configuration Management > Media Processing > Callback. On the Callback page, click Modify. In the Callback dialog box that appears, set parameters and select the following options for Events: All Transcoding Tasks Completed, AI Processing Completed, Create Audit Completed, and Screenshot Created.

For more information, see Event notification.

  1. Configure callback authentication.ApsaraVideo for VOD allows you to add a specific signature header to each HTTP or HTTPS callback request. In this way, the server that receives callback event notifications can authenticate the signature to prevent illegal or invalid requests.First, specify a custom authentication key in the ApsaraVideo for VOD console.

Then, replace the authentication key in the code with the one you specified in the ApsaraVideo for VOD console as follows:Open the project file /sdk-api/src/main/resources/application.properties and set the CALLBACK_PRIVETEKEY parameter to the authentication key you specified in the ApsaraVideo for VOD console.

For more information, see HTTP callback authentication.

  1. Configure the video audit feature.

The video audit feature allows you to audit videos before publishing them. You can block improper videos in a timely manner or in advance to reduce or avoid adverse effects caused by these videos when they are published.

For more information, see Audit settings.

ApsaraDB for RDS

  1. Configure the whitelist for accessing ApsaraDB for RDS. For more information, see Configure a whitelist.
  2. Create an ApsaraDB for RDS account.

This account is used to log on to the ApsaraDB for RDS database. When writing program code, you can use this account to set up database connections and log on to the ApsaraDB for RDS console to create table schemas and initialize the database. Keep the username and password properly.

On the instance management page, click Accounts in the left-side navigation pane. On the Accounts page, click Create Account. On the page that appears, set parameters to create an account, including Database Account, Account Type, Password, and Re-enter Password.

Generally, you can set Account Type to Standard Account. You can also leave Authorized Database blank and select authorized databases later.For more information, see Create accounts and databases for an RDS for MySQL instance.

  1. Create a database.On the instance management page, click Databases in the left-side navigation pane. On the Database page, click Create Database in the upper-right corner. The Create Database page appears, as shown in the following figure.

Configure the following fields:Supported Character Set: the supported character set. Select utf8mb4 to support emoticons.Authorized Account: the account to be granted access to the database. Select the account that you previously created.Account Type: the account permission. Select Read/Write to grant the required read and write permissions to the account.

  1. Initialize the database.On the instance management page, click Basic Information in the left-side navigation pane. On the page that appears, click Log On to DB. The RDS Database Logon page appears, as shown in the following figure.

In the ApsaraDB for RDS console, click Log On to DB in the upper-right corner to go to the database logon page in the DMS console. Select the network address of the relevant instance and use the username and password of the previously created account to log on to the previously created database. Then, you can create tables and initialize data as follows:

  • Create a table.Find the appserver_create_table.sql file in the sql folder in the root directory of your project. Use the table creation statements in the file to create tables.

  • Initialize table data.Run the following code to create an administrator account for the SmartVideo console:

  1. insert into `console_userinfo`(`id`,`user_id`,`user_name`,`avatar_url`,`password`,`remark`)
  2. values(1,'12351232334','admin','','12345678','administrator');

Change the values of the user_id, user_name, avatar_url, and password parameters as required.

Alibaba Cloud RAM

Resource Access Management (RAM) is an Alibaba Cloud service designed for user identity management and resource access control. You can use RAM to create and manage RAM users, such as employees, systems, or applications, and control their access permissions on resources under your Alibaba Cloud account. If multiple people in your enterprise work collaboratively and share resources, you do not have to share the AccessKey of your Alibaba Cloud account with others. You can use RAM to grant RAM users the minimum permissions necessary for them to complete their work, thereby improving the security of your enterprise’s information. RAM is required for almost all Alibaba Cloud services. STS is an Alibaba Cloud service that manages temporary access permissions for Alibaba Cloud accounts (or RAM users). Using STS, you can grant each RAM user (who you can manage under your Alibaba Cloud account) an access credential with a custom validity period and custom permissions. Then, RAM users can use this temporary access credential granted by STS to call Alibaba Cloud APIs or log on to the Alibaba Cloud console to access authorized resources. The SmartVideo solution also uses STS to grant temporary access credentials. You need to grant the AliyunVODFullAccess permission (indicating all ApsaraVideo for VOD permissions) to RAM users. For more information, see STS authorization.

Quick start

Source code download

Download the SmartVideo AppServer source code package.

Project description

The AppServer project supports the client in calling relevant methods and organizes data logic for the client. The directory structure of the project can be divided into the control layer, dao layer, service layer, and persistence layer.

Project description

Note: To use the source code, you need to replace the values of some parameters based on your configuration, such as the database configuration, the AccessKey ID and AccessKey secret, and relevant service configuration. For more information, see the following AppServer project configuration.

AppServer project configuration

Database

You must make sure that ApsaraDB for RDS is activated and the account and password are created for the ApsaraDB for RDS instance. Then, you need to replace the relevant configuration in source code files. For more information, see the application.properties file in the /sdk-api/src/main/resources directory.

  1. #DATABASE (After creating a database, you can use the username and password of the previously created account to log on to the database.)
  2. spring.datasource.url = jdbc:mysql://{dburl}:3306/{dbname}?useSSL=false&useUnicode=true&characterEncoding=UTF-8
  3. spring.datasource.username = <# The username used to log on to the ApsaraDB for RDS database. >
  4. spring.datasource.password = <# The password used to log on to the ApsaraDB for RDS database. >

{dburl}: the network address of the ApsaraDB for RDS instance. You can obtain this information from the ApsaraDB for RDS console as follows: Go to the instance management page and choose Basic Information > Intranet Address. The default port number is 3306.username and password: the username and password of the previously created ApsaraDB for RDS account.{dbname}: the name of the previously created ApsaraDB for RDS database.

ApsaraVideo for VOD

You must make sure that ApsaraVideo for VOD is activated and the account and password are created for the ApsaraDB for RDS instance. Then, you need to replace the relevant configuration in source code files. For more information, see the application.properties file in the /sdk-api/src/main/resources directory.

  1. #transcoding template ID
  2. TEMPLATEGROUP_ID = <# The transcoding template ID for videos. >
  3. TAB_TEMPLATEGROUP_ID = <# The template ID for Narrowband HD transcoding. >
  4. #domain name
  5. DOMAIN_NAME = <# The domain name, in the http://xxx.com/ format. >
  6. AVATAR_DOMAIN_NAME = <# The domain name for the avatar. Set the value to http://live-appserver-sh.alivecdn.com/. >
  7. VOD_REGIONID = cn-shanghai
  8. CALLBACK_PRIVETEKEY = <# The authentication key for callback events. >
  9. CALLBACK_NAME = <# The callback URL. Set the value to http://ip:8080/vodcallback/callback. >
  10. #for VOD services policy
  11. policy = {"Version": "1", "Statement": [ {"Action": ["vod:*"], "Resource": ["*" ],"Effect": "Allow"}]}

Note: If you use a Chinese Alibaba Cloud account, the default value of the VOD_REGIONID parameter is cn-shanghai, indicating that the region is China (Shanghai). We recommend that you activate other involved Alibaba Cloud services in the same region. If you use an international Alibaba Cloud account, set the VOD_REGIONID parameter as required.

STS and dynamic identity and authorization for cloud applications

You must make sure that RAM is activated and configured by referring to STS authorization, and a temporary access credential is obtained. In addition, use RAM to allow applications to obtain the dynamic STS token of a RAM role for access to Alibaba Cloud APIs. For more information, see Dynamic identity and permission management of cloud applications. Then, you need to replace the values of the following parameters in source code files: REGION_CN_HANGZHOU, STS_API_VERSION, roleArn, roleSessionName, and roleName. For more information, see the application.properties file in the /sdk-api/src/main/resources directory.

  1. #ak information
  2. REGION_CN_HANGZHOU = cn-hangzhou
  3. STS_API_VERSION = 2015-04-01
  4. roleArn = <# The Alibaba Cloud Resource Name (ARN). >
  5. roleSessionName = <# The name of the session that uses the temporary token. >
  6. roleName = <# The name of the RAM role. >

Service packaging and compilation

Compile and package project files

Run the following command to go to the root directory of the disk where the project files are stored:

  1. mvn clean package -Dmaven.test.skip=true

Compile and package project filesAs shown in the preceding figure, the “BUILD SUCCESS” message indicates that the project files are packaged. You can find a JAR package named sdk-api-0.0.1-SNAPSHOT.jar in the target/ directory.

Deploy the AppServer

Upload the JAR package to the current user directory of your ECS instance. Run the following command to start the AppServer:

  1. nohup java -jar sdk-api.jar &

Deploy the AppServer

Access the project

  1. Access the project.Use the default port number 8080 and your server IP address to access the AppServer project:http://{Your server IP}:8080/demo/getSts
  1. @RequestMapping(value = "/demo/getSts", method = RequestMethod.GET)
  2. @ResponseBody
  3. public ResponseResult getSts() throws Exception {
  4. String traceId = TraceIdContext.ctx.get().getTraceId();
  5. LOG.info("traceId: {} ",traceId);
  6. ResponseResult result = new ResponseResult(traceId);
  7. Map<String, String> stsMap = new HashMap<String, String>(4);
  8. try {
  9. stsMap.put("expiration", AkUtil.getAkInfo().getString("Expiration"));
  10. stsMap.put("accessKeyId", AkUtil.getAkInfo().getString("AccessKeyId"));
  11. stsMap.put("accessKeySecret", AkUtil.getAkInfo().getString("AccessKeySecret"));
  12. stsMap.put("securityToken", AkUtil.getAkInfo().getString("SecurityToken"));
  13. result.setData(stsMap);
  14. } catch (ClientException e) {
  15. result.setResult("false");
  16. result.setCode(ConstanData.INTERNAL_SERVER_ERROR);
  17. result.setMessage("An internal server error occurred.");
  18. result.setData(null);
  19. LOG.error("An error occurred while obtaining the STS token.", e);
  20. }
  21. return result;
  22. }

The response is as follows:

  1. {
  2. "result": "true",
  3. "requestId": "05afbda6-2c7c-43be-bb66-bd85e50914ee",
  4. "message": "",
  5. "code": "200",
  6. "data": {
  7. "accessKeyId": "STS.NHcwHdkzNZXV78f5LXsAtBjrj",
  8. "securityToken": "CAISiwJ1q6Ft5B2yfSjIr4vWPPLQhqVv7Zq9NR7X0UwNf85Yra/ZiDz2IHlKdHBuCeoWs/QylWxU5voblrRtTtpfTEmBbI5t4MpVqhrwPtHTspGu/OEchIG5FDBW4eoHHoqADd/iRfbxJ92PCTmd5AIRrJL+cTK9JS/HVbSClZ9gaPkOQwC8dkAoLdxKJwxk2qR4XDmrQpTLCBPxhXfKB0dFoxd1jXgFiZ6y2cqB8BHT/jaYo603392oesP9M5UxZ8wjCYnujLJMG/CfgHIK2X9j77xriaFIwzDDs+yGDkNZixf8aLOKooQxfFUpO/hnSvIY/KSlj5pxvu3NnMH7xhNKePtSVynP9kh1DXtxrYkagAEZuvLVwHxAb2PA5kSr/u9Hyt0iEqW1XSCcEMJ+oxEAEwocUHqKQRGzQJn0U1uxyPveM5GYElUcm/9Os7l546j8moMjUIAkhJ2Rl1Ty8KLHyHzbNmZLlZ+lUFW2l0NWTXWbO8ZWyW90tYqjXqKExoKGf6h9HBTMVfXrWia+N1RtTw==",
  9. "expiration": "2019-05-10T16:15:17Z",
  10. "accessKeySecret": "5oeqKaimw6Bi6z5uiPDn357to9MAkMJZRS5mZGrD8ceM"
  11. }
  12. }
  1. Access the SmartVideo consoleTo access the SmartVideo console, you must compile and package console source code files. For more information, see Console source code integration. Then, visit the following website to log on to the SmartVideo console: http://{Your server IP}:8080/resource/index.html#/login.
  • The default username is admin, and the default password is 12345678.

Additional information

  1. Notes:You can modify the port number 8080 in the src/main/resources/application.properties file of the Spring Boot project.
  1. public void customize(ConfigurableEmbeddedServletContainer container) {
  2. container.setPort(8080);
  3. }

{ip} indicates the public IP address of the ECS instance. You can obtain this information from the ECS console. If you have configured a domain name, you can also resolve the domain name to this IP address and use the domain name to access the project.

For example, use http://{ip}:{port}/ as the endpoint for calling methods.

  1. View logs.Run the following command to view logs:

    1. tail -f nohup.out

    Logs

AppServer front-end webpage configuration

You can find the front-end source code in the video-admin folder in the root directory of the AppServer project.To visit the front-end webpage, you need to configure the resources tag in the pom.xml file and change the folder name specified by the targetPath parameter to the package name of the front-end source code. For more information, see Console source code integration.

Precautions

  • To configure the SmartVideo AppServer, make sure that you use the ApsaraVideo for VOD SDK V2.12.0 or later, Java Core V4.3.3 or later, and aliyun-java-sdk-core V4.3.3 or later.

  • Use http or https as the prefix of the domain name or IP address as required. Do not use the https prefix if you do not activate the HTTPS service.

  • When you compile the application.properties file, note the following points: The CALLBACK_PRIVETEKEY parameter indicates the authentication key. Set the same authentication key in the file and in the console. The CALLBACK_NAME parameter indicates the callback URL. The AVATAR_DOMAIN_NAME parameter indicates the domain name of the user avatar. The AVATAR_URL parameter indicates the user URL. You can set multiple URLs by separating them with a comma (,). For example, you can set AVATAR_DOMAIN_NAME and AVATAR_URL as follows: AVATAR_DOMAIN_NAME = http://xxx.com ,AVATAR_URL = heads/01.png,heads/02.png. The AUDIT_SETTINGS_FLAG parameter indicates the audit method. The value on indicates that you audit videos before publishing them. The value off indicates that you audit videos after publishing them.

Key business logic

Video publish

When you upload a video on the client, you also submit a first frame snapshot job, a video snapshot job (for taking eight video snapshots), and a video audit job asynchronously. Then, ApsaraVideo for VOD takes video snapshots and audits the video. When ApsaraVideo for VOD completes the audit, it sends a callback event notification to notify the AppServer of the audit result. After receiving the audit result, the AppServer distinguishes whether the job is a video audit job, a first frame snapshot job, or a video snapshot job based on the returned snapshot type and number of snapshots. If a video audit job is completed, the AppServer changes the audit status. If a first frame snapshot job is completed, the AppServer modifies the first frame data in the video library. If a video snapshot job is completed, the AppServer inserts the snapshot data (images and user ID) to the snapshot table.

Callback after the completion of a video snapshot job

After a video snapshot job is completed, ApsaraVideo for VOD triggers a SnapshotComplete event to notify the AppServer of the job result. For more information, see SnapshotComplete. In the AppServer project, you submit two snapshot jobs when you upload a video: a first frame snapshot job that takes a snapshot of the first frame in the video, and a video snapshot job that takes multiple video snapshots for you to view in the SmartVideo console. After receiving a notification of the SnapshotComplete event, the AppServer checks the returned data as follows: Check the SubType parameter first. If the value is SpecifiedTime, the snapshots are taken through the SubmitSnapshotJob operation. Then, check the Status parameter. If the value is success, the snapshot job succeeded. Then, check the number of elements in the JSON-formatted array of the SnapshotInfos parameter. Multiple elements indicate multiple video snapshots. The AppServer stores the snapshots in the snapshot table. A single element indicates the first frame snapshot. The AppServer changes the snapshot status to successful in the vod_videos table and updates the first frame in the table to this snapshot.

Callback after the completion of a video audit job

After a video audit job is completed, ApsaraVideo for VOD triggers an AIMediaAuditComplete event to notify the AppServer of the job result. For more information, see AIMediaAuditComplete. After receiving this event notification, the AppServer checks the returned data as follows: Check the Status parameter first. If the value is success, the audit job succeeded. Then, check the Suggestion parameter of the Data parameter. If the value of the Suggestion parameter is pass, the video passes the audit. The AppServer changes the audit status to successful and calls a manual audit method to submit a non-Narrowband HD transcoding job. If the value of the Suggestion parameter is block, the video contains violations. The AppServer changes the audit status to failed. If the value of the Suggestion parameter is review, the video needs to be audited manually. The AppServer changes the audit status to to-be-reviewed. If the value of the Status parameter is fail, the audit job failed. The AppServer changes the audit status to failed.

Callback after the completion of a transcoding job

After a transcoding job is completed, ApsaraVideo for VOD triggers a TranscodeComplete event to notify the AppServer of the job result. For more information, see TranscodeComplete. After receiving this event notification, the AppServer checks the returned data as follows: Check the Status parameter first. If the value is success, the transcoding job succeeded. The AppServer changes the transcoding status to successful and stores the playback URL (FileUrl) and video ID (VideoId) of the transcoded video in the transcoding table. If the value is fail, the transcoding job failed. The AppServer changes the transcoding status to failed.