Skip to content

Handle timeouts #105

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

Merged
merged 2 commits into from
Apr 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion cmd/list_devices.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cmd

import (
"context"
"fmt"

"github.com/erdaltsksn/cui"
Expand All @@ -24,7 +25,8 @@ var listDevicesCmd = &cobra.Command{
color.Cyan(fmt.Sprintf("\t🎥 %v (%v)\n", partition.Device, utils.CameraGuess(partition.Device)))
}

networkDevices, err := gopro.GetGoProNetworkAddresses()
ctx := context.Background()
networkDevices, err := gopro.GetGoProNetworkAddresses(ctx)
if err != nil {
cui.Error(err.Error())
}
Expand Down
31 changes: 22 additions & 9 deletions pkg/dji/location.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package dji

import (
"bufio"
"io"
"io/ioutil"
"os"
"regexp"
"strconv"
"strings"
Expand All @@ -15,13 +18,20 @@ type LatLongPair struct {
Indicator string
}

var allDrones = map[string]LatLongPair{
"NewMavics": {
type ACType int

const (
NewAircraft ACType = iota
OldAircraft
)

var allDrones = map[ACType]LatLongPair{
NewAircraft: {
Latitude: regexp.MustCompile(`\[latitude[ ]?: ([+-]?(\d+\.?\d*)|(\.\d+))\]`),
Longitude: regexp.MustCompile(`\[long[t]?itude[ ]?: ([+-]?(\d+\.?\d*)|(\.\d+))\]`), // DJI and their typos...
},

"OldMavics": {
OldAircraft: {
Latitude: regexp.MustCompile(`GPS[ ]?\(([+-]?(\d+\.?\d*)|(\.\d+))`),
Longitude: regexp.MustCompile(`,[ ]?([+-]?(\d+\.?\d*)|(\.\d+)),[ ]?\d+\)`),
},
Expand All @@ -41,7 +51,14 @@ func (LocationService) GetLocation(path string) (*utils.Location, error) {
}

func fromSRT(srtPath string) (*utils.Location, error) {
content, err := ioutil.ReadFile(strings.Replace(srtPath, ".MP4", ".SRT", -1))
fs, err := os.Open(strings.Replace(srtPath, ".MP4", ".SRT", -1))
if err != nil {
return nil, err
}
defer fs.Close()
reader := bufio.NewReader(fs)
limitedSizeReader := io.LimitReader(reader, 2048)
content, err := ioutil.ReadAll(limitedSizeReader)
if err != nil {
return nil, err
}
Expand All @@ -51,13 +68,9 @@ func fromSRT(srtPath string) (*utils.Location, error) {
for _, drone := range allDrones {
latMatches := drone.Latitude.FindAllStringSubmatch(string(content), -1)

if len(latMatches) == 0 {
continue
}

lonMatches := drone.Longitude.FindAllStringSubmatch(string(content), -1)

if len(lonMatches) == 0 {
if len(lonMatches) == 0 || len(latMatches) == 0 {
continue
}

Expand Down
1 change: 1 addition & 0 deletions pkg/dji/location_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ func TestParseSRT(t *testing.T) {
"Mini_SE.SRT": 1470,
"mavic_mini.SRT": 145,
"p4_rtk.SRT": 250,
"mavic_air2.srt": 290,
}
fs, err := gitfs.New(ctx, "github.com/JuanIrache/DJI_SRT_Parser/samples",
gitfs.OptGlob("*.srt", "*.SRT"))
Expand Down
10 changes: 0 additions & 10 deletions pkg/generic/generic.go

This file was deleted.

28 changes: 18 additions & 10 deletions pkg/gopro/connect.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package gopro
/* GoPro Connect - API exposed over USB Ethernet */

import (
"context"
"encoding/json"
"fmt"
"log"
Expand Down Expand Up @@ -31,24 +32,26 @@ var (

func handleKill() {
c := make(chan os.Signal, 2)
ctx := context.Background()
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
color.Red("\nKilling program, exiting Turbo mode.")
if gpTurbo {
if err := caller(ipAddress, "gp/gpTurbo?p=0", nil); err != nil {
if err := caller(ctx, ipAddress, "gp/gpTurbo?p=0", nil); err != nil {
color.Red("Could not exit turbo mode")
}
}
os.Exit(0)
}()
}

func caller(ip, path string, object interface{}) error {
func caller(ctx context.Context, ip, path string, object interface{}) error {
req, err := http.NewRequest("GET", fmt.Sprintf("http://%s/%s", ip, path), nil)
if err != nil {
return err
}
req = req.WithContext(ctx)
resp, err := utils.Client.Do(req)
if err != nil {
return err
Expand Down Expand Up @@ -81,12 +84,15 @@ func head(path string) (int, error) {
return length, nil
}

func GetGoProNetworkAddresses() ([]ConnectDevice, error) {
func GetGoProNetworkAddresses(ctx context.Context) ([]ConnectDevice, error) {
ctx, cancelCtx := context.WithTimeout(ctx, 2*time.Second)
defer cancelCtx()
ipsFound := []ConnectDevice{}
ifaces, err := net.Interfaces()
if err != nil {
return ipsFound, err
}

for _, i := range ifaces {
addrs, err := i.Addrs()
if err != nil {
Expand All @@ -98,7 +104,7 @@ func GetGoProNetworkAddresses() ([]ConnectDevice, error) {
if r.MatchString(ipv4Addr.String()) {
correctIP := ipv4Addr.String()[:len(ipv4Addr.String())-1] + "1"
gpInfo := &cameraInfo{}
err := caller(correctIP, "gp/gpControl/info", gpInfo)
err := caller(ctx, correctIP, "gp/gpControl/info", gpInfo)
if err != nil {
continue
}
Expand All @@ -113,8 +119,9 @@ func GetGoProNetworkAddresses() ([]ConnectDevice, error) {
}

func GetMediaList(in string) (*MediaList, error) {
ctx := context.Background()
gpMediaList := &MediaList{}
err := caller(in, "gp/gpMediaList", gpMediaList)
err := caller(ctx, in, "gp/gpMediaList", gpMediaList)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -147,7 +154,8 @@ func ImportConnect(params utils.ImportParams) (*utils.Result, error) {
return nil, mErrors.ErrInvalidSuppliedData(ipAddress)
}
gpInfo := &cameraInfo{}
err := caller(params.Input, "gp/gpControl/info", gpInfo)
ctx := context.Background()
err := caller(ctx, params.Input, "gp/gpControl/info", gpInfo)
if err != nil {
return nil, mErrors.ErrNotFound("Connect camera: " + params.Input)
}
Expand All @@ -169,7 +177,7 @@ func ImportConnect(params utils.ImportParams) (*utils.Result, error) {
// activate turbo

if gpTurbo {
err = caller(params.Input, "gp/gpTurbo?p=1", nil)
err = caller(ctx, params.Input, "gp/gpTurbo?p=1", nil)
if err != nil {
color.Red("Error activating Turbo! Download speeds will be much slower")
}
Expand Down Expand Up @@ -255,7 +263,7 @@ func ImportConnect(params utils.ImportParams) (*utils.Result, error) {

finalPath := utils.GetOrder(params.Sort, locationService, filepath.Join(unsorted, origFilename), params.Output, mediaDate, cameraName)
gpFileInfo := &goProMediaMetadata{}
err = caller(in, fmt.Sprintf("gp/gpMediaMetadata?p=%s/%s&t=v4info", folder, origFilename), gpFileInfo)
err = caller(ctx, in, fmt.Sprintf("gp/gpMediaMetadata?p=%s/%s&t=v4info", folder, origFilename), gpFileInfo)
if err != nil {
inlineCounter.SetFailure(err, origFilename)
return
Expand Down Expand Up @@ -401,7 +409,7 @@ func ImportConnect(params utils.ImportParams) (*utils.Result, error) {
filename := fmt.Sprintf("%s%04d.JPG", filebaseroot, i)

gpFileInfo := &goProMediaMetadata{}
err = caller(params.Input, fmt.Sprintf("gp/gpMediaMetadata?p=%s/%s&t=v4info", folder.D, filename), gpFileInfo)
err = caller(ctx, params.Input, fmt.Sprintf("gp/gpMediaMetadata?p=%s/%s&t=v4info", folder.D, filename), gpFileInfo)
if err != nil {
log.Fatal(err.Error())
}
Expand Down Expand Up @@ -449,7 +457,7 @@ func ImportConnect(params utils.ImportParams) (*utils.Result, error) {
wg.Wait()
progressBar.Shutdown()
if gpTurbo {
if err := caller(params.Input, "gp/gpTurbo?p=0", nil); err != nil {
if err := caller(ctx, params.Input, "gp/gpTurbo?p=0", nil); err != nil {
color.Red("Could not exit turbo mode")
}
}
Expand Down
5 changes: 4 additions & 1 deletion pkg/gopro/detect.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package gopro

import (
"context"

mErrors "github.com/konradit/mmt/pkg/errors"
"github.com/konradit/mmt/pkg/utils"
"github.com/shirou/gopsutil/disk"
Expand All @@ -17,7 +19,8 @@ func Detect() (string, utils.ConnectionType, error) {
}
}

networkDevices, err := GetGoProNetworkAddresses()
ctx := context.Background()
networkDevices, err := GetGoProNetworkAddresses(ctx)
if err != nil {
return "", "", err
}
Expand Down
2 changes: 2 additions & 0 deletions pkg/gopro/mp4parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ func (*HMMT) GetType() mp4.BoxType {
}

func (h *HMMT) GetFieldLength(name string, ctx mp4.Context) uint {
_ = name
_ = ctx
return uint(h.Count)
}

Expand Down
10 changes: 6 additions & 4 deletions pkg/utils/cameras.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,11 @@ func CameraGuess(input string) string {
if err == nil {
return Insta360.ToString()
}

_, err = os.Stat(filepath.Join(input, "MISC", "GIS", "dji.gis"))
if err == nil {
return DJI.ToString()
}
return ""
}

Expand Down Expand Up @@ -199,10 +204,7 @@ func DownloadFile(filepath string, url string, progressbar *mpb.Bar) error {
// Close the file without defer so it can happen before Rename()
out.Close()

if err = os.Rename(filepath+".tmp", filepath); err != nil {
return err
}
return nil
return os.Rename(filepath+".tmp", filepath)
}

func Unzip(src string, dest string) error {
Expand Down
2 changes: 1 addition & 1 deletion pkg/utils/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (

func timeoutFromConfig() int {
key := "network_timeout"
viper.SetDefault(key, 10)
viper.SetDefault(key, 4)
return viper.GetInt(key)
}

Expand Down