playing video player in flutter - api

I've a courses app in production mode when published it there is an problem occurs that the video player doesn't work
I'm using chewie package and there is my code
Chewie(controller: videoPlayerController)
var controller;
var videoPlayerController;
#override
void initState() {
print("video link is : ${widget.initialUrl}"); // https://www.privilegeapps.com/images/materials/Ceramics Part 2 Material 2_93ef3e743cfd6c0a6e7baa9a3409f2e5.mp4
controller = VideoPlayerController.network(widget.initialUrl);
loadVideoPlayer();
super.initState();
videoPlayerController = ChewieController(
videoPlayerController: controller,
allowFullScreen: false,
autoInitialize: true,
allowedScreenSleep: false,
aspectRatio: 5 / 8,
autoPlay: false,
looping: false,
)
..addListener(() => setState(() {}))
..setLooping(true);
controller.initialize().then((_) => videoPlayerController.play());
}
loadVideoPlayer() {
controller.addListener(() {
setState(() {
print("Video Link is : ${widget.initialUrl}");
});
});
controller.initialize().then((value) {
setState(() {
print("Load Video Player Initialized 2222");
});
}).catchError((e) {
print("***********************************");
print("Vedio player error is : $e");
print("***********************************");
});
}
it always goes to catch error block with any link come from the GET API, if I use any other link like this Package Example it's work without any problems
my GET API Function
Future<void> getOneMaterial(String materialId) async {
var uri = Uri.parse('${APIsURL}/material/$materialId');
emit(HomeGetOneMaterialLoadingState());
await http.get(uri, headers: {
"Accept": "application/json",
'Authorization': 'Bearer ${CacheHelper.getData(key: 'token')}'
}).then((value) {
oneMaterialModel = OneMaterialModel.fromJson(jsonDecode(value.body));
print(" getOneMaterial body is : ${value.body}");
emit(HomeGetOneMaterialSuccessState());
}).catchError((e) {
emit(HomeGetOneMaterialErrorState());
});
}
catch error block output is
PlatformException(VideoError, Video player had error com.google.android.exoplayer2.ExoPlaybackException: Source error, null, null)
androidmainfest.xml already has this tag
android:usesCleartextTraffic="true"
of course I'm trying to make flutter clean and rebuild again

Related

How to do screen sharing in agora without getting an authentication problem

I've implemented the agora sdk 3.0 for video calls.
now I'm trying to get screen sharing to work, but I keep getting the error provided in
the picture below (Join failed: NO_AUTHORIZED).
Picture of console while sharing a screen
screen sharing code sample:
async shareScreen() {
this.shareClient = AgoraRTC.createClient({
mode: 'rtc',
codec: 'vp8'
})
this.shareClient.init('xxxxxxxxxxxxxx', () => {
this.shareClient.join('same token video call started with', 'same room name of current outgoing video call', null, (uid) => {
const streamSpec = {
streamID: uid,
audio: false,
video: false,
screen: true
}
if (isFirefox()) {
streamSpec.mediaSource = 'window';
} else if (!isCompatibleChrome()) {
streamSpec.extensionId = 'minllpmhdgpndnkomcoccfekfegnlikg';
}
this.shareScreenStream = AgoraRTC.createStream(streamSpec);
// Initialize the stream.
this.shareScreenStream.init(() => {
// Play the stream.
this.shareScreenStream.play('renderer');
// Publish the stream.
this.shareClient.publish(this.shareScreenStream);
}, function(err) {
console.log(err);
});
}, function(err) {
console.log(err);
})
});
},
The screensharing client should use an unique token based on the UID and channel name. Not the one the main user is using.

Send additional info to server in uploading image process

im using filepond 4.25.1 on vue 2.6.11 and everything work without problem until now.
i want to send additional information to my server which is aspnet core 3. i send my request from filepond like below
myServer: {
url: "http://**********/api/CustomerAuth/",
process: {
url: "uploadimages",
method: "POST",
withCredentials: false,
headers: {},
data: {
nationalcode: "1234567890",
typecode:"1"
},
timeout: 7000,
},
load: (source, load) => {
fetch(source)
.then((res) => res.blob())
.then(load);
},
}
and server side
[HttpPost("uploadimages")]
public IActionResult UploadImages()
{
try
{
var file = Request.Form.Files[0];
string folderName = "Upload";
string webRootPath = _hostingEnvironment.WebRootPath;
string newPath = Path.Combine(webRootPath, folderName);
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
if (file.Length > 0)
{
string fileName =
ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
string fullPath = Path.Combine(newPath, fileName);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
}
}
return Ok("Upload Successful");
}
catch (System.Exception ex)
{
return NotFound(new { img_upld_error = ex.Message });
}
}
in server side i need to access "nationalcode" and "typecode" which is send as data in process and value of these two parameters always change so its not static value and with interact of user value of this two always change.
I really appreciated if someone give me a some clue or guide me to solve my problem.
FilePond dev here.
data does not exist as a prop on process.
You can add additional FormData parameters with the ondata property. See updated example below:
myServer: {
url: "http://**********/api/CustomerAuth/",
process: {
url: "uploadimages",
method: "POST",
withCredentials: false,
headers: {},
data: {
nationalcode: "1234567890",
typecode:"1"
},
ondata: (formData) => {
formData.append('nationalcode', '1234567890');
formData.append('typecode', '1');
return formData;
}
timeout: 7000,
},
load: (source, load) => {
fetch(source)
.then((res) => res.blob())
.then(load);
},
}
Alternatively you can use the filepond metadata plugin to add metadata to each file (this is automatically sent to the server).
https://pqina.nl/filepond/docs/patterns/plugins/file-metadata/
FilePond.setOptions({
fileMetadataObject: {
'nationalcode': '1234567890',
'typecode': '1'
}
})
You can get file's in model, define your model like this
public class FileWithDataModel
{
public IFormFile File { get; set; }
public string NationalCode { get; set; }
public string TypeCode { get; set; }
}
and controller method will be :
public async Task<IActionResult> UploadFileWithData(FileWithDataModel model)
{
var file = model.File;
//you can save this file...
var nCode = model.NationalCode; //can access data easy
//......
return Ok();
}
Microsoft suggest to use Async method especially for file processing and uploading
here is example of jquery client
var form = new FormData();
form.append("NationalCode", "12345678");
form.append("TypeCode", "1");
form.append("File", fileInput.files[0], "/path/to/file");
var settings = {
"url": "http://**********/api/CustomerAuth/",
"method": "POST",
"timeout": 0,
"headers": {
"Content-Type": "application/x-www-form-urlencoded"
},
"processData": false,
"mimeType": "multipart/form-data",
"contentType": false,
"data": form
};
$.ajax(settings).done(function (response) {
console.log(response);
});

how to refresh message stream for chat inbox in flutter

I'm new to the flutter, I start to create a simple messenger app using flutter and flutter stream to handle API call for get message content.
also created the message controller to update and refresh the message list
class MessageService {
Client httpClient = Client();
List<MessageModal> _messageList = [];
Future<AppConfig> _getApiURL() async {
final config = await AppConfig.forEnvironment('dev');
return config;
}
Future<List<MessageModal>> getMessageThread(
String senderId, String receiverId) async {
var config = await _getApiURL();
var url = config.baseUrl + "message/history";
final response = await httpClient.post(url,
headers: {"content-type": "application/json"},
body: json.encode({
"senderId": senderId,
"receiverId": receiverId,
}));
if (response.statusCode == 200) {
_messageList = messageListFromJson(response.body);
} else {
_messageList = [];
}
return _messageList;
}
}
Here is the message service class for fetch API data
class MessageService {
Client httpClient = Client();
List<MessageModal> _messageList = [];
Future<AppConfig> _getApiURL() async {
final config = await AppConfig.forEnvironment('dev');
return config;
}
Future<List<MessageModal>> getMessageThread(
String senderId, String receiverId) async {
var config = await _getApiURL();
var url = config.baseUrl + "message/history";
final response = await httpClient.post(url,
headers: {"content-type": "application/json"},
body: json.encode({
"senderId": senderId,
"receiverId": receiverId,
}));
if (response.statusCode == 200) {
_messageList = messageListFromJson(response.body);
} else {
_messageList = [];
}
return _messageList;
}
}
Here is the ui preview to create the message list preview
StreamBuilder<List<MessageModal>> _buildStreamBuilder() {
return StreamBuilder<List<MessageModal>>(
// stream: _messageService.getMessageThread("UID1", "UID2").asStream(),
stream: streamController.counter,
initialData: _messageList,
builder:
(BuildContext context, AsyncSnapshot<List<MessageModal>> snapshot) {
print(snapshot.data);
if (snapshot.hasError) {
print(snapshot.error);
return Center(
child: Text("Something went wrong!"),
);
} else if (snapshot.hasData) {
List<MessageModal> messages = snapshot.data;
return _buildMessageHistory(messages);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
);
}
I need to do the messages update and also keep updating (send the API call and fetch data to stream) the message preview. can anybody help me on this one.
It's been a while since this question was originally asked. Since then the Stream Chat Flutter support has improved a lot. Implementing what this question asks is now really easy, with varying levels of customisability.
Pre-built UI widgets package : https://pub.dev/packages/stream_chat_flutter
This package is plug and play to add chat support, with a lot of customisability options.
If you want more control: https://pub.dev/packages/stream_chat_flutter_core
This package provides convenient builders to enable you to build your own UI components. It does the heavy lifting for you but will require more implementation on your side.
If you want low level control:
https://pub.dev/packages/stream_chat
Check out the tutorial for an easy getting started guide: https://getstream.io/chat/flutter/tutorial/
See here for awesome Stream examples of what you can build: https://github.com/GetStream/flutter-samples
Video tutorials: https://www.youtube.com/playlist?list=PLNBhvhkAJG6t-BxkRAnSqa67lm5C1mpKk

Chrome, recognize open tab

I'm creating an extenstion for google chrome that will perform checking if a stream on twitch.tv is online and will notify the user evey X minutes, I got that covered. What I'm looking for is a JScirpt code that will recognize if user is already on the streamers channel and will stop notifying him.
var username="$user";
setInterval(check,300000);
function check()
{
request("https://api.twitch.tv/kraken/streams/" + username, function() {
var json = JSON.parse(this.response);
if (json.stream == null)
{
chrome.browserAction.setIcon({ path: "offline.png" });
}
else
{
notify();
}
});
return 1;
}
function notify(){
var opt = {type: "basic",title: username + " is streaming!",message: "Click to join!",iconUrl: "start.png"};
chrome.notifications.create("", opt, function(notificationId)
{
setTimeout(function()
{
chrome.notifications.clear(notificationId, function(wasCleared) { console.log(wasCleared); });
}, 3000);
});
chrome.browserAction.setIcon({path:"online.png" });
}
chrome.browserAction.onClicked.addListener(function () {
chrome.tabs.create({ url: "http://www.twitch.tv/"+username });
});
function request(url, func, post)
{
var xhr = new XMLHttpRequest();
xhr.onload = func;
xhr.open(post == undefined ? 'GET' : 'POST', url, true);
xhr.send(post || '');
return 1;
}
check();
Use window.location.href to get the complete URL.
Use window.location.pathname to get URL leaving the host.
You can read more here.

JS and CSS file fails to load when the page is refreshed in grails application which uses Atmosphere Meteor plugin

In my grails 2.3.7 application,
I am using atmosphere-meteor 0.8.3.
On my home page load, I subscribe the client. And by default I run long-polling; and it works fine.
On page refresh, I unsubscribe the client.
However, if I refresh the page; then some of the JS and CSS fails to load. It happens 5 out of 10 times of refresh.
Am I doing anything wrong? (As I subscribe on document.ready()).
Or do I need to do anything else?
Any help is appreciated.
Update:
Code inside gsp for subscription:
$('body').bind('beforeunload',function(){
Jabber.unsubscribe();
});
$(document).ready(function () {
if (typeof atmosphere == 'undefined') {
Jabber.socket = $.atmosphere;
} else {
Jabber.socket = atmosphere;
}
var atmosphereRequest = {
type: 'public',
url: 'atmosphere/public',
trackMessageLength: false
};
//setTimeout(function(){
Jabber.subscribe(atmosphereRequest);
//}, 10000);
});
And the Jabber variable
var Jabber = {
socket: null,
publicSubscription: null,
transport: null,
subscribe: function (options) {
var defaults = {
type: '',
contentType: "application/json",
shared: false,
//transport: 'websocket',
transport: 'long-polling',
fallbackTransport: 'long-polling',
trackMessageLength: true
},
atmosphereRequest = $.extend({}, defaults, options);
console.log(atmosphereRequest);
atmosphereRequest.onOpen = function (response) {
console.log('atmosphereOpen transport: ' + response.transport);
};
atmosphereRequest.onReconnect = function (request, response) {
console.log("atmosphereReconnect");
};
atmosphereRequest.onMessage = function (response) {
console.log("on message");
Jabber.onMessage(response);
};
atmosphereRequest.onError = function (response) {
console.log('atmosphereError: ' + response);
};
atmosphereRequest.onTransportFailure = function (errorMsg, request) {
console.log('atmosphereTransportFailure: ' + errorMsg);
};
atmosphereRequest.onClose = function (response) {
console.log('atmosphereClose: ' + response);
};
switch (options.type) {
case 'public':
Jabber.publicSubscription = Jabber.socket.subscribe(atmosphereRequest);
break;
default:
return false;
}
//Jabber.publicSubscription = Jabber.socket.subscribe(atmosphereRequest);
},
unsubscribe: function () {
if (Jabber.socket)
Jabber.socket.unsubscribe();
},
onMessage:function(response){....}
}
I'm the plugin author. Please update to version 1.0.1. If you still have trouble after updating the plugin, create a new issue. We can work through the problem then. However, I do have a question. When you say the JS fails to load, do you mean the atmosphere JavaScript or your own? There is no plugin related CSS.