Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Video is not playing #181

Open
rahul-s-1110 opened this issue Mar 1, 2024 · 1 comment
Open

Video is not playing #181

rahul-s-1110 opened this issue Mar 1, 2024 · 1 comment

Comments

@rahul-s-1110
Copy link

rahul-s-1110 commented Mar 1, 2024

I'm using
"react-native-video-player": "0.14.0",

and my code is

<VideoPlayer
video={{
uri: 'https://api.mycourtclerk.com/get-files/s3/user-files/337/case-68/evidence/ArqBENKKZVfsbtji19JF0hEiGkILpaARhMyVcXRT.mp4',
}}
videoWidth={1600}
videoHeight={900}
thumbnail={{ uri: 'https://i.picsum.photos/id/866/1600/900.jpg' }}
onError={(err)=>console.log("Error while playing video",err)}
/>

It's showing an blank screen and getting error of
Ios Error : {"error": {"code": -11850, "domain": "AVFoundationErrorDomain", "localizedDescription": "Operation Stopped", "localizedFailureReason": "The server is not correctly configured.", "localizedRecoverySuggestion": ""}, "target": 3097}

Android Error: {"error": {"extra": -2147483648, "what": 1}}

this video in running in browser

my full code is

import React, { useEffect, useRef, useState } from 'react'
import {
Alert,
// eslint-disable-next-line react-native/split-platform-components
PermissionsAndroid,
Platform,
ScrollView,
StyleSheet,
TouchableOpacity,
} from 'react-native'

import { useNavigation } from '@react-navigation/native'
import Config from 'react-native-config'
import FileViewer from 'react-native-file-viewer'
import FlashMessage from 'react-native-flash-message'
import {
DocumentDirectoryPath,
DownloadDirectoryPath,
downloadFile,
DownloadFileOptions,
exists,
} from 'react-native-fs'
import { ActivityIndicator } from 'react-native-paper'
import VideoPlayer from 'react-native-video-player'
import Video from 'react-native-video'

import { appSize } from '@vn.starlingTech/config/AppConstant'
import {
SyncDataType,
useAppContext,
} from '@vn.starlingTech/context/AppContext'
import AppBlock from '@vn.starlingTech/elements/AppBlock'
import AppButton, {
AppProcessingButton,
} from '@vn.starlingTech/elements/AppButton'
import AppImage from '@vn.starlingTech/elements/AppImage'
import AppStyles from '@vn.starlingTech/elements/AppStyles'
import AppText from '@vn.starlingTech/elements/AppText'
import AppTextInput from '@vn.starlingTech/elements/form/AppTextInput'
import { isImage, isVideo } from '@vn.starlingTech/helpers/fileHelper'
import { formatBytes } from '@vn.starlingTech/helpers/formatBytes'
import { getDateTime } from '@vn.starlingTech/helpers/timeHelper'
import light from '@vn.starlingTech/theme/light'

import { AppNavigationProps } from 'app/navigation/params'
import { FileType } from 'app/service/api/evidence.types'
import {
useDeleteFile,
useDownloadFile,
useEditFile,
} from 'app/service/api/file.service'
import IconAdd from 'assets/svg/evidence/IconAdd'
import IconDelete from 'assets/svg/evidence/IconDelete'
import IconDownloadFile from 'assets/svg/evidence/IconDownloadFile'
import IconEdit from 'assets/svg/evidence/IconEdit'
import IconViewFile from 'assets/svg/evidence/IconViewFile'

const ModalFileDetails = ({
infoFile,
onToggleModal,
visible,
}: {
infoFile: FileType
onToggleModal?: () => void
visible?: boolean
}) => {
const flashMsgRef = useRef(null)

const fileName = infoFile?.name?.substring(0, infoFile?.name.lastIndexOf('.'))
const fileExtension = infoFile?.name?.substring(
infoFile?.name.lastIndexOf('.'),
)

const { dispatchSyncData, syncData } = useAppContext()
const navigation = useNavigation()

const [processing, setProcessing] = useState(false)
const [nameEdit, setNameEdit] = useState(fileName)
// const [nameEdit, setNameEdit] = useState(infoFile.name)
const [isEditName, setIsEditName] = useState(false)
const [processingEditName, setProcessingEditName] = useState(false)

const [isDownloaded, setIsDownloaded] = useState(false)

const { mutate: downloadFiles, isLoading: isLoadingDownload } =
useDownloadFile()
const { mutate: deleteFile, isLoading: isLoadingDelete } = useDeleteFile()
const { mutate: editNameFile } = useEditFile()

let fullFileUri = ''

const fileIsImage = isImage(infoFile.ext)
const fileIsVideo = isVideo(infoFile.ext)

if (fileIsImage || fileIsVideo) {
fullFileUri = infoFile.url
if (Config.FILE_PATH) {
fullFileUri = infoFile.url
// fullFileUri = Config.FILE_PATH + infoFile.path
}
}

const { filePath } = getDownloadInfo(infoFile.url)

useEffect(() => {
if (filePath) {
exists(filePath)
.then((downloaded) => {
setIsDownloaded(downloaded)
})
.catch(() => {
setIsDownloaded(false)
})
}
}, [filePath])

const handleDownloadFile = async (): Promise => {
const url = infoFile.url
const options: DownloadFileOptions = {
fromUrl: url,
toFile: filePath,
}

await downloadFile(options)
  .promise.then(() => {
    setIsDownloaded(true)
    openDownloadedFile()
  })
  .then(() => {
    console.log('File should have opened')
  })

}

const onDownloadFile = () => {
downloadFiles(infoFile.id.toString(), {
onSuccess: () => {
// flashMsgRef.current?.showMessage({
// message: 'Download file success',
// type: 'success',
// position: 'center',
// })

    handleDownloadFile()
  },
  onError: () => {
    flashMsgRef.current?.showMessage({
      message: 'Something went wrong',
      type: 'danger',
      position: 'center',
    })
  },
})

}

const onDeleteFile = () => {
deleteFile(infoFile.id.toString(), {
onSuccess: () => {
flashMsgRef.current?.showMessage({
message: 'Delete file success',
type: 'success',
position: 'center',
})

    onToggleModal && onToggleModal()
    handleSyncData()
    // dispatchSyncData({
    //   ...syncData,
    //   evidence: new Date().getTime(),
    //   witness: new Date().getTime(),
    //   journal: new Date().getTime(),
    //   files: new Date().getTime(),
    //   todo: new Date().getTime(),
    //   visitation: new Date().getTime(),
    //   calendarEvent: new Date().getTime(),
    //   document: new Date().getTime(),
    //   voiceMemo: new Date().getTime(),
    // })
  },
  onError: () => {
    flashMsgRef.current?.showMessage({
      message: 'Something went wrong',
      type: 'danger',
      position: 'center',
    })
  },
})

}

const handleEditName = () => {
setIsEditName(true)
}

const onCancel = () => {
setIsEditName(false)
setNameEdit(fileName)
// setNameEdit(infoFile.name)
}

const onEditName = () => {
setProcessingEditName(true)

editNameFile(
  {
    id: infoFile.id.toString(),
    // name: nameEdit,
    name: nameEdit + fileExtension,
  },
  {
    onSuccess: () => {
      flashMsgRef.current?.showMessage({
        message: 'Edit file success',
        type: 'success',
        position: 'center',
      })

      setIsEditName(false)
      handleSyncData()
      // dispatchSyncData({
      //   ...syncData,
      //   evidence: new Date().getTime(),
      //   witness: new Date().getTime(),
      //   journal: new Date().getTime(),
      //   files: new Date().getTime(),
      //   todo: new Date().getTime(),
      //   visitation: new Date().getTime(),
      //   calendarEvent: new Date().getTime(),
      //   document: new Date().getTime(),
      //   voiceMemo: new Date().getTime(),
      // })

      setProcessingEditName(false)
    },
    onError: () => {
      flashMsgRef.current?.showMessage({
        message: 'Something went wrong',
        type: 'danger',
        position: 'center',
      })

      setProcessingEditName(false)
    },
  },
)

}

const handleSyncData = () => {
const statesHistory = navigation.getState()
let _syncData: SyncDataType = {} as SyncDataType
const timing = new Date().getTime()
if (statesHistory.type === 'stack') {
} else {
switch (statesHistory.index) {
case 1:
_syncData.journal = timing
break
case 2:
_syncData.calendarEvent = timing
break
case 3:
_syncData.timeline = timing
break
default:
_syncData.evidence = timing
break
}
}
const prevState = statesHistory.routes[statesHistory.routes.length - 1]
if (prevState) {
switch (prevState.name) {
case 'MyDocuments':
_syncData.document = timing
break
case 'TodoScreen':
_syncData.todo = timing
break
case 'MyWitnessScreen':
_syncData.witness = timing
break
case 'ChatScreen':
_syncData.chat = timing
break
}
dispatchSyncData({
...syncData,
..._syncData,
})
}
}

const handleAddEvidence = () => {
onToggleModal && onToggleModal()

setTimeout(
  () => navigation.navigate('AddEvidenceScreen', { file: infoFile }),
  500,
)

setProcessing(false)

}

const openDownloadedFile = () => {
if (Platform.OS === 'android') {
PermissionsAndroid.requestMultiple([
PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
])
.then((res) => {
const isGranted =
res['android.permission.READ_EXTERNAL_STORAGE'] === 'granted' &&
res['android.permission.WRITE_EXTERNAL_STORAGE'] === 'granted'

      isGranted
        ? FileViewer.open(filePath, {
            showOpenWithDialog: true,
            showAppsSuggestions: true,
          })
        : console.log('Declined')
    })
    .catch((err) => console.log('err', err))
} else {
  FileViewer.open(filePath, {
    showOpenWithDialog: true,
    showAppsSuggestions: true,
  })
}

}

return (


<AppProcessingButton
processing={processing}
onPress={() => handleAddEvidence()}
width={180}
primary
style={styles.flexStart}
>


Add to Evidence

    <AppBlock row center>
      {isDownloaded ? (
        <TouchableOpacity
          style={AppStyles.iconBtn}
          onPress={openDownloadedFile}
        >
          <IconViewFile width={22} />
        </TouchableOpacity>
      ) : isLoadingDownload ? (
        <ActivityIndicator color={light.primary} size="small" />
      ) : (
        <TouchableOpacity
          style={AppStyles.iconBtn}
          onPress={() => onDownloadFile()}
        >
          <IconDownloadFile width={22} />
        </TouchableOpacity>
      )}

      {isLoadingDelete ? (
        <ActivityIndicator color={light.danger} size="small" />
      ) : (
        <TouchableOpacity
          style={AppStyles.iconBtn}
          onPress={() => onDeleteFile()}
        >
          <IconDelete stroke={light.danger} width={22} />
        </TouchableOpacity>
      )}
    </AppBlock>
  </AppBlock>

  {!isEditName ? (
    <AppBlock row mt={20} center>
      <AppText size={14} weight="500" color={light.textSecondary}>
        Name:
      </AppText>
      <AppText
        size={14}
        weight="500"
        mr={7}
        ml={12}
        numberOfLines={1}
        style={AppStyles.fill}
      >
        {fileName}
        {/* {infoFile.name} */}
      </AppText>
      <TouchableOpacity
        onPress={handleEditName}
        style={AppStyles.flatButton}
      >
        <IconEdit width={18} />
      </TouchableOpacity>
    </AppBlock>
  ) : (
    <AppBlock mt={20}>
      <AppText size={14} weight="500" color={light.textSecondary}>
        Name:
      </AppText>
      <AppTextInput
        value={nameEdit}
        autoCapitalize="none"
        onChangeText={setNameEdit}
        inputStyle={{
          borderRadius: appSize(8),
          paddingLeft: appSize(16),
        }}
        inputTextStyle={{ paddingLeft: appSize(12) }}
      />

      <AppBlock row center left mt={21}>
        <AppButton
          text="Cancel"
          textColor={light.text}
          textStyle={styles.textStyle}
          width={100}
          height={38}
          radius={8}
          style={styles.footerButton}
          onPress={onCancel}
        />
        <AppProcessingButton
          disabled={!nameEdit.trim()}
          processing={processingEditName}
          onPress={onEditName}
          text="Save"
          textStyle={styles.textStyle}
          primary
          ml={17}
          width={120}
          height={38}
          radius={8}
          confirm
        />
      </AppBlock>
    </AppBlock>
  )}

  <AppBlock mt={33} row>
    <AppBlock mr={25}>
      <AppText size={14} mb={22} weight="500" color={light.textSecondary}>
        Type of File:
      </AppText>
      <AppText size={14} mb={22} weight="500" color={light.textSecondary}>
        File Size:
      </AppText>
      <AppText size={14} mb={22} weight="500" color={light.textSecondary}>
        Upload On:
      </AppText>
    </AppBlock>
    <AppBlock>
      <AppText color={light.textSecondary} mb={22}>
        {infoFile.ext}
      </AppText>
      <AppText color={light.textSecondary} mb={22}>
        {formatBytes(infoFile.size)}
      </AppText>
      <AppText color={light.textSecondary} mb={22}>
        {getDateTime(
          infoFile.updated_at ? infoFile.updated_at : infoFile.created_at,
        )}
      </AppText>
    </AppBlock>
  </AppBlock>
  {fileIsImage && fullFileUri ? (
    <AppImage
      source={{
        uri: fullFileUri,
      }}
      style={[styles.image, { width: appSize(300), height: appSize(300) }]}
      resizeMode="contain"
    />
  ) : null}
  {visible && fileIsVideo && fullFileUri ? (
    <VideoPlayer
      video={{
        uri: fullFileUri,
      }}
      style={{
        width: appSize(320),
        height: appSize(240),
      }}
      onError={(err)=>console.log("Error while playing video",err)}
    />
  ) : null}
  <FlashMessage ref={flashMsgRef} />
</ScrollView>

)
}

export default ModalFileDetails

function getDownloadInfo(url: string) {
const fileName = url?.substring(url?.lastIndexOf('/') + 1)
return {
fileName,
filePath:
Platform.OS === 'android'
? ${DownloadDirectoryPath}/${fileName}
: ${DocumentDirectoryPath}/${fileName},
}
}

const styles = StyleSheet.create({
flexStart: { alignItems: 'flex-start' },

footerButton: {
backgroundColor: light.surface,
borderColor: light.footerBtnBorder,
borderWidth: appSize(1),
},
image: { marginBottom: appSize(20), width: '100%' },
textStyle: { fontSize: appSize(16), fontWeight: '500' },
})

@vatsmanu
Copy link

add
<VideoPlayer
autoplay={true}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants