Giter Club home page Giter Club logo

megacmd4j's Introduction

MEGAcmd for Java

MEGAcmd for Java

Build Status Maven Central Twitter URL

This is an open source Java library for the mega.nz API, working on top of the MEGAcmd CLI. There is a Quick Start available for developers who want to start using the library right away.

Features

Feature MEGAcmd Description
Start session login Allows to authenticate into the mega api to start running commands using user and password, or sessionID or an exported/public folder
Close session logout Close the current session.
Put content in the Cloud put Upload content to the cloud.
Session Id session Returns the id of the current session.
HTTPS https Shows if HTTPS is used for transfers. Allows enabling and disabling this option.
Idenfity current username whoami Returns the username of the current session.
Make directory mkdir Creates a directory or multiple based on a given remote path.
List files/directories ls List files and directories in a remote path.
Get content get Get the content of files and directories in a remote path.
Copy cp Copy remote files and directories into a new location.
Move mv Move remote files and directories into a new location.
Change password passwd Changes the password of the currently logged user.
Shares folder share Shares/Unshares folder with user
Export to the Internet export Create, delete or list existing public links
Signup user signup Register as user with a given email
Version version Prints MEGAcmd versioning and extra info
Quit quit Quits MEGAcmd. Stops the server without killing the session
Import import Imports the contents of a remote link into user's cloud

If you have any doubt about how each feature works, please run

    MegaClient <MEGAcmd> --help

Additional Features

This features have no corresponding Megacmd command, but they are infered from the existing ones

Count

Show the amount of elements in a folder or that match the query mask. E.g.

    final long amountOfFilesAndDirectories = sessionMega.count("remote/path");

But what if you want to filter that counting and it a Predicate to, for instance, just get the files and not the directories.

    final long amountOfFiles = sessionMega.count("remote/path", FileInfo::isFile);

Exists

This is pretty much the equivalent of java.io.File.exists. It checks if the remote path or mask indicates any non null response. E.g.

    sessionMega.exists("remote/path/filesprefix*.ext");

Export with an expiration date

With a premium mega account, you can export and generate public folder links by setting the option expire date.

    LocalDate expireDate = LocalDate.of(2020, 9, 2);
    final ExportInfo exportInfo = sessionMega.export(exportFolder)
            .setExpireDate(expireDate)
            .call();

or you can just specify a duration using TimeDelay.

    final ExportInfo exportInfo = sessionMega.export(exportFolder)
        .setExpirationTimeDelay(TimeDelay.of(
             Period.ofYears(3).plusMonths(11).plusDays(15)
         ))
        .call();

MEGAcmdServer

Thanks to the class io.github.eliux.mega.MegaServer you can now start and stop the local MEGAcmdServer on command.

System requirements

  • Install MEGAcmd. Available packages for MEGAcmd in all supported platforms should be found here.

Environment variables to set

  • MEGA_EMAIL: Email used as username (lowercase)
  • MEGA_PWD: Corresponding password
  • CMD_TTL_ENV_VAR: Maximum time to live of a running MEGAcmd command. By default, 20 seconds.

Setup your credentials

  1. The most common way to setup your credentials would be using the environment variables MEGA_EMAIL and MEGA_PWD.

  2. Use an existing session can be a saver way. You can use it from your app as long as it don't be closed.

Continuous Integrations

As most OSS projects in github, this one uses Travis CI. I you want a CLI for your project, its recommend to install the correspondent ruby gem:

    gem install travis

For users

  • Once installed MEGAcmd in your system, execute mega-help to check all commands. You will be able to notice those who are already implemented in this library and those who don't. Try them out.

Contributing

Make sure your contact data is included in the Contributors section, and

Contributors

Add your name, email and your account for Twitter, Github or LinkedIn:

Built With

  • Java SDK 8 - Java™ Platform
  • Maven - Dependency Management
  • MEGAcmd - Command Line Interactive and Scriptable Application

Author

License

This project is licensed under the MIT License - see the LICENSE.md file for details

megacmd4j's People

Contributors

ccenyo avatar dependabot[bot] avatar eliux avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

megacmd4j's Issues

Exception in thread "main" io.github.eliux.mega.error.MegaInvalidStateException: Invalid state

Ẁhen I try to use the library and use an account that is running low on storage, it crashes with:

Exception in thread "main" io.github.eliux.mega.error.MegaInvalidStateException: Invalid state
	at io.github.eliux.mega.MegaUtils.handleResult(MegaUtils.java:84)
	at io.github.eliux.mega.cmd.MegaCmdLogin.executeSysCmd(MegaCmdLogin.java:28)
	at io.github.eliux.mega.cmd.AbstractMegaCmdRunner.run(AbstractMegaCmdRunner.java:14)
	at io.github.eliux.mega.auth.MegaAuthCredentials.login(MegaAuthCredentials.java:43)
	at io.github.eliux.mega.Mega.login(Mega.java:33)
	at io.github.eliux.mega.Mega.init(Mega.java:28)

Expected Behavior

It should not crash, even the storage is low

Current Behavior

It crashes

Possible Solution

It seems to have something to do with the "You are running out of available storage banner" that shows up all the time in mega-cmd:

 -----------------------------------------------------------------------------
|                  You are running out of available storage.                  |
|       You can change your account plan to increase your quota limit.        |
|                  See "help --upgrade" for further details.                  |
 -----------------------------------------------------------------------------

Steps to Reproduce

  1. Have an account with low storage
  2. Use Mega#init

Context (Environment)

OS: Linux Mint 19.2
Mega-Cmd: MEGAcmd version: 1.4.0.6: code 1040006

Fix problems when arguments have whitespaces

If you reference a folder that uses whitespaces, e.g. <root path>\folder with spaces\my_text_files.txt, it must be specified between double quotes (") or it wont work. Its needed in local source paths and remote dest paths. It can be reproduced with put command like this:

mega-put -c <root path>\folder with spaces\my_text_files.txt test/folder with spaces

which will fail. Therefore, to make it work, paths should be specified between double quotes, i.e.:

mega-put -c "<root path>\folder with spaces\my_text_files.txt" "test/folder with spaces"

All commands that uses local or remote paths should have this change applied.

Can't login with current Maven build

Environment is Android Studio emulator running Android 8.1 (Oreo)
Using maven package com.github.eliux:megacmd4j:1.2.1-alpha

Problem:
As of the time of writing, 1.2.1-alpha does not permit login to MEGA via the "most common way" in the Quick start guide. If this has already been fixed, please update the Maven repo.

Code shown here:
https://pastebin.com/D2qRpQhQ

Stacktrace is:
com.github.eliux.mega.error.MegaLoginException: Error while executing login command in Mega at com.github.eliux.mega.cmd.MegaCmdLogin.executeSysCmd(MegaCmdLogin.java:31) at com.github.eliux.mega.cmd.AbstractMegaCmdRunnerWithParams.run(AbstractMegaCmdRunnerWithParams.java:8) at com.github.eliux.mega.auth.MegaAuthCredentials.login(MegaAuthCredentials.java:24) at com.github.eliux.mega.Mega$$CC.login$$STATIC$$(Unknown Source:28)

Change remote to remotePath in code

There is an attribute called io.github.eliux.mega.cmd.AbstractMegaCmdPathHandler#remoteFolderCreatedIfNotPresent which has the corresponding related functions:

  • createRemoteIfNotPresent
  • skipIfRemoteNotPresent

It would be more intuitive if a suffix to remote be added, and instead of folder, path be used, e.g.

  • remotePathCreatedIfNotPresent
  • createRemotePathIfNotPresent
  • skipIfRemotePathNotPresent
  • isRemotePathCreatedIfNotPresent

Add commands start and stop

People might need and start and a stop command to manage better the MEGAcmdServer that runs as daemon so MEGAcmd client commands can be used:

  • start: Starts the MEGAcmdServer. It prevent the lazy initialization when the first command is called.
  • stop: Stops the MEGAcmdServer.

First call never ends

Scenario

Whenever I run the tests in my local machine (Windows), they keep running but never eventually ends: no response is given. Nonetheless, if you run them again, everything will go smoothly.

Notes

It doesnt happen in the tests that runs in Travis CI.

Possible source of problems and solution

It would be nice to investigate if there is a workaround to solve this.
When the tests are run in Travis CI, a MEGAcmd help command is called before, saying that the server has started:

Initiating server in background. Log: /home/travis/.megaCmd/megacmdserver.log
So for you to reproduce the error more than once, the MEGAcmd server must be stopped before.
Posible workflows to check how to solve this:

  • Debug the first time its run and check the given response (in console and error code) when the server starts. The codebase will keep the process waiting until that expected response be obtained. This called command can be executed after the session was started.
  • Create a method that initialize the server explicitly. It will required a MEGAcmd issue be fixed or clarified.

uploading issue

Exception in thread "main" io.github.eliux.mega.error.MegaUnexpectedFailureException: Unexpected failure with code 21
	at io.github.eliux.mega.MegaUtils.handleResult(MegaUtils.java:66)
	at io.github.eliux.mega.cmd.AbstractMegaCmdRunner.executeSysCmd(AbstractMegaCmdRunner.java:20)
	at io.github.eliux.mega.cmd.AbstractMegaCmdRunnerWithParams.run(AbstractMegaCmdRunnerWithParams.java:8)
class MEGA(_file: File) {

    private val file: File = _file

    fun upload(): String {
        val sessionMega: MegaSession = try {
            Mega.currentSession()
        } catch (e: MegaException) {
            Mega.login(MegaAuthCredentials(MAIL, PASSWORD))
        }

        sessionMega.uploadFile(file.canonicalPath, "test/").run() // ERROR HERE (dir "test" exists)
        return sessionMega.export("test/${file.name}").call().publicLink
    }

}

Upload doesn't work, creating directories does work.
Using Linux Mint 18, MegaCMD installed.
Thanks in advance ^^

Try to run CI in multiple OS

CI have been running by default in Ubuntu/Debian/Linux. It would be great if it could run in other operative systems like Windows or even Mac, which are supported already by Travis CI.

Standardise CI/CD

I would like to follow a workflow more alike to the Git workflow:

  • PR are merged into the default branch dev, that may require a second integration review
  • A PR is created toward master and if it gets merged then a release is made
  • I could enforce semantic versioning and autogenerate a ChangeLog.

Files containing space do in name do not show up

When calling MegaSession#ls, files containing a space in their name do not show up

Expected Behavior

Files with space in their name should show up

Current Behavior

Files with space in their name do not show up

Steps to Reproduce

  1. Create a file with space in it's name, and one without a space, and upload it to Mega (e.g. touch test123.txt && touch "test 123.txt" && mega-put test\ 123.txt test123.txt /)
  2. Confirm both show up (e.g. mega-ls -la /)
  3. Run sample code:
public class Test {
    public static void main(String[] args) {
        MegaSession session = Mega.init();
        session.ls("/").call().forEach(fi -> {
            System.out.println(fi.getName());
        });
    }
}
  1. Only the file without a space in its name shows up

Issues with the versions

Tests related to the version are failing.

Possible Solution

Checkout if the format of the versions has changed or just make the tests with more flexible expectations about the format of the version.

Steps to Reproduce

This errors are non deterministic ones.

Migrate to JUnit5

What happens?

JUnit 5 provides better ways to run tests in Java and it allows some advantages for labeling tests, specify their order and avoid a non deterministic behaviour. Therefore it should be nice to migrate from JUnit4 to this version.

Expected Behavior

Besides passing, tests should be easier to read and less non-deterministic proof.

Possible solution

Right now, there are too many workarounds for tests to run in a particular order. We could group them in JUnit5 Nested tests and make tests easier to run, maintain and understand.

Support for command errorcode and POSIX compliant error return values

Problem

When this project was initiated the MEGAcmd project returned negative values; but at some OS the returned value was translated to positive values. Such issue was reported and it was solved by adding a new command called errorcode.
Due to this issue all tests that expects right now an Exception are using mostly the generic MegaException instead of an specific one.

Acceptance Criteria

  • Change from MegaException to a more specific exception in tests.
  • Add or tweak tests to provide full coverage to all specialized exceptions.

Create Gradle configuration

I would be nice to handle the dependencies and versioning of the app with gradle and take advantage of Gradle tasks to automate certain things

Expected Behavior

Allow compilation and testing using Gradle

Current Behavior

Right now everything is done with Maven

Possible Solution

Create a Gradle configuration that can be capable of generating new versions in Maven Central

Steps to Reproduce

Compile and test the project with Gradle. When running CI on master Gradle tasks should be in charge of automating the process of changing the version and publishing it to Maven Central, among other things.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.