Git Product home page Git Product logo

cozy-konnector-template's Introduction

Cozy YOUR_SUPER_NEW_KONNECTOR_NAME

What's Cozy?

Cozy Logo

Cozy is a personal data platform that brings all your web services in the same private space. With it, your webapps and your devices can share data easily, providing you with a new experience. You can install Cozy on your own hardware where no one's tracking you.

What is this konnector about ?

This konnector retrieves your SOME_DATA and SOME_OTHER_DATA from SERVICE

YOUR_DESCRIPTION_HERE

Open a Pull-Request

If you want to work on this konnector and submit code modifications, feel free to open pull-requests!
See :

Run and test

Create a konnector-dev-config.json file at the root with your test credentials :

{
  "COZY_URL": "http://cozy.tools:8080",
  "fields": {"login":"[email protected]", "password":"123456"}
}

Then :

yarn
yarn standalone

For running the konnector connected to a Cozy server and more details see konnectors tutorial

Cozy-konnector-libs

This connector uses cozy-konnector-libs. It brings a bunch of helpers to interact with the Cozy server and to fetch data from an online service.

Maintainer

The lead maintainer for this konnector is YOUR_NAME

Get in touch

You can reach the Cozy Community by:

License

YOUR_KONNECTOR_NAME is developed by YOUR_NAME and distributed under the AGPL v3 license.

cozy-konnector-template's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cozy-konnector-template's Issues

Unable to install dependencies

Hi Cozy team.

I can't install dependencies (using yarn or npm) :

 ~/Dev/cozy-konnector | master > yarn install
yarn install v1.12.3
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
error [email protected]: The engine "node" is incompatible with this module. Expected version ">=4 <=9". Got "11.5.0"
error Found incompatible module
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.

I found this issue which seems related. Deleting the same lines in my local yarn.lock fixes the issue :

upath@^1.0.0:
  version "1.0.4"
  resolved "https://registry.yarnpkg.com/upath/-/upath-1.0.4.tgz#ee2321ba0a786c50973db043a50b7bcba822361d"
  integrity sha512-d4SJySNBXDaQp+DPrziv3xGS6w3d2Xt69FijJr86zMPBy23JEloMCEOUBBzuN7xCtjLCnmB9tI/z7SBCahHBOw==

An error in the code sample

While writing the getting-started documentation, I faced an error in the scrape call:

Given the following HTML markup from http://books.toscrape.com/

<article class="product_pod">
  <div class="image_container">
    <a href="catalogue/a-light-in-the-attic_1000/index.html">
      <img src="media/cache/2c/da/2cdad67c44b002e7ead0cc35693c0e8b.jpg" alt="A Light in the Attic" class="thumbnail">
    </a>
  </div>
  <p class="star-rating Three">
    <i class="icon-star"></i>
    <i class="icon-star"></i>
    <i class="icon-star"></i>
    <i class="icon-star"></i>
    <i class="icon-star"></i>
  </p>
  <h3>
    <a href="catalogue/a-light-in-the-attic_1000/index.html" title="A Light in the Attic">A Light in the ...</a>
  </h3>
  <div class="product_price">
    <p class="price_color">£51.77</p>
    <p class="instock availability">
      <i class="icon-ok"></i>
      In stock
    </p>
    <form>
      <button type="submit" class="btn btn-primary btn-block" data-loading-text="Adding...">Add to basket</button>
    </form>
  </div>
</article>

The scrape call computes a wrong url value:

url: {
sel: 'h3 a',
attr: 'title',
parse: url => `${baseUrl}/${url}`
},

The result will be:

{
  "title": "A Light in the Attic",
  "amount": 51.77,
  "url": "http://books.toscrape.com/A Light in the Attic",
  "fileurl": "http://books.toscrape.com/media/cache/2c/da/2cdad67c44b002e7ead0cc35693c0e8b.jpg",
  "filename": "A Light in the Attic.jog"
}

So we must change the code to:

url: {
        sel: 'h3 a',
        attr: 'href',
        parse: url => `${baseUrl}/${url}`
      },

So the result could be:

{
  "title": "A Light in the Attic",
  "amount": 51.77,
  "url": "http://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html",
  "fileurl": "http://books.toscrape.com/media/cache/2c/da/2cdad67c44b002e7ead0cc35693c0e8b.jpg",
  "filename": "A Light in the Attic.jog"
}

request-promise doesn't run the same way in konnector

If I run the following code with node ., it works flawlessly

const rp = require('request-promise');
const qs = require('querystring');
const moment = require('moment');
const cookiejar = rp.jar();

//require('request-debug')(rp);

const username = '*******';
const password = '*******';
const startDate = moment().subtract(1, 'day').format('DD/MM/YYYY');
const endDate = moment().format('DD/MM/YYYY');

main();

async function main() {
    try {
        await authenticate(username, password);
        await getData();
    } catch (error) {
        console.error(error);
    }
}

function authenticate(username, password) {

    const authRequest = {
        method: 'POST',
        uri: 'https://espace-client-connexion.enedis.fr/auth/UI/Login',
        jar: cookiejar,
        headers: {
            'Host': 'espace-client-connexion.enedis.fr',
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        form: {
            IDToken1: username,
            IDToken2: password,
            goto: 'aHR0cHM6Ly9lc3BhY2UtY2xpZW50LXBhcnRpY3VsaWVycy5lbmVkaXMuZnIv',
            SunQueryParamsString: 'cmVhbG09cGFydGljdWxpZXJz',
            encoded: true,
        },
        followAllRedirects: true
    };

    // Reset Content-Length header since Enedis auth wants Title-Cased Headers
    const authRequestLength = Buffer.byteLength(qs.stringify(authRequest.form));
    authRequest.headers['Content-Length'] = authRequestLength;
    return rp(authRequest);
}

async function getData() {
    const dataRequest = {
        method: 'POST',
        uri: 'https://espace-client-particuliers.enedis.fr/group/espace-particuliers/suivi-de-consommation?p_p_id=lincspartdisplaycdc_WAR_lincspartcdcportlet&p_p_lifecycle=2&p_p_resource_id=urlCdcHeure',
        jar: cookiejar,
        headers: {
            'Referer': 'https://espace-client-particuliers.enedis.fr/group/espace-particuliers/suivi-de-consommation',
        },
        form: {
            _lincspartdisplaycdc_WAR_lincspartcdcportlet_dateDebut: startDate,
            _lincspartdisplaycdc_WAR_lincspartcdcportlet_dateFin: endDate,
        },
        json: true
    }
    try {
        const response = await rp(dataRequest);
        const start = response.graphe.periode.dateDebut;
        const loadProfile = response.graphe.data.map(value => { return { load: value.valeur, time: moment(start, 'DD/MM/YYYY').add((value.ordre - 1) * 0.5, 'hour').format() }; });
        console.dir(loadProfile, { depth: null });
        return loadProfile;
    } catch (error) {
        console.error(error);
    }
}

response is

[ { load: -2, time: '2018-11-18T00:00:00+01:00' },
  ...,
  { load: 0.656, time: '2018-11-18T13:00:00+01:00' },
  { load: 0.946, time: '2018-11-18T13:30:00+01:00' },
  { load: 0.436, time: '2018-11-18T14:00:00+01:00' },
  { load: 0.55, time: '2018-11-18T14:30:00+01:00' },
  { load: 0.322, time: '2018-11-18T15:00:00+01:00' },
  { load: 0.734, time: '2018-11-18T15:30:00+01:00' },
  { load: 0.404, time: '2018-11-18T16:00:00+01:00' },
  { load: 0.226, time: '2018-11-18T16:30:00+01:00' },
  { load: 0.156, time: '2018-11-18T17:00:00+01:00' },
 ...,
  { load: 0.122, time: '2018-11-18T23:30:00+01:00' } ]

But if I try to put it in a konnector start function and launch it with yarn standalone, the auth fails (redirection loop), event if the logged request is exactly the same :
Code :

const { BaseKonnector, log } = require('cozy-konnector-libs')

const rp = require('request-promise')
const qs = require('querystring')
const moment = require('moment')
const cookiejar = rp.jar()

require('request-debug')(rp)

module.exports = new BaseKonnector(start)

async function start(fields) {
  log('info', 'Authenticating ...')
  try {
    await authenticate(fields.username, fields.password)
    log('info', 'Successfully logged in')
    log('info', 'Getting data')
    await getData()
  } catch (error) {
    console.error(error)
  }
  log('info', 'Saving data to Cozy')
}

const startDate = moment()
  .subtract(1, 'day')
  .format('DD/MM/YYYY')
const endDate = moment().format('DD/MM/YYYY')

function authenticate(username, password) {
  const authRequest = {
    method: 'POST',
    uri: 'https://espace-client-connexion.enedis.fr/auth/UI/Login',
    jar: cookiejar,
    headers: {
      Host: 'espace-client-connexion.enedis.fr',
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    form: {
      IDToken1: username,
      IDToken2: password,
      goto: 'aHR0cHM6Ly9lc3BhY2UtY2xpZW50LXBhcnRpY3VsaWVycy5lbmVkaXMuZnIv',
      SunQueryParamsString: 'cmVhbG09cGFydGljdWxpZXJz',
      encoded: true
    },
    followAllRedirects: true
  }

  // Reset Content-Length header since Enedis auth wants Title-Cased Headers
  const authRequestLength = Buffer.byteLength(qs.stringify(authRequest.form))
  authRequest.headers['Content-Length'] = authRequestLength
  return rp(authRequest)
}

async function getData() {
  const dataRequest = {
    method: 'POST',
    uri:
      'https://espace-client-particuliers.enedis.fr/group/espace-particuliers/suivi-de-consommation?p_p_id=lincspartdisplaycdc_WAR_lincspartcdcportlet&p_p_lifecycle=2&p_p_resource_id=urlCdcHeure',
    jar: cookiejar,
    headers: {
      Referer:
        'https://espace-client-particuliers.enedis.fr/group/espace-particuliers/suivi-de-consommation'
    },
    form: {
      _lincspartdisplaycdc_WAR_lincspartcdcportlet_dateDebut: startDate,
      _lincspartdisplaycdc_WAR_lincspartcdcportlet_dateFin: endDate
    },
    json: true
  }
  try {
    const response = await rp(dataRequest)
    const start = response.graphe.periode.dateDebut
    const loadProfile = response.graphe.data.map(value => {
      return {
        load: value.valeur,
        time: moment(start, 'DD/MM/YYYY')
          .add((value.ordre - 1) * 0.5, 'hour')
          .format()
      }
    })
    console.dir(loadProfile, { depth: null })
    return loadProfile
  } catch (error) {
    console.error(error)
  }
}

Logged request :

 request:
   { debugId: 1,
     uri: 'https://espace-client-connexion.enedis.fr/auth/UI/Login',
     method: 'POST',
     headers:
      { Host: 'espace-client-connexion.enedis.fr',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': 181 },
     body: 'IDToken1=***username***&IDToken2=***password***&goto=aHR0cHM6Ly9lc3BhY2UtY2xpZW50LXBhcnRpY3VsaWVycy5lbmVkaXMuZnIv&SunQueryParamsString=cmVhbG09cGFydGljdWxpZXJz&encoded=true' } }

Does konnector alter the working of request-promise in any way ?

PS : The SunQueryParamsString: 'cmVhbG09cGFydGljdWxpZXJz' bit reference a hidden field <input type="hidden" name="SunQueryParamsString" value="cmVhbG09cGFydGljdWxpZXJz" /> in the authentication page. It would be better to fetch the value of this field with cheerio in case it changes. I'm writing this just in case someone would be interested in writting a connector based on my code...

Use async/await in the example

On the assumption than async/await is easier to understand than promises and supported by Node 8.

Was already done ><

Avoid submission of credentials to the github repo

At the moment, data/env.js is followed by git and when doing git ci -a we get the risk to submit our credentials to github :-(

Proposition :

  • Rename the data directory to conf directory
  • Rename conf/env.js to conf/env.js.template
  • Ignore only conf/env.js
  • Display a proper error message when conf/env.js does not exist
  • Create a new data directory which is still ignored in the .gitignore and will still be used to save imported files in standalone mode

Supprimer la commande yarn deploy:prod

On pourrait optimiser les commandes de déploiements, dans le fichier pachage.jsonil y a actuellement ceci :

"deploy": "git-directory-deploy --directory build/ --branch build --repo=${DEPLOY_REPOSITORY:-https://[email protected]/konnectors/cozy-konnector-nef.git}",
"deploy:prod": "git-directory-deploy --directory build/ --branch prod --repo=${DEPLOY_REPOSITORY:-https://[email protected]/konnectors/cozy-konnector-nef.git}",

Les 2 commandes sont vraiment identiques, avec seulement un nom de branche qui change...

Je proposerai bien d'avoir une seul commande:

"deploy": "git-directory-deploy --directory build/ --branch=${DEPLOY_BRANCH:-build} --repo=${DEPLOY_REPOSITORY:-https://[email protected]/konnectors/cozy-konnector-nef.git}"

Ca veut dire que l'on doit changer package.json et .travis.yml.

Vous en pensez quoi ?

Update CONTRIBUTING.md file

This file is cloned from connector-template to every connector and repeat the same old story.

The only places which specify the project name are in the title and in example git commands.

To remove frictions when a new connector is created from this template, we should reformulate this file with generic information as there is no need to be specific inside it.

Documentation is not consistent on `npm` and `yarn`

README.md uses indistinctively npm and yarn in command line.
I am not enough familiar with these tools and your habits to open a PR to sort this up.
According to what I have read elsewhere, I assume yarn should be used everywhere instead of npm.

Cannot run `yarn test` after git clone

After a fresh clone :

$ yarn test
...
Error: Cannot find module 'rxjs/Rx'
    at Function.Module._resolveFilename (module.js:536:15)
    at Function.Module._load (module.js:466:25)
    at Module.require (module.js:579:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/pbrowne/code/cozy/konn-paybyphone/node_modules/konitor/node_modules/inquirer/lib/ui/prompt.js:3:10)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Repository problems

These problems occurred while renovating this repository. View logs.

  • WARN: Using npm packages for Renovate presets is now deprecated. Please migrate to repository-based presets instead.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

npm
package.json
  • cozy-konnector-libs 5.11.0
  • cozy-jobs-cli 2.4.2
  • cozy-konnector-build 1.7.0
travis
.travis.yml
  • node 20

  • Check this box to trigger a request for Renovate to run again on this repository

Npm run standalone and npm run dev are not clear in what they do

npm run standalone actually runs the konnector without needing an accessible cozy. Because of the "standalone" name, we could think that it does not need a internet connection

Propositions : npm run nocozy or npm run nostack

npm run dev actually runs the connector in development mode by logging into the cozy through OAuth authentication, without being installed in the cozy.

Propositions : npm run noinstall or npm run oauth

Cannot run `yarn standalone`

Steps to reproduce

git clone https://github.com/konnectors/cozy-konnector-template cozy-konnector-newservice
cd cozy-konnector-newservice
rm -rf .git
git init
yarn install 
yarn standalone

throws

TypeError: Cannot read property 'folderPath' of undefined
@ ./node_modules/cozy-konnector-libs/dist/helpers/cozy-client-js-stub.js:171
    DUMP_PATH = path.join(KONNECTOR_DEV_CONFIG.fields.folderPath || rootPath, DUMP_PATH);

Configuration

yarn 1.12.3
macOS Mojave
cozy-connector-template@4854003cad50a1338dc3ba3d93f8b15d4974b851

Change CODEOWNERS file

As mentioned here: https://help.github.com/articles/about-codeowners/ this file is used to automatically set reviewers in a PR.
Today this file list a certain number of developers and it is hard to maintain.
If we set it to the @konnectors/maintainers team, it will be easier to maintain the members list automatically added as reviewers, etc.

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: Cannot find preset's package (cozy-libs). Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

Payslips download doesn't work anymore

As reported here konnectors/lucca#137


My payslip for april has been downloaded under the name 2019_04.pdf but the content isn't a PDF, the content is :

{
  "message": "No HTTP resource was found that matches the request URI 'http://MYCOMPANY.ilucca.net/pagga/download/DOCUMENT_ID'."
}

I manually downloaded the payslip from Lucca and the download URL was https://MYCOMPANY.ilucca.net/pagga/services/download/DOCUMENT_ID

I think the URL should be changed

https://github.com/konnectors/lucca/blob/b306a954dfe6b7715d5082477e77e4c583060a4c/src/index.js#L111

-    const url = companyInstanceUrl + '/pagga/download/' + payslip.id
+    const url = companyInstanceUrl + '/pagga/services/download/' + payslip.id

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.