first cmmit

This commit is contained in:
Miguel Lopez 2022-07-08 11:44:32 +02:00
commit 2554f03923
1519 changed files with 272567 additions and 0 deletions

27
README.md Normal file
View File

@ -0,0 +1,27 @@
# E4link Sample Project
## Introduction
This sample project gives you the boilerplate code you need to connect to an Empatica E4 device and start streaming data.
The sample application implemented in the project has very simple functionalities:
- It initializes the E4link library with your API key.
- If the previous step is successful, it starts scanning for Empatica devices, till it finds one that can be used with the API key you inserted in the code.
- When such a device has been found, the app connects to the devices and streams data for 10 seconds, then it disconnects.
## Setup
- Clone / download this repository.
- Open the sample project in Android Studio.
- Make sure you have a valid API key. You can request one for your Empatica Connect account from our [Developer Area][1].
- Edit `MainActivity.java` and assign your API key to the `EMPATICA_API_KEY` constant .
- Download the Android E4 link 1.0 or newer SDK from our [Developer Area][1].
- Unzip the archive you've downloaded and copy the `.aar` file you'll find inside into the `libs` folder contained in the sample project.
- Build and run the project.
- If a device is in range and its light is blinking green, but the app doesn't connect, please check that the discovered device can be used with your API key. If the `allowed` parameter is always false, the device is not linked to your API key. Please check your [Developer Area][1].
If you need any additional information about the Empatica API for Android, please check the [official documentation][2].
[1]: https://www.empatica.com/connect/developer.php
[2]: http://developer.empatica.com

1
app/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/build

91
app/build.gradle Normal file
View File

@ -0,0 +1,91 @@
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
android {
compileSdkVersion 31
useLibrary 'org.apache.http.legacy'
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'mozilla/public-suffix-list.txt'
}
defaultConfig {
applicationId 'com.empatica.empalinksample'
minSdkVersion 19
targetSdkVersion 30
versionCode 2323
versionName "1.2"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
buildFeatures {
viewBinding true
}
}
//// DE-COMMENT THIS IF YOU HAVE ISSUES AT RUNTIME, CRASHING WITH java.lang.UnsatisfiedLinkError
//android {
//
// splits {
//
// // Configures multiple APKs based on ABI.
// abi {
//
// // Enables building multiple APKs per ABI.
// enable true
//
// // By default all ABIs are included, so use reset() and include to specify that we only
// // want APKs for x86, armeabi-v7a, and mips.
//
// // Resets the list of ABIs that Gradle should create APKs for to none.
// reset()
//
// // Specifies a list of ABIs that Gradle should create APKs for.
// include 'armeabi-v7a', 'x86', 'x86_64' // de-comment this to test on emulator
// // include 'armeabi-v7a'
//
// // Specifies that we do not want to also generate a universal APK that includes all ABIs.
// universalApk false
// }
// }
//}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.empatica.empalink:E4link:1.0.0@aar'
implementation 'com.squareup.okhttp:okhttp:2.7.5'
implementation platform('com.google.firebase:firebase-bom:29.1.0')
implementation 'com.google.firebase:firebase-analytics:20.1.0'
implementation 'com.google.firebase:firebase-storage:20.0.0'
implementation 'com.google.firebase:firebase-auth:21.0.1'
implementation 'com.google.firebase:firebase-firestore:24.0.1'
implementation 'androidx.multidex:multidex:2.0.1'
implementation 'com.google.firebase:firebase-database:20.0.3'
implementation 'androidx.recyclerview:recyclerview:1.2.1'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'com.google.firebase:firebase-crashlytics-buildtools:2.8.1'
implementation 'com.google.http-client:google-http-client-android:+'
implementation 'com.google.api-client:google-api-client-android:+'
implementation 'com.google.api-client:google-api-client-gson:+'
implementation 'com.squareup.okhttp3:okhttp:4.7.2'
implementation 'com.android.volley:volley:1.1.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
implementation 'androidx.navigation:navigation-fragment:2.3.5'
implementation 'androidx.navigation:navigation-ui:2.3.5'
implementation 'com.google.android.material:material:1.5.0-alpha02'
}

69
app/google-services.json Normal file
View File

@ -0,0 +1,69 @@
{
"project_info": {
"project_number": "800514867625",
"firebase_url": "https://empaticae4-3e023-default-rtdb.europe-west1.firebasedatabase.app",
"project_id": "empaticae4-3e023",
"storage_bucket": "empaticae4-3e023.appspot.com"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:800514867625:android:991bb941fb5f3d87df44b8",
"android_client_info": {
"package_name": "com.empatica.empalinksample"
}
},
"oauth_client": [
{
"client_id": "800514867625-i7rbc19o1ndunjim276j4us3tkake405.apps.googleusercontent.com",
"client_type": 3
}
],
"api_key": [
{
"current_key": "AIzaSyAGCef7cUf5-b0CPiZMb1ZkiZN6JVKitRo"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": [
{
"client_id": "800514867625-i7rbc19o1ndunjim276j4us3tkake405.apps.googleusercontent.com",
"client_type": 3
}
]
}
}
},
{
"client_info": {
"mobilesdk_app_id": "1:800514867625:android:ba61c3e2e28c1c8adf44b8",
"android_client_info": {
"package_name": "com.example.prueba"
}
},
"oauth_client": [
{
"client_id": "800514867625-i7rbc19o1ndunjim276j4us3tkake405.apps.googleusercontent.com",
"client_type": 3
}
],
"api_key": [
{
"current_key": "AIzaSyAGCef7cUf5-b0CPiZMb1ZkiZN6JVKitRo"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": [
{
"client_id": "800514867625-i7rbc19o1ndunjim276j4us3tkake405.apps.googleusercontent.com",
"client_type": 3
}
]
}
}
}
],
"configuration_version": "1"
}

View File

@ -0,0 +1 @@
COPY HERE THE EMPALINK LIBRARY

17
app/proguard-rules.pro vendored Normal file
View File

@ -0,0 +1,17 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /Users/andrea/Library/Android/sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

View File

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.empatica.sample">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat.NoActionBar"
android:usesCleartextTraffic="true"
tools:replace="android:theme">
<activity
android:name=".LoginActivity"
android:label="@string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity" />
<activity android:name=".UsersActivity" />
<activity android:name=".ProfileActivity" />
<activity android:name=".SavedSessionsActivity" />
<activity android:name=".RegisterActivity" />
</application>
</manifest>

View File

@ -0,0 +1,64 @@
package com.empatica.domain;
import java.io.Serializable;
public class Acceleration implements Serializable{
private String key;
private int acc_x;
private int acc_y;
private int acc_z;
private double timestamp;
public Acceleration(){}
public int getAcc_x() {
return acc_x;
}
public void setAcc_x(int acc_x) {
this.acc_x = acc_x;
}
public int getAcc_y() {
return acc_y;
}
public void setAcc_y(int acc_y) {
this.acc_y = acc_y;
}
public int getAcc_z() {
return acc_z;
}
public void setAcc_z(int acc_z) {
this.acc_z = acc_z;
}
public double getTimestamp() {
return timestamp;
}
public void setTimestamp(double timestamp) {
this.timestamp = timestamp;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Acceleration(String key, int acc_x, int acc_y, int acc_z, double timestamp) {
this.key = key;
this.acc_x = acc_x;
this.acc_y = acc_y;
this.acc_z = acc_z;
this.timestamp = timestamp;
}
}

View File

@ -0,0 +1,43 @@
package com.empatica.domain;
import java.io.Serializable;
public class BVP implements Serializable{
private String key;
private float bvp;
private double timestamp;
public BVP(){}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public BVP(String key, float bvp, double timestamp){
this.key=key;
this.bvp=bvp;
this.timestamp=timestamp;
}
public float getBvp() {
return bvp;
}
public void setBvp(float bvp) {
this.bvp = bvp;
}
public double getTimestamp() {
return timestamp;
}
public void setTimestamp(double timestamp) {
this.timestamp = timestamp;
}
}

View File

@ -0,0 +1,34 @@
package com.empatica.domain;
import java.io.Serializable;
public class Click implements Serializable {
public String getDateInit() {
return dateInit;
}
public void setDateInit(String dateInit) {
this.dateInit = dateInit;
}
public String getDateEnd() {
return dateEnd;
}
public void setDateEnd(String dateEnd) {
this.dateEnd = dateEnd;
}
public Click(String dateInit, String dateEnd) {
this.dateInit = dateInit;
this.dateEnd = dateEnd;
}
public Click(){}
private String dateInit;
private String dateEnd;
}

View File

@ -0,0 +1,72 @@
package com.empatica.domain;
import java.io.Serializable;
public class Data {
private float bvp;
private float gsr;
private float temp;
private float acc_x;
private float acc_y;
private float acc_z;
public float getBvp() {
return bvp;
}
public void setBvp(float bvp) {
this.bvp = bvp;
}
public float getGsr() {
return gsr;
}
public void setGsr(float gsr) {
this.gsr = gsr;
}
public float getTemp() {
return temp;
}
public void setTemp(float temp) {
this.temp = temp;
}
public float getAcc_x() {
return acc_x;
}
public void setAcc_x(float acc_x) {
this.acc_x = acc_x;
}
public float getAcc_y() {
return acc_y;
}
public void setAcc_y(float acc_y) {
this.acc_y = acc_y;
}
public float getAcc_z() {
return acc_z;
}
public void setAcc_z(float acc_z) {
this.acc_z = acc_z;
}
public Data(float bvp, float gsr, float temp, float acc_x, float acc_y, float acc_z) {
this.bvp = bvp;
this.gsr = gsr;
this.temp = temp;
this.acc_x = acc_x;
this.acc_y = acc_y;
this.acc_z = acc_z;
}
public Data(){}
}

View File

@ -0,0 +1,41 @@
package com.empatica.domain;
import java.io.Serializable;
public class GSR implements Serializable {
private String key;
private float gsr;
private double timestamp;
public GSR(){}
public float getGsr() {
return gsr;
}
public void setGsr(float gsr) {
this.gsr = gsr;
}
public double getTimestamp() {
return timestamp;
}
public void setTimestamp(double timestamp) {
this.timestamp = timestamp;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public GSR(String key, float gsr, double timestamp) {
this.key = key;
this.gsr = gsr;
this.timestamp = timestamp;
}
}

View File

@ -0,0 +1,41 @@
package com.empatica.domain;
import java.io.Serializable;
public class IBI implements Serializable {
private String key;
private float ibi;
private double timestamp;
public IBI(){}
public float getIbi() {
return ibi;
}
public void setIbi(float ibi) {
this.ibi = ibi;
}
public double getTimestamp() {
return timestamp;
}
public void setTimestamp(double timestamp) {
this.timestamp = timestamp;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public IBI(String key,float ibi, double timestamp) {
this.key = key;
this.ibi = ibi;
this.timestamp = timestamp;
}
}

View File

@ -0,0 +1,63 @@
package com.empatica.domain;
import java.io.Serializable;
public class SuperUser implements Serializable {
private String email;
private String pass;
private String name;
private String gender;
private String age;
public SuperUser(){}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public SuperUser(String email, String age, String gender, String name, String pass) {
this.email = email;
this.age = age;
this.gender = gender;
this.name = name;
this.pass = pass;
}
}

View File

@ -0,0 +1,41 @@
package com.empatica.domain;
import java.io.Serializable;
public class Temperature implements Serializable {
private String key;
private float temp;
private double timestamp;
public Temperature(){}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Temperature(String key, float temp, double timestamp) {
this.key = key;
this.temp = temp;
this.timestamp = timestamp;
}
public float getTemp() {
return temp;
}
public void setTemp(float temp) {
this.temp = temp;
}
public double getTimestamp() {
return timestamp;
}
public void setTimestamp(double timestamp) {
this.timestamp = timestamp;
}
}

View File

@ -0,0 +1,82 @@
package com.empatica.sample;
import androidx.recyclerview.widget.RecyclerView;
import androidx.cardview.widget.CardView;
import android.content.Context;
import android.os.storage.StorageManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.lang.invoke.MethodType;
import java.util.List;
//A class to handle the recycler view
public class AdapterUsers extends RecyclerView.Adapter<AdapterUsers.MyViewHolder> {
private OnItemClickListener clickListener;
private List<String> listUsers;
private Context ctx;
public AdapterUsers(List<String> listUsers, Context ctx) {
this.listUsers=listUsers;
this.ctx=ctx;
}
//Create new views (invoked by the layout manager)
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
LayoutInflater inflater = LayoutInflater.from(ctx);
View view = inflater.inflate(R.layout.list_layout, null);
view.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));
return new MyViewHolder(view, clickListener);
}
//Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(MyViewHolder holder, int position){
//holder.cardView.setAnimation(AnimationUtils.loadAnimation(ctx,R.anim.item_fall_down));
String name = listUsers.get(position);
holder.textViewName.setText(name);
}
//Return the size of the dataset
@Override
public int getItemCount(){return listUsers.size();}
public interface OnItemClickListener{
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
clickListener = listener;
}
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView textViewName;
CardView cardView;
public MyViewHolder(View itemView, OnItemClickListener listener){
super(itemView);
textViewName = itemView.findViewById(R.id.textName);
cardView = itemView.findViewById(R.id.card_view);
itemView.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
if(listener != null){
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
listener.onItemClick(position);
}
}
}
});
}
}
}

View File

@ -0,0 +1,110 @@
package com.empatica.sample;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.empatica.domain.SuperUser;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
//A class to handle the users login activity
public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
private EditText editTextEmail;
private EditText editTextPassword;
private Button buttonLogin;
private Button buttonRegister;
private String email="";
private String pass="";
private SuperUser superUser;
private FirebaseAuth firebaseAuth;
private DatabaseReference databaseReference;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
editTextEmail=(EditText) findViewById(R.id.editTextEmail);
editTextPassword=(EditText) findViewById(R.id.editTextPassword);
buttonLogin=(Button) findViewById(R.id.buttonLogin);
buttonRegister=(Button)findViewById(R.id.buttonRegister);
firebaseAuth = FirebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance("https://empaticae4-3e023-default-rtdb.europe-west1.firebasedatabase.app").getReference();
buttonLogin.setOnClickListener(this);
buttonRegister.setOnClickListener(this);
}
//Check if the values of 'email' and 'pass' are correct in the data base
private void loginUser(){
firebaseAuth.signInWithEmailAndPassword(email,pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
getUser();
}else{
Toast.makeText(LoginActivity.this,"wrong labels",Toast.LENGTH_SHORT).show();
}
}
});
}
//2 options, login or register. If the user click on register goes to the activity of register. If the user click on login
//the variables 'email' and 'pass' take the values of the editText and calls the function loginUser
@Override
public void onClick(View v){
switch (v.getId()){
case R.id.buttonRegister:
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
case R.id.buttonLogin:
email =editTextEmail.getText().toString();
pass = editTextPassword.getText().toString();
if (!email.isEmpty()&&!pass.isEmpty()){
loginUser();
}else{
Toast.makeText(LoginActivity.this,"Empty label",Toast.LENGTH_SHORT).show();
}
}
}
//take the user and send it to the other activity
private void getUser(){
email = firebaseAuth.getCurrentUser().getEmail().substring(0,firebaseAuth.getCurrentUser().getEmail().indexOf("@"));
databaseReference.child("superUser").child(email).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
superUser = snapshot.getValue(SuperUser.class);
Intent main = new Intent(LoginActivity.this,UsersActivity.class);
Bundle bundleMain = new Bundle();
bundleMain.putSerializable("superUser", superUser);
bundleMain.putSerializable("layout",1);
main.putExtras(bundleMain);
startActivity(main);
//finish();
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
}

View File

@ -0,0 +1,565 @@
package com.empatica.sample;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.le.ScanCallback;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.empatica.domain.Acceleration;
import com.empatica.domain.GSR;
import com.empatica.domain.IBI;
import com.empatica.domain.SuperUser;
import com.empatica.domain.Temperature;
import com.empatica.domain.Click;
import com.empatica.empalink.ConnectionNotAllowedException;
import com.empatica.empalink.EmpaDeviceManager;
import com.empatica.empalink.EmpaticaDevice;
import com.empatica.empalink.config.EmpaSensorStatus;
import com.empatica.empalink.config.EmpaSensorType;
import com.empatica.empalink.config.EmpaStatus;
import com.empatica.empalink.delegate.EmpaDataDelegate;
import com.empatica.empalink.delegate.EmpaStatusDelegate;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.empatica.domain.BVP;
import com.google.firebase.database.ValueEventListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class MainActivity extends AppCompatActivity implements EmpaDataDelegate, EmpaStatusDelegate {
private static final String TAG = "MainActivity";
private static final int REQUEST_ENABLE_BT = 1;
private static final int REQUEST_PERMISSION_ACCESS_COARSE_LOCATION = 1;
private static final String EMPATICA_API_KEY = "dfb56ca6b87841bd88b2bc5b076bba0f"; // TODO insert your API Key here
private EmpaDeviceManager deviceManager = null;
private TextView accel_xLabel;
private TextView accel_yLabel;
private TextView accel_zLabel;
private TextView bvpLabel;
private TextView edaLabel;
private TextView ibiLabel;
private TextView temperatureLabel;
private TextView batteryLabel;
private TextView statusLabel;
private TextView deviceNameLabel;
private LinearLayout dataCnt;
private DatabaseReference databaseReference;
private FirebaseDatabase firebaseDatabase;
private String nameUser;
private SuperUser superUser;
private ArrayList<String> listsession;
private String session;
private String currentDateandTimeInit;
private String currentDateandTimeEnd;
private boolean firstSession=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize vars that reference UI components
statusLabel = (TextView) findViewById(R.id.status);
dataCnt = (LinearLayout) findViewById(R.id.dataArea);
accel_xLabel = (TextView) findViewById(R.id.accel_x);
accel_yLabel = (TextView) findViewById(R.id.accel_y);
accel_zLabel = (TextView) findViewById(R.id.accel_z);
bvpLabel = (TextView) findViewById(R.id.bvp);
edaLabel = (TextView) findViewById(R.id.eda);
ibiLabel = (TextView) findViewById(R.id.ibi);
temperatureLabel = (TextView) findViewById(R.id.temperature);
batteryLabel = (TextView) findViewById(R.id.battery);
deviceNameLabel = (TextView) findViewById(R.id.deviceName);
firebaseDatabase = FirebaseDatabase.getInstance("https://empaticae4-3e023-default-rtdb.europe-west1.firebasedatabase.app");
databaseReference = firebaseDatabase.getReference();
final Button disconnectButton = findViewById(R.id.disconnectButton);
Bundle extra = getIntent().getExtras();
nameUser = (String) extra.getSerializable("user");
superUser = (SuperUser) extra.getSerializable("superUser");
getSession();
disconnectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (deviceManager != null) {
// Get the timestamp when the user disconnect the wristbrand
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
currentDateandTimeEnd = sdf.format(new Date());
deviceManager.disconnect();
}
}
});
initEmpaticaDeviceManager();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_PERMISSION_ACCESS_COARSE_LOCATION:
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission was granted, yay!
initEmpaticaDeviceManager();
} else {
// Permission denied, boo!
final boolean needRationale = ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION);
new AlertDialog.Builder(this)
.setTitle("Permission required")
.setMessage("Without this permission bluetooth low energy devices cannot be found, allow it in order to connect to the device.")
.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// try again
if (needRationale) {
// the "never ask again" flash is not set, try again with permission request
initEmpaticaDeviceManager();
} else {
// the "never ask again" flag is set so the permission requests is disabled, try open app settings to enable the permission
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
}
})
.setNegativeButton("Exit application", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// without permission exit is the only way
finish();
}
})
.show();
}
break;
}
}
private void initEmpaticaDeviceManager() {
// Android 6 (API level 23) now require ACCESS_COARSE_LOCATION permission to use BLE
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_PERMISSION_ACCESS_COARSE_LOCATION);
} else {
if (TextUtils.isEmpty(EMPATICA_API_KEY)) {
new AlertDialog.Builder(this)
.setTitle("Warning")
.setMessage("Please insert your API KEY")
.setNegativeButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// without permission exit is the only way
finish();
}
})
.show();
return;
}
// Create a new EmpaDeviceManager. MainActivity is both its data and status delegate.
deviceManager = new EmpaDeviceManager(getApplicationContext(), this, this);
// Initialize the Device Manager using your API key. You need to have Internet access at this point.
deviceManager.authenticateWithAPIKey(EMPATICA_API_KEY);
}
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (deviceManager != null) {
deviceManager.cleanUp();
}
}
@Override
protected void onStop() {
super.onStop();
if (deviceManager != null) {
deviceManager.stopScanning();
}
}
@Override
public void didDiscoverDevice(EmpaticaDevice bluetoothDevice, String deviceName, int rssi, boolean allowed) {
// Check if the discovered device can be used with your API key. If allowed is always false,
// the device is not linked with your API key. Please check your developer area at
// https://www.empatica.com/connect/developer.php
Log.i(TAG, "didDiscoverDevice" + deviceName + "allowed: " + allowed);
if (allowed) {
// Stop scanning. The first allowed device will do.
deviceManager.stopScanning();
try {
// Connect to the device
deviceManager.connectDevice(bluetoothDevice);
updateLabel(deviceNameLabel, "To: " + deviceName);
} catch (ConnectionNotAllowedException e) {
// This should happen only if you try to connect when allowed == false.
Toast.makeText(MainActivity.this, "Sorry, you can't connect to this device", Toast.LENGTH_SHORT).show();
Log.e(TAG, "didDiscoverDevice" + deviceName + "allowed: " + allowed + " - ConnectionNotAllowedException", e);
}
}
}
@Override
public void didFailedScanning(int errorCode) {
/*
A system error occurred while scanning.
@see https://developer.android.com/reference/android/bluetooth/le/ScanCallback
*/
switch (errorCode) {
case ScanCallback.SCAN_FAILED_ALREADY_STARTED:
Log.e(TAG,"Scan failed: a BLE scan with the same settings is already started by the app");
break;
case ScanCallback.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED:
Log.e(TAG,"Scan failed: app cannot be registered");
break;
case ScanCallback.SCAN_FAILED_FEATURE_UNSUPPORTED:
Log.e(TAG,"Scan failed: power optimized scan feature is not supported");
break;
case ScanCallback.SCAN_FAILED_INTERNAL_ERROR:
Log.e(TAG,"Scan failed: internal error");
break;
default:
Log.e(TAG,"Scan failed with unknown error (errorCode=" + errorCode + ")");
break;
}
}
@Override
public void didRequestEnableBluetooth() {
// Request the user to enable Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
@Override
public void bluetoothStateChanged() {
// E4link detected a bluetooth adapter change
// Check bluetooth adapter and update your UI accordingly.
boolean isBluetoothOn = BluetoothAdapter.getDefaultAdapter().isEnabled();
Log.i(TAG, "Bluetooth State Changed: " + isBluetoothOn);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// The user chose not to enable Bluetooth
if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
// You should deal with this
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void didUpdateSensorStatus(@EmpaSensorStatus int status, EmpaSensorType type) {
didUpdateOnWristStatus(status);
}
@Override
public void didUpdateStatus(EmpaStatus status) {
// Update the UI
updateLabel(statusLabel, status.name());
// The device manager is ready for use
if (status == EmpaStatus.READY) {
updateLabel(statusLabel, status.name() + " - Turn on your device");
// Start scanning
deviceManager.startScanning();
// The device manager has established a connection
hide();
} else if (status == EmpaStatus.CONNECTED) {
// Get the timestamp when the user connect the wristbrand
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
currentDateandTimeInit = sdf.format(new Date());
show();
// The device manager disconnected from a device
} else if (status == EmpaStatus.DISCONNECTED) {
String email = superUser.getEmail();
if(firstSession==true) { // Check if is the first session of the user
databaseReference.child("users").child(email).child(nameUser).removeValue();
}
Click click = new Click();
click.setDateInit(currentDateandTimeInit);
click.setDateEnd(currentDateandTimeEnd);
// Store the timestamp of connect and disconnect in the data base
databaseReference.child("users").child(email).child(nameUser).child(session).setValue(click);
updateLabel(deviceNameLabel, "");
hide();
}
}
// Receive the acceleration of the wristband
@Override
public void didReceiveAcceleration(int x, int y, int z, double timestamp) {
Acceleration acc = new Acceleration();
updateLabel(accel_xLabel, "" + x);
updateLabel(accel_yLabel, "" + y);
updateLabel(accel_zLabel, "" + z);
String email = superUser.getEmail();
acc.setAcc_x(x);
acc.setAcc_y(y);
acc.setAcc_z(z);
acc.setTimestamp(timestamp);
Date date = new Date((long)timestamp*1000);
String year = getYear(date.getYear());
String month = getMonth(date.getMonth());
String day = getDay();
String hour = String.valueOf(date.getHours());
String minute = String.valueOf(date.getMinutes());
String second = String.valueOf(date.getSeconds());
// Store the acceleration with the date in the data base
databaseReference.child("acceleration").child(email).child(nameUser).child(session).child(year).child(month).child(day).child(hour).child(minute).child(second).push().setValue(acc);
}
// Receive the BVP of the wristband
@Override
public void didReceiveBVP(float bvp, double timestamp) {
BVP classbvp = new BVP();
updateLabel(bvpLabel, "" + bvp);
String email = superUser.getEmail();
classbvp.setBvp(bvp);
classbvp.setTimestamp(timestamp);
Date date = new Date((long)timestamp*1000);
String year = getYear(date.getYear());
String month = getMonth(date.getMonth());
String day = getDay();
String hour = String.valueOf(date.getHours());
String minute = String.valueOf(date.getMinutes());
String second = String.valueOf(date.getSeconds());
// Store the BVP with the date in the data base
databaseReference.child("bvp").child(email).child(nameUser).child(session).child(year).child(month).child(day).child(hour).child(minute).child(second).push().setValue(classbvp);
}
@Override
public void didReceiveBatteryLevel(float battery, double timestamp) {
updateLabel(batteryLabel, String.format("%.0f %%", battery * 100));
}
// Receive the GSR of the wristband
@Override
public void didReceiveGSR(float gsr, double timestamp) {
GSR classgsr = new GSR();
updateLabel(edaLabel, "" + gsr);
String email = superUser.getEmail();
classgsr.setGsr(gsr);
classgsr.setTimestamp(timestamp);
Date date = new Date((long)timestamp*1000);
String year = getYear(date.getYear());
String month = getMonth(date.getMonth());
String day = getDay();
String hour = String.valueOf(date.getHours());
String minute = String.valueOf(date.getMinutes());
String second = String.valueOf(date.getSeconds());
// Store the GSR with the date in the data base
databaseReference.child("gsr").child(email).child(nameUser).child(session).child(year).child(month).child(day).child(hour).child(minute).child(second).push().setValue(classgsr);
}
// Receive the IBI of the wristband
@Override
public void didReceiveIBI(float ibi, double timestamp) {
IBI classibi = new IBI();
updateLabel(ibiLabel, "" + ibi);
String email = superUser.getEmail();
classibi.setIbi(ibi);
classibi.setTimestamp(timestamp);
Date date = new Date((long)timestamp*1000);
String year = getYear(date.getYear());
String month = getMonth(date.getMonth());
String day = getDay();
String hour = String.valueOf(date.getHours());
String minute = String.valueOf(date.getMinutes());
String second = String.valueOf(date.getSeconds());
// Store the IBI with the date in the data base
databaseReference.child("ibi").child(email).child(nameUser).child(session).child(year).child(month).child(day).child(hour).child(minute).child(second).push().setValue(classibi);
}
// Receive the temperature of the wristband
@Override
public void didReceiveTemperature(float temp, double timestamp) {
Temperature classtemp = new Temperature();
updateLabel(temperatureLabel, "" + temp);
String email = superUser.getEmail();
classtemp.setTemp(temp);
classtemp.setTimestamp(timestamp);
Date date = new Date((long)timestamp*1000);
String year = getYear(date.getYear());
String month = getMonth(date.getMonth());
String day = getDay();
String hour = String.valueOf(date.getHours());
String minute = String.valueOf(date.getMinutes());
String second = String.valueOf(date.getSeconds());
// Store the temperature with the date in the data base
databaseReference.child("temp").child(email).child(nameUser).child(session).child(year).child(month).child(day).child(hour).child(minute).child(second).push().setValue(classtemp);
}
public String getYear(int year){
return String.valueOf(year+1900);
}
public String getMonth(int month){
if(month==12){
month=1;
}else{
month=month+1;
}
return String.valueOf(month);
}
public String getDay(){
SimpleDateFormat sdf = new SimpleDateFormat("dd");
String dia = sdf.format(new Date());
return dia;
}
// Check if is the first session of the user for change the first value of the data base because to create the user
// in firebase needs to create with min one child, in this case the session 0
private void getSession(){
String email = superUser.getEmail();
databaseReference.child("users").child(email).child(nameUser).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
listsession = new ArrayList<>();
int ss;
if (snapshot.exists()) {
for (DataSnapshot ds : snapshot.getChildren()) {
String s =ds.getKey().toString();
listsession.add(s);
}
if (listsession.get(0).equals("0")){
ss=0;
firstSession=true;
}else{
ss=listsession.size();
}
ss++;
session=String.valueOf(ss);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
// Update a label with some text, making sure this is run in the UI thread
private void updateLabel(final TextView label, final String text) {
runOnUiThread(new Runnable() {
@Override
public void run() {
label.setText(text);
}
});
}
@Override
public void didReceiveTag(double timestamp) {
}
@Override
public void didEstablishConnection() {
show();
}
@Override
public void didUpdateOnWristStatus(@EmpaSensorStatus final int status) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (status == EmpaSensorStatus.ON_WRIST) {
((TextView) findViewById(R.id.wrist_status_label)).setText("ON WRIST");
}
else {
((TextView) findViewById(R.id.wrist_status_label)).setText("NOT ON WRIST");
}
}
});
}
void show() {
runOnUiThread(new Runnable() {
@Override
public void run() {
dataCnt.setVisibility(View.VISIBLE);
}
});
}
void hide() {
runOnUiThread(new Runnable() {
@Override
public void run() {
dataCnt.setVisibility(View.INVISIBLE);
}
});
}
}

View File

@ -0,0 +1,42 @@
package com.empatica.sample;
import android.content.Context;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class MySingleton {
private static MySingleton instance;
private RequestQueue requestQueue;
private static Context ctx;
private MySingleton(Context context) {
ctx = context;
requestQueue = getRequestQueue();
}
public static synchronized MySingleton getInstance(Context context) {
if (instance == null) {
instance = new MySingleton(context);
}
return instance;
}
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
requestQueue = Volley.newRequestQueue(ctx.getApplicationContext());
}
return requestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
}

View File

@ -0,0 +1,65 @@
package com.empatica.sample;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.empatica.domain.SuperUser;
import java.io.IOException;
//A class to handle 2 possible options, click on saved sessions or click on create new session
public class ProfileActivity extends AppCompatActivity implements View.OnClickListener{
private SuperUser superUser;
private String name;
private Button buttonSaved;
private Button buttonSession;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
buttonSession = (Button) findViewById(R.id.buttonSession);
buttonSaved = (Button) findViewById(R.id.buttonSaved);
Bundle extra = getIntent().getExtras();
superUser = (SuperUser) extra.getSerializable("superUser");
name = (String) extra.getSerializable("user");
buttonSaved.setOnClickListener(this);
buttonSession.setOnClickListener(this);
}
@Override
public void onClick(View v){
switch (v.getId()){
case R.id.buttonSaved:
Intent main1 = new Intent(ProfileActivity.this, UsersActivity.class);
Bundle bundleMain = new Bundle();
bundleMain.putSerializable("superUser", superUser);
bundleMain.putSerializable("user",name);
bundleMain.putSerializable("layout",2);
main1.putExtras(bundleMain);
startActivity(main1);
//finish();
case R.id.buttonSession:
Intent main2 = new Intent(ProfileActivity.this, MainActivity.class);
bundleMain = new Bundle();
bundleMain.putSerializable("superUser", superUser);
bundleMain.putSerializable("user",name);
main2.putExtras(bundleMain);
startActivity(main2);
//finish();
}
}
}

View File

@ -0,0 +1,114 @@
package com.empatica.sample;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.empatica.domain.SuperUser;
import com.google.android.gms.tasks.OnCanceledListener;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{
private Button buttonRegister;
private EditText editTextEmail;
private EditText editTextPassword;
private EditText editTextPasswordRepeat;
private EditText editTextName;
private EditText editTextGender;
private EditText editTextAge;
private FirebaseAuth firebaseAuth;
private DatabaseReference databaseReference;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
editTextEmail=(EditText) findViewById(R.id.editTextEmail);
editTextPassword=(EditText) findViewById(R.id.editTextPassword);
editTextPasswordRepeat=(EditText)findViewById(R.id.editTextPasswordRepeat);
editTextAge=(EditText)findViewById(R.id.editTextAge);
editTextGender=(EditText)findViewById(R.id.editTextGender);
editTextName=(EditText)findViewById(R.id.editTextName);
buttonRegister=(Button)findViewById(R.id.buttonRegister);
firebaseAuth = FirebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance("https://empaticae4-3e023-default-rtdb.europe-west1.firebasedatabase.app").getReference();
buttonRegister.setOnClickListener(this);
}
@Override
public void onClick(View v){
switch (v.getId()){
case R.id.buttonRegister:
String email = editTextEmail.getText().toString();
String pass = editTextPassword.getText().toString();
String repass= editTextPasswordRepeat.getText().toString();
String name=editTextName.getText().toString();
String age=editTextAge.getText().toString();
String gender=editTextGender.getText().toString();
if(!email.isEmpty()&&!pass.isEmpty()&&!repass.isEmpty()&&!name.isEmpty()&&!age.isEmpty()&&!gender.isEmpty()){
//got the values
if(pass.equals(repass)){
//password matched
if(pass.length()>6){
firebaseAuth.createUserWithEmailAndPassword(email,pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
//user created
SuperUser superUser = new SuperUser();
String email2= email.substring(0,email.indexOf("@"));
superUser.setEmail(email2);
superUser.setPass(pass);
superUser.setAge(age);
superUser.setGender(gender);
superUser.setEmail(name);
databaseReference.child("superUser").child(email2).setValue(superUser);
startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
finish();
}else{
//Something went wrong
Toast.makeText(RegisterActivity.this,"Something went wrong please try again", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
//Failed
Toast.makeText(RegisterActivity.this,"Error: "+e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnCanceledListener(new OnCanceledListener() {
@Override
public void onCanceled() {
Toast.makeText(RegisterActivity.this,"Canceled, try again!", Toast.LENGTH_SHORT).show();
}
})
;
}else{
//pass length short
Toast.makeText(RegisterActivity.this,"Password must be 6 character long", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(RegisterActivity.this,"Password must be the same", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(RegisterActivity.this,"Empty labels", Toast.LENGTH_SHORT).show();
}
}
}
}

View File

@ -0,0 +1,584 @@
package com.empatica.sample;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.TableLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.checkerframework.checker.units.qual.A;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.empatica.domain.Acceleration;
import com.empatica.domain.BVP;
import com.empatica.domain.Data;
import com.empatica.domain.GSR;
import com.empatica.domain.SuperUser;
import com.empatica.domain.Temperature;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
//A class to display the data of the session in a table
public class SavedSessionsActivity extends AppCompatActivity {
private TableLayout tableLayout;
private TableDynamic tableDynamic;
private TextView textViewMood;
private String[] header = {"Time","BVP (BPM)", "GSR (µS)", "Temperature (ºC)","Acceleration x","Acceleration y","Acceleration z"};
private ArrayList<String[]> rows = new ArrayList<>();
private DatabaseReference databaseReference;
private ArrayList<String> listTemp, listBvp, listGsr, listAccx, listAccy, listAccz, listTime;
private ArrayList<String> avgTemp, avgBvp, avgGsr, avgAccx, avgAccy, avgAccz;
private SuperUser superUser;
private String name;
private String session;
private String s, yearI, yearE, monthI, monthE, dayI, dayE, hourI="", hourE, minutI="", minutE, secondI="", secondE; //Variables of initial and end of the time
private int ints, intyearI, intyearE, intmonthI, intmonthE, intdayI, intdayE, inthourI, inthourE, intminutI, intminutE, intsecondI, intsecondE;
private String postBodyString;
private MediaType mediaType;
private RequestBody requestBody;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_table);
databaseReference = FirebaseDatabase.getInstance("https://empaticae4-3e023-default-rtdb.europe-west1.firebasedatabase.app").getReference();
Bundle extra = getIntent().getExtras();
superUser = (SuperUser) extra.getSerializable("superUser");
name = (String) extra.getSerializable("user");
session = (String) extra.getSerializable("session");
textViewMood = (TextView) findViewById(R.id.textViewMood);
tableLayout = (TableLayout) findViewById(R.id.table);
tableDynamic = new TableDynamic(tableLayout, getApplicationContext());
getDate(); //Initialize the variables yearI, yearE, etc
avgAccx = new ArrayList<>();
avgAccy = new ArrayList<>();
avgAccz = new ArrayList<>();
avgTemp = new ArrayList<>();
avgBvp = new ArrayList<>();
avgGsr = new ArrayList<>();
listTime = new ArrayList<>();
ints=Integer.parseInt(s);
intyearI=Integer.parseInt(yearI);
intmonthI=Integer.parseInt(monthI);
intdayI=Integer.parseInt(dayI);
inthourI=Integer.parseInt(hourI);
intminutI=Integer.parseInt(minutI);
intsecondI=Integer.parseInt(secondI);
intyearE=Integer.parseInt(yearE);
intmonthE=Integer.parseInt(monthE);
intdayE=Integer.parseInt(dayE);
inthourE=Integer.parseInt(hourE);
intminutE=Integer.parseInt(minutE);
intsecondE=Integer.parseInt(secondE);
getAcc();
getBvp();
getGsr();
getTemp();
}
//Get accelerometer data but only the session data, from start time to end time of the session
private void getAcc() {
String email = superUser.getEmail();
for(int i=intyearI; i<=intyearE;i++){
for(int j=intmonthI; j<=intmonthE;j++){
for(int k=intdayI; k<=intdayE; k++){
for(int l=inthourI; l<=inthourE; l++){
for(int m=intminutI; m<=intminutE; m++){
for(int p = intsecondI; p<intsecondE; p++) {
databaseReference.child("acceleration").child(email).child(name).child(s).child(String.valueOf(i)).child(String.valueOf(j)).child(String.valueOf(k)).child(String.valueOf(l)).child(String.valueOf(m)).child(String.valueOf(p)).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
listAccx = new ArrayList<>();
listAccy = new ArrayList<>();
listAccz = new ArrayList<>();
if (snapshot.exists()) {
for (DataSnapshot ds : snapshot.getChildren()) {
Acceleration acc = ds.getValue(Acceleration.class);
String datax = String.valueOf(acc.getAcc_x());
String datay = String.valueOf(acc.getAcc_y());
String dataz = String.valueOf(acc.getAcc_z());
listAccx.add(datax);
listAccy.add(datay);
listAccz.add(dataz);
}
}
//Calculates the average of all data collected in one second
Double a=AVG(listAccx);
avgAccx.add(String.valueOf(Math.round(a*100.0)/100.0));
Double b=AVG(listAccy);
avgAccy.add(String.valueOf(Math.round(b*100.0)/100.0));
Double c=AVG(listAccz);
avgAccz.add(String.valueOf(Math.round(c*100.0)/100.0));
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
}
}
}
}
}
}
//Get BVP data but only the session data, from start time to end time of the session
private void getBvp(){
String email = superUser.getEmail();
for(int i=intyearI; i<=intyearE;i++){
for(int j=intmonthI; j<=intmonthE;j++){
for(int k=intdayI; k<=intdayE; k++){
for(int l=inthourI; l<=inthourE; l++){
for(int m=intminutI; m<=intminutE; m++){
for(int p = intsecondI; p<intsecondE; p++) {
int finalI = i;
int finalJ = j;
int finalK = k;
int finalP = p;
int finalM = m;
int finalL = l;
databaseReference.child("bvp").child(email).child(name).child(s).child(String.valueOf(i)).child(String.valueOf(j)).child(String.valueOf(k)).child(String.valueOf(l)).child(String.valueOf(m)).child(String.valueOf(p)).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
listBvp = new ArrayList<>();
if (snapshot.exists()) {
for (DataSnapshot ds : snapshot.getChildren()) {
BVP bvp = ds.getValue(BVP.class);
String data = String.valueOf(bvp.getBvp());
listBvp.add(data);
}
}
//Calculates the average of all data collected in one second
Double a=AVG(listBvp);
avgBvp.add(String.valueOf(Math.round(a*100.0)/100.0));
String stamp =String.valueOf(finalK)+"-"+String.valueOf(finalJ)+"-"+String.valueOf(finalI)+" "+String.valueOf(finalL)+":"+String.valueOf(finalM)+":"+String.valueOf(finalP);
listTime.add(stamp);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
}
}
}
}
}
}
//Get GSR data but only the session data, from start time to end time of the session
private void getGsr(){
String email = superUser.getEmail();
for(int i=intyearI; i<=intyearE;i++){
for(int j=intmonthI; j<=intmonthE;j++){
for(int k=intdayI; k<=intdayE; k++){
for(int l=inthourI; l<=inthourE; l++){
for(int m=intminutI; m<=intminutE; m++){
for(int p = intsecondI; p<intsecondE; p++) {
databaseReference.child("gsr").child(email).child(name).child(s).child(String.valueOf(i)).child(String.valueOf(j)).child(String.valueOf(k)).child(String.valueOf(l)).child(String.valueOf(m)).child(String.valueOf(p)).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
listGsr = new ArrayList<>();
if (snapshot.exists()) {
for (DataSnapshot ds : snapshot.getChildren()) {
GSR gsr = ds.getValue(GSR.class);
String data = String.valueOf(gsr.getGsr());
listGsr.add(data);
}
}
//Calculates the average of all data collected in one second
Double a=AVG(listGsr);
avgGsr.add(String.valueOf(Math.round(a*100.0)/100.0));
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
}
}
}
}
}
}
//Get temperature data but only the session data, from start time to end time of the session
private void getTemp(){
String email = superUser.getEmail();
for(int i=intyearI; i<=intyearE;i++){
for(int j=intmonthI; j<=intmonthE;j++){
for(int k=intdayI; k<=intdayE; k++){
for(int l=inthourI; l<=inthourE; l++){
for(int m=intminutI; m<=intminutE; m++){
for(int p = intsecondI; p<intsecondE; p++) {
databaseReference.child("temp").child(email).child(name).child(s).child(String.valueOf(i)).child(String.valueOf(j)).child(String.valueOf(k)).child(String.valueOf(l)).child(String.valueOf(m)).child(String.valueOf(p)).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
listTemp = new ArrayList<>();
if (snapshot.exists()) {
for (DataSnapshot ds : snapshot.getChildren()) {
Temperature temp = ds.getValue(Temperature.class);
String data = String.valueOf(temp.getTemp());
listTemp.add(data);
}
//Calculates the average of all data collected in one second
Double a = AVG(listTemp);
avgTemp.add(String.valueOf(Math.round(a * 100.0) / 100.0));
if (avgTemp.size() == avgBvp.size()) {
tableDynamic.addHeader(header); //Create header of the table
try {
tableDynamic.addData(getData()); //Add data to the table
} catch (JSONException e) {
e.printStackTrace();
}
tableDynamic.backgroundHeader(Color.rgb(62, 151, 169)); //Set the color of the header
tableDynamic.backgroundData(Color.rgb(164, 233, 247), Color.rgb(220, 220, 220)); //Set the color of the data
tableDynamic.lineColor(Color.BLACK); //Color of the table borders
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
}
}
}
}
}
}
//Get the time of the String for initialize the variables
private void getDate(){
String d="";
for(int i = 0, n = session.length() ; i < n ; i++) {
char c = session.charAt(i);
d=d.concat(String.valueOf(c));
switch (d){
case "Session: ":
d="";
i++;
s=String.valueOf(session.charAt(i));
i++;
break;
case "Init: ":
i++;
d="";
int dot=0;
for(int j = i; j<n; j++ ){
c = session.charAt(j);
String m= String.valueOf(c);
if(m.equals(".")||m.equals(" "))
dot++;
else
d=d.concat(String.valueOf(c));
switch (dot){
case 1:
yearI = d;
d="";
dot++;
break;
case 3:
monthI = d;
d="";
dot++;
break;
case 5:
dayI = d;
d="";
i=j;
j=n;
break;
}
}
break;
case "d.C. at ":
i++;
dot=0;
d="";
for(int j = i; j<n; j++ ){
c = session.charAt(j);
String m= String.valueOf(c);
if(m.equals(":")||m.equals(" "))
dot++;
else
d=d.concat(String.valueOf(c));
switch (dot){
case 1:
if (hourI=="")
hourI = d;
else
hourE=d;
d="";
dot++;
break;
case 3:
if (minutI=="")
minutI=d;
else
minutE=d;
d="";
dot++;
break;
case 5:
if (secondI=="")
secondI = d;
else
secondE = d;
d="";
i=j;
j=n;
break;
}
}
break;
case "CET End: ":
i++;
dot=0;
d="";
for(int j = i; j<n; j++ ){
c = session.charAt(j);
String m= String.valueOf(c);
if(m.equals(".")||m.equals(" "))
dot++;
else
d=d.concat(String.valueOf(c));
switch (dot){
case 1:
yearE = d;
d="";
dot++;
break;
case 3:
monthE = d;
d="";
dot++;
break;
case 5:
dayE = d;
d="";
i=j;
j=n;
break;
}
}
break;
case "CEST End: ":
i++;
dot=0;
d="";
for(int j = i; j<n; j++ ){
c = session.charAt(j);
String m= String.valueOf(c);
if(m.equals(".")||m.equals(" "))
dot++;
else
d=d.concat(String.valueOf(c));
switch (dot){
case 1:
yearE = d;
d="";
dot++;
break;
case 3:
monthE = d;
d="";
dot++;
break;
case 5:
dayE = d;
d="";
i=j;
j=n;
break;
}
}
break;
}
}
}
//Function to calculate the average
private Double AVG(ArrayList<String> listAvg){
double sum=0;
for(int i=0; i<listAvg.size(); i++){
sum=sum+Double.parseDouble(listAvg.get(i));
}
return sum/listAvg.size();
}
//Function to create the table
private ArrayList<String[]> getData() throws JSONException {
String email =superUser.getEmail();
JSONObject jsonObject = new JSONObject();
JSONArray jsonArrayAccx = new JSONArray();
JSONArray jsonArrayAccy = new JSONArray();
JSONArray jsonArrayAccz = new JSONArray();
JSONArray jsonArrayBvp = new JSONArray();
JSONArray jsonArrayGsr = new JSONArray();
JSONArray jsonArrayTemp = new JSONArray();
for(int i=0;i<avgBvp.size();i++){
//Generates the rows
rows.add(new String[]{listTime.get(i),avgBvp.get(i),avgGsr.get(i),avgTemp.get(i),avgAccx.get(i),avgAccy.get(i),avgAccz.get(i)});
Data classData = new Data();
String time =listTime.get(i);
classData.setBvp(Float.valueOf(avgBvp.get(i)));
classData.setGsr(Float.valueOf(avgGsr.get(i)));
classData.setTemp(Float.valueOf(avgTemp.get(i)));
classData.setAcc_x(Float.valueOf(avgAccx.get(i)));
classData.setAcc_y(Float.valueOf(avgAccy.get(i)));
classData.setAcc_z(Float.valueOf(avgAccz.get(i)));
//Store the average in data base
databaseReference.child("avg").child(email).child(name).child(time).setValue(classData);
//Create jsonArrays for send to the server
jsonArrayAccx.put(avgAccx.get(i));
jsonArrayAccy.put(avgAccy.get(i));
jsonArrayAccz.put(avgAccz.get(i));
jsonArrayBvp.put(avgBvp.get(i));
jsonArrayGsr.put(avgGsr.get(i));
jsonArrayTemp.put(avgTemp.get(i));
}
jsonObject.put("acc_x",jsonArrayAccx);
jsonObject.put("acc_y",jsonArrayAccy);
jsonObject.put("acc_z",jsonArrayAccz);
jsonObject.put("bvp",jsonArrayBvp);
jsonObject.put("eda",jsonArrayGsr);
jsonObject.put("temp",jsonArrayTemp);
//postRequest("your message here", url);
getMood(jsonObject);
return rows;
}
private void getMood(JSONObject jsonObject){
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, "http://192.168.43.115:5000/", jsonObject,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response){
String p="The mood is ";
JSONArray jsonArrayIndex = new JSONArray();
JSONArray jsonArrayData = new JSONArray();
ArrayList percent = new ArrayList();
ArrayList index = new ArrayList();
try{
jsonArrayIndex = response.getJSONArray("index");
jsonArrayData = response.getJSONArray("data");
for(int i =0;i<jsonArrayData.length();i++){
JSONArray jsonPercent = jsonArrayData.getJSONArray(i);
double n = (double) jsonPercent.get(1);
percent.add(Math.round(n));
index.add(jsonArrayIndex.get(i));
}
}catch (JSONException e) {
throw new RuntimeException(e);
}
for(int i=0;i<index.size();i++){
switch (index.get(i).toString()){
case "1.0":
p=p+"Baseline: "+percent.get(i).toString()+"%\n";
break;
case "2.0":
p=p+"Stress: "+percent.get(i).toString()+"%\n";
break;
case "3.0":
p=p+"Amusement: "+percent.get(i).toString()+"%\n";
break;
case "4.0":
p=p+"Meditation: "+percent.get(i).toString()+"%\n";
break;
}
}
textViewMood.setText(p);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
textViewMood.setText("Error getting response");
}
});
/*jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));*/
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
//requestQueue.add(jsonObjectRequest);
//OkHttpClient okHttpClient = new OkHttpClient();
//MediaType JSON = MediaType.parse("application/json; charset=utf-8");
//String json = new Gson().toJson(avgBvp);
//JSONArray jsArray = new JSONArray(avgBvp);
// RequestBody formbody = RequestBody.create(JSON, jsArray.toString());
/* Request request = new Request.Builder().url("http://146.48.52.220:5000/").post(formbody).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
textViewMood.setText("Fail");
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
textViewMood.setText((response.body().string()));
}
});*/
}
}

View File

@ -0,0 +1,120 @@
package com.empatica.sample;
import android.content.Context;
import android.view.Gravity;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
//A class to generate the table
public class TableDynamic{
private TableLayout tableLayout;
private Context context;
private String[] header;
private ArrayList<String []>data;
private TableRow tableRow;
private TextView textCell;
private int indexC;
private int indexR;
private boolean multicolor = false;
int firstColor, secondColor;
public TableDynamic(TableLayout tableLayout, Context context) {
this.tableLayout=tableLayout;
this.context=context;
}
public void addHeader(String[] header) {
this.header=header;
createHeader();
}
public void addData(ArrayList<String[]>data){
this.data=data;
createDataTable();
}
private void newRow(){
tableRow = new TableRow(context);
}
private void newCell(){
textCell = new TextView(context);
textCell.setGravity(Gravity.CENTER);
textCell.setTextSize(25);
}
private void createHeader(){
indexC=0;
newRow();
while(indexC<header.length){
newCell();
textCell.setText(header[indexC++]);
tableRow.addView(textCell, newTableRowParams());
}
tableLayout.addView(tableRow);
}
private void createDataTable() {
String info;
for(indexR=1;indexR<=data.size();indexR++){
newRow();
for(indexC=0;indexC<header.length;indexC++){
newCell();
String[] row=data.get(indexR-1);
info =(indexC<row.length)?row[indexC]:"";
textCell.setText(info);
tableRow.addView(textCell,newTableRowParams());
}
tableLayout.addView(tableRow);
}
}
public void backgroundHeader(int color){
indexC=0;
while(indexC<header.length){
textCell = getCell(0,indexC++);
textCell.setBackgroundColor(color);
}
}
public void backgroundData(int firstColor, int secondColor){
for(indexR=1;indexR<=data.size();indexR++){
multicolor = !multicolor;
for(indexC=0;indexC<header.length;indexC++){
textCell = getCell(indexR,indexC);
textCell.setBackgroundColor((multicolor)?firstColor:secondColor);
}
}
this.firstColor = firstColor;
this.secondColor = secondColor;
}
public void lineColor(int color){
indexR=0;
while (indexR<=data.size()){
getRow(indexR++).setBackgroundColor(color);
}
}
private TableRow getRow(int index){
return (TableRow) tableLayout.getChildAt(index);
}
private TextView getCell(int rowIndex, int columIndex){
tableRow = getRow(rowIndex);
return (TextView) tableRow.getVirtualChildAt(columIndex);
}
private TableRow.LayoutParams newTableRowParams(){
TableRow.LayoutParams params = new TableRow.LayoutParams();
params.setMargins(1,1,1,1);
params.weight=1;
return params;
}
}

View File

@ -0,0 +1,249 @@
package com.empatica.sample;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.empatica.domain.SuperUser;
import com.empatica.domain.Click;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
//A class to handle 2 activities, the list of different users (layout=1) and the list of the saved sessions (layout=2)
public class UsersActivity extends AppCompatActivity implements View.OnClickListener {
private DatabaseReference databaseReference;
private RecyclerView recyclerView;
private Button buttonAddUser;
private EditText editTextUser;
private SuperUser superUser;
private List<String> listUsers,listSessions;
private AdapterUsers adapterUsers;
private String user;
private int layout;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_users);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
buttonAddUser = findViewById(R.id.buttonUser);
buttonAddUser.setOnClickListener(this);
editTextUser = findViewById(R.id.editTextUser);
Bundle extra = getIntent().getExtras();
superUser = (SuperUser) extra.getSerializable("superUser");
layout =(int) extra.getSerializable("layout");
user = (String)extra.getSerializable("user");
databaseReference = FirebaseDatabase.getInstance("https://empaticae4-3e023-default-rtdb.europe-west1.firebasedatabase.app").getReference();
if(layout==1){
getUsers();
}else{
getSession();
buttonAddUser.setText("Search");
editTextUser.setHint("Date: Format dd/mm/yyyy");
}
}
//Get the list of different users from the data base, store it in an arraylist 'listUsers' and show it with the recycler view
private void getUsers(){
String email = superUser.getEmail();
databaseReference.child("users").child(email).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
listUsers = new ArrayList<>();
if (snapshot.exists()){
for (DataSnapshot ds : snapshot.getChildren()){
String name = ds.getKey().toString();
listUsers.add(name);
}
adapterUsers = new AdapterUsers(listUsers, UsersActivity.this);
recyclerView.setAdapter(adapterUsers);
adapterUsers.setOnItemClickListener(new AdapterUsers.OnItemClickListener() {
@Override
//When click on in one user, send this user to the Profile activity
public void onItemClick(int position) {
String nameUser=listUsers.get(position);
Intent main = new Intent(UsersActivity.this,ProfileActivity.class);
Bundle bundleMain = new Bundle();
bundleMain.putSerializable("user", nameUser);
bundleMain.putSerializable("superUser",superUser);
main.putExtras(bundleMain);
startActivity(main);
//finish();
}
});
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
//Get the list of saved sessions from the data base, store it in an arraylist 'listSessions' and show it with the recycler view
private void getSession(){
String email = superUser.getEmail();
databaseReference.child("users").child(email).child(user).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
listSessions = new ArrayList<>();
if (snapshot.exists()) {
for (DataSnapshot ds : snapshot.getChildren()) {
Click time = ds.getValue(Click.class);
String n = ds.getKey().toString();
String i = time.getDateInit();
String e = time.getDateEnd();
String c ="Session: "+n+" Init: "+i+" End: "+e;
listSessions.add(c);
}
adapterUsers = new AdapterUsers(listSessions, UsersActivity.this);
recyclerView.setAdapter(adapterUsers);
adapterUsers.setOnItemClickListener(new AdapterUsers.OnItemClickListener() {
@Override
//When click on in one session, send this session to the Record activity
public void onItemClick(int position) {
String session=listSessions.get(position);
Intent main = new Intent(UsersActivity.this, SavedSessionsActivity.class);
Bundle bundleMain = new Bundle();
bundleMain.putSerializable("user", user);
bundleMain.putSerializable("session", session);
bundleMain.putSerializable("superUser",superUser);
main.putExtras(bundleMain);
startActivity(main);
//finish();
}
});
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
//Different functions of the button, save a new user or search one session
@Override
public void onClick(View view){
switch (view.getId()){
case R.id.buttonUser:
//Save a new user
if (layout==1) {
String email = superUser.getEmail();
String newUser = editTextUser.getText().toString();
Click click = new Click();
click.setDateEnd("0");
click.setDateInit("0");
databaseReference.child("users").child(email).child(newUser).child("0").setValue(click);
//Search one session
}else{
List<String> searchSession= new ArrayList<>();
String date = editTextUser.getText().toString();
String[] dat = date.split("/");
String day = dat[0];
String month = dat[1];
String year = dat[2];
for(int i=0;i<listSessions.size();i++){
String session = listSessions.get(i);
boolean t = getDate(session,day,month,year);
if(t==true)
searchSession.add(session);
}
adapterUsers = new AdapterUsers(searchSession, UsersActivity.this);
recyclerView.setAdapter(adapterUsers);
adapterUsers.setOnItemClickListener(new AdapterUsers.OnItemClickListener() {
@Override
public void onItemClick(int position) {
String session=searchSession.get(position);
Intent main = new Intent(UsersActivity.this, SavedSessionsActivity.class);
Bundle bundleMain = new Bundle();
bundleMain.putSerializable("user", user);
bundleMain.putSerializable("session", session);
bundleMain.putSerializable("superUser",superUser);
main.putExtras(bundleMain);
startActivity(main);
//finish();
}
});
}
}
}
//Search dates in the database equal to the one introduced
private boolean getDate(String session,String day, String month,String year){
String d="";
String yearI="",monthI="",dayI="";
boolean t=false;
for(int i = 0, n = session.length() ; i < n ; i++) {
char c = session.charAt(i);
d=d.concat(String.valueOf(c));
switch (d){
case "Session: ":
d="";
i++;
i++;
break;
case "Init: ":
i++;
d="";
int dot=0;
for(int j = i; j<n; j++ ){
c = session.charAt(j);
String m= String.valueOf(c);
if(m.equals(".")||m.equals(" "))
dot++;
else
d=d.concat(String.valueOf(c));
switch (dot){
case 1:
yearI = d;
d="";
dot++;
break;
case 3:
monthI = d;
d="";
dot++;
break;
case 5:
dayI = d;
d="";
i=j;
j=n;
break;
}
}
break;
}
if(year.equals(yearI)&&month.equals(monthI)&&day.equals(dayI)){
t=true;
return t;
}
}
return t;
}
}

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#3e97a9" android:width="3dp"/>
<corners android:radius="10dp"/>
</shape>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:color="#3e97a9" android:width="3dp"/>
<solid android:color="#ffffff"/>
<corners android:radius="10dp"/>
</shape>

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#FFFFFF"/>
<corners
android:radius="0dp"/>
</shape>

View File

@ -0,0 +1,59 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".LoginActivity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/first_background"
android:padding="20dp">
<EditText
android:id="@+id/editTextEmail"
app:backgroundTint="#000000"
android:textColor="#000000"
android:textColorHint="#B8B8B8"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:hint="Email"
android:maxLines="1"
android:inputType="text"/>
<EditText
android:id="@+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:backgroundTint="#000000"
android:textColor="#000000"
android:textColorHint="#B8B8B8"
android:layout_marginTop="20dp"
android:inputType="textPassword"
android:hint="Password "/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<Button
android:id="@+id/buttonLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/button1"
android:layout_margin="10dp"
android:text="Login"/>
<Button
android:id="@+id/buttonRegister"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/button1"
android:layout_margin="10dp"
android:text="Register"/>
</LinearLayout>
</LinearLayout>

View File

@ -0,0 +1,171 @@
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:padding="16dp"
android:background="@android:color/holo_blue_dark">
<TextView
android:id="@+id/status"
android:layout_width="match_parent"
android:layout_height="36dp"/>
<TextView
android:id="@+id/deviceName"
android:layout_below="@id/status"
android:layout_width="match_parent"
android:layout_height="36dp"/>
<LinearLayout
android:visibility="invisible"
android:id="@+id/dataArea"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/deviceName"
android:orientation="vertical">
<TextView
android:id="@+id/accel_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:text="@string/accel" />
<LinearLayout
android:id="@+id/accel_area"
android:layout_below="@id/accel_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/accel_x" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="50dp"
android:id="@+id/accel_x"
android:text="@string/emptyText"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/accel_y" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="50dp"
android:id="@+id/accel_y"
android:text="@string/emptyText"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/accel_z" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="50dp"
android:id="@+id/accel_z"
android:text="@string/emptyText"/>
</LinearLayout>
<TextView
android:id="@+id/bvp_label"
android:layout_marginTop="10dp"
android:layout_below="@id/accel_area"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/bvp_label" />
<TextView
android:layout_below="@id/bvp_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/bvp"
android:text="@string/emptyText"/>
<TextView
android:id="@+id/eda_label"
android:layout_marginTop="10dp"
android:layout_below="@id/bvp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/eda_label" />
<TextView
android:layout_below="@id/eda_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/eda"
android:text="@string/emptyText"/>
<TextView
android:id="@+id/ibi_label"
android:layout_marginTop="10dp"
android:layout_below="@id/eda"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/ibi_label" />
<TextView
android:layout_below="@id/ibi_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/ibi"
android:text="@string/emptyText"/>
<TextView
android:id="@+id/temp_label"
android:layout_marginTop="10dp"
android:layout_below="@id/ibi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/temp_label" />
<TextView
android:layout_below="@id/temp_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/temperature"
android:text="@string/emptyText"/>
<TextView
android:id="@+id/battery_label"
android:layout_marginTop="10dp"
android:layout_below="@id/temperature"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/battery_label" />
<TextView
android:layout_below="@id/battery_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/battery"
android:text="@string/emptyText"/>
<TextView
android:layout_below="@id/wrist_status_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/wrist_status_label"
android:text="@string/emptyText"/>
<Button
android:id="@+id/disconnectButton"
android:text="STOP STREAMING"
android:layout_width="match_parent"
android:layout_height="44dp" />
</LinearLayout>
</LinearLayout>

View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="@drawable/first_background"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/buttonSession"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="230dp"
android:background="@drawable/button1"
android:text="New session" />
<Button
android:id="@+id/buttonSaved"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:background="@drawable/button1"
android:text="Saved sessions" />
</LinearLayout>

View File

@ -0,0 +1,112 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".LoginActivity"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/first_background"
android:padding="20dp">
<EditText
android:id="@+id/editTextEmail"
app:backgroundTint="#000000"
android:textColor="#000000"
android:textColorHint="#B8B8B8"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:hint="Email"
android:maxLines="1"
android:inputType="text"/>
<EditText
android:id="@+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:backgroundTint="#000000"
android:textColor="#000000"
android:textColorHint="#B8B8B8"
android:layout_marginTop="20dp"
android:inputType="textPassword"
android:hint="Password "/>
<EditText
android:id="@+id/editTextPasswordRepeat"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:backgroundTint="#000000"
android:textColor="#000000"
android:textColorHint="#B8B8B8"
android:layout_marginTop="20dp"
android:inputType="textPassword"
android:hint="Repeat Password "/>
<EditText
android:id="@+id/editTextName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:backgroundTint="#000000"
android:textColor="#000000"
android:textColorHint="#B8B8B8"
android:layout_marginTop="20dp"
android:inputType="text"
android:hint="Name"/>
<EditText
android:id="@+id/editTextGender"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:backgroundTint="#000000"
android:textColor="#000000"
android:textColorHint="#B8B8B8"
android:layout_marginTop="20dp"
android:inputType="text"
android:hint="Gender: M/F"/>
<EditText
android:id="@+id/editTextAge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:backgroundTint="#000000"
android:textColor="#000000"
android:textColorHint="#B8B8B8"
android:layout_marginTop="20dp"
android:inputType="text"
android:hint="Age"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<Button
android:id="@+id/buttonRegister"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/button1"
android:layout_margin="10dp"
android:text="Register new user"/>
</LinearLayout>
<EditText
android:id="@+id/editTextNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" />
<EditText
android:id="@+id/editTextNumber2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" />
<com.google.android.material.chip.ChipGroup
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.google.android.material.chip.ChipGroup>
</LinearLayout>

View File

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/first_background"
tools:context=".SavedSessionsActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableLayout
android:id="@+id/table"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
</HorizontalScrollView>
</ScrollView>
<TextView
android:id="@+id/textViewMood"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="30dp"
android:text="The mood is..." />
</LinearLayout>

View File

@ -0,0 +1,44 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".UsersActivity"
android:background="@drawable/first_background"
android:orientation="vertical">
<EditText
android:id="@+id/editTextUser"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:backgroundTint="#000000"
android:textColor="#000000"
android:textColorHint="#B8B8B8"
android:layout_margin="10dp"
android:hint="New user"
android:maxLines="1"/>
<Button
android:layout_width="match_parent"
android:id="@+id/buttonUser"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="@drawable/button1"
android:text="Add user"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:padding="1dp">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
</LinearLayout>

View File

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/first_background"
android:orientation="vertical">
<androidx.cardview.widget.CardView
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardBackgroundColor="@drawable/first_background">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:paddingTop="10dp"
android:paddingVertical="10dp"
android:paddingLeft="10dp"
android:background="@drawable/card"
android:paddingRight="10dp">
<TextView
android:id="@+id/textName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="name"
android:textColor="#000000"
android:textSize="18dp"
android:textStyle="bold" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

View File

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/nav_graph"
app:startDestination="@id/FirstFragment">
<fragment
android:id="@+id/FirstFragment"
android:name="com.empatica.sample.FirstFragment"
android:label="@string/first_fragment_label"
tools:layout="@layout/fragment_first">
<action
android:id="@+id/action_FirstFragment_to_SecondFragment"
app:destination="@id/SecondFragment" />
</fragment>
<fragment
android:id="@+id/SecondFragment"
android:name="com.empatica.sample.SecondFragment"
android:label="@string/second_fragment_label"
tools:layout="@layout/fragment_second">
<action
android:id="@+id/action_SecondFragment_to_FirstFragment"
app:destination="@id/FirstFragment" />
</fragment>
</navigation>

View File

@ -0,0 +1,3 @@
<resources>
<dimen name="fab_margin">48dp</dimen>
</resources>

View File

@ -0,0 +1,3 @@
<resources>
<dimen name="fab_margin">200dp</dimen>
</resources>

View File

@ -0,0 +1,3 @@
<resources>
<dimen name="fab_margin">48dp</dimen>
</resources>

View File

@ -0,0 +1,6 @@
<resources>
<!-- Example customization of dimensions originally defined in res/values/dimens.xml
(such as screen margins) for screens with more than 820dp of available width. This
would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->
<dimen name="activity_horizontal_margin">64dp</dimen>
</resources>

View File

@ -0,0 +1,6 @@
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
<dimen name="fab_margin">16dp</dimen>
</resources>

View File

@ -0,0 +1,22 @@
<resources>
<string name="app_name">EmpaLink Sample Project</string>
<string name="accel">Accelerometers</string>
<string name="accel_x">x:</string>
<string name="accel_y">y:</string>
<string name="accel_z">z:</string>
<string name="bvp_label">BVP</string>
<string name="eda_label">EDA</string>
<string name="ibi_label">IBI</string>
<string name="emptyText">-</string>
<string name="temp_label">Temperature</string>
<string name="battery_label">Battery</string>
<string name="title_activity_register">activity_register</string>
<!-- Strings used for fragments for navigation -->
<string name="first_fragment_label">First Fragment</string>
<string name="second_fragment_label">Second Fragment</string>
<string name="next">Next</string>
<string name="previous">Previous</string>
<string name="hello_first_fragment">Hello first fragment</string>
<string name="hello_second_fragment">Hello second fragment. Arg: %1$s</string>
</resources>

View File

@ -0,0 +1,8 @@
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>
</resources>

View File

@ -0,0 +1,11 @@
<resources>
<style name="NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</resources>

View File

@ -0,0 +1,187 @@
# don't import any costly modules
import sys
import os
is_pypy = '__pypy__' in sys.builtin_module_names
def warn_distutils_present():
if 'distutils' not in sys.modules:
return
if is_pypy and sys.version_info < (3, 7):
# PyPy for 3.6 unconditionally imports distutils, so bypass the warning
# https://foss.heptapod.net/pypy/pypy/-/blob/be829135bc0d758997b3566062999ee8b23872b4/lib-python/3/site.py#L250
return
import warnings
warnings.warn(
"Distutils was imported before Setuptools, but importing Setuptools "
"also replaces the `distutils` module in `sys.modules`. This may lead "
"to undesirable behaviors or errors. To avoid these issues, avoid "
"using distutils directly, ensure that setuptools is installed in the "
"traditional way (e.g. not an editable install), and/or make sure "
"that setuptools is always imported before distutils.")
def clear_distutils():
if 'distutils' not in sys.modules:
return
import warnings
warnings.warn("Setuptools is replacing distutils.")
mods = [
name for name in sys.modules
if name == "distutils" or name.startswith("distutils.")
]
for name in mods:
del sys.modules[name]
def enabled():
"""
Allow selection of distutils by environment variable.
"""
which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'local')
return which == 'local'
def ensure_local_distutils():
import importlib
clear_distutils()
# With the DistutilsMetaFinder in place,
# perform an import to cause distutils to be
# loaded from setuptools._distutils. Ref #2906.
with shim():
importlib.import_module('distutils')
# check that submodules load as expected
core = importlib.import_module('distutils.core')
assert '_distutils' in core.__file__, core.__file__
assert 'setuptools._distutils.log' not in sys.modules
def do_override():
"""
Ensure that the local copy of distutils is preferred over stdlib.
See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401
for more motivation.
"""
if enabled():
warn_distutils_present()
ensure_local_distutils()
class _TrivialRe:
def __init__(self, *patterns):
self._patterns = patterns
def match(self, string):
return all(pat in string for pat in self._patterns)
class DistutilsMetaFinder:
def find_spec(self, fullname, path, target=None):
if path is not None:
return
method_name = 'spec_for_{fullname}'.format(**locals())
method = getattr(self, method_name, lambda: None)
return method()
def spec_for_distutils(self):
if self.is_cpython():
return
import importlib
import importlib.abc
import importlib.util
try:
mod = importlib.import_module('setuptools._distutils')
except Exception:
# There are a couple of cases where setuptools._distutils
# may not be present:
# - An older Setuptools without a local distutils is
# taking precedence. Ref #2957.
# - Path manipulation during sitecustomize removes
# setuptools from the path but only after the hook
# has been loaded. Ref #2980.
# In either case, fall back to stdlib behavior.
return
class DistutilsLoader(importlib.abc.Loader):
def create_module(self, spec):
mod.__name__ = 'distutils'
return mod
def exec_module(self, module):
pass
return importlib.util.spec_from_loader(
'distutils', DistutilsLoader(), origin=mod.__file__
)
@staticmethod
def is_cpython():
"""
Suppress supplying distutils for CPython (build and tests).
Ref #2965 and #3007.
"""
return os.path.isfile('pybuilddir.txt')
def spec_for_pip(self):
"""
Ensure stdlib distutils when running under pip.
See pypa/pip#8761 for rationale.
"""
if self.pip_imported_during_build():
return
clear_distutils()
self.spec_for_distutils = lambda: None
@classmethod
def pip_imported_during_build(cls):
"""
Detect if pip is being imported in a build script. Ref #2355.
"""
import traceback
return any(
cls.frame_file_is_setup(frame)
for frame, line in traceback.walk_stack(None)
)
@staticmethod
def frame_file_is_setup(frame):
"""
Return True if the indicated frame suggests a setup.py file.
"""
# some frames may not have __file__ (#2940)
return frame.f_globals.get('__file__', '').endswith('setup.py')
DISTUTILS_FINDER = DistutilsMetaFinder()
def add_shim():
DISTUTILS_FINDER in sys.meta_path or insert_shim()
class shim:
def __enter__(self):
insert_shim()
def __exit__(self, exc, value, tb):
remove_shim()
def insert_shim():
sys.meta_path.insert(0, DISTUTILS_FINDER)
def remove_shim():
try:
sys.meta_path.remove(DISTUTILS_FINDER)
except ValueError:
pass

View File

@ -0,0 +1 @@
__import__('_distutils_hack').do_override()

View File

@ -0,0 +1 @@
import os; var = 'SETUPTOOLS_USE_DISTUTILS'; enabled = os.environ.get(var, 'local') == 'local'; enabled and __import__('_distutils_hack').add_shim();

View File

@ -0,0 +1 @@
pip

View File

@ -0,0 +1,20 @@
Copyright (c) 2008-present The pip developers (see AUTHORS.txt file)
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,92 @@
Metadata-Version: 2.1
Name: pip
Version: 22.0.4
Summary: The PyPA recommended tool for installing Python packages.
Home-page: https://pip.pypa.io/
Author: The pip developers
Author-email: distutils-sig@python.org
License: MIT
Project-URL: Documentation, https://pip.pypa.io
Project-URL: Source, https://github.com/pypa/pip
Project-URL: Changelog, https://pip.pypa.io/en/stable/news/
Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Topic :: Software Development :: Build Tools
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Requires-Python: >=3.7
License-File: LICENSE.txt
pip - The Python Package Installer
==================================
.. image:: https://img.shields.io/pypi/v/pip.svg
:target: https://pypi.org/project/pip/
.. image:: https://readthedocs.org/projects/pip/badge/?version=latest
:target: https://pip.pypa.io/en/latest
pip is the `package installer`_ for Python. You can use pip to install packages from the `Python Package Index`_ and other indexes.
Please take a look at our documentation for how to install and use pip:
* `Installation`_
* `Usage`_
We release updates regularly, with a new version every 3 months. Find more details in our documentation:
* `Release notes`_
* `Release process`_
In pip 20.3, we've `made a big improvement to the heart of pip`_; `learn more`_. We want your input, so `sign up for our user experience research studies`_ to help us do it right.
**Note**: pip 21.0, in January 2021, removed Python 2 support, per pip's `Python 2 support policy`_. Please migrate to Python 3.
If you find bugs, need help, or want to talk to the developers, please use our mailing lists or chat rooms:
* `Issue tracking`_
* `Discourse channel`_
* `User IRC`_
If you want to get involved head over to GitHub to get the source code, look at our development documentation and feel free to jump on the developer mailing lists and chat rooms:
* `GitHub page`_
* `Development documentation`_
* `Development mailing list`_
* `Development IRC`_
Code of Conduct
---------------
Everyone interacting in the pip project's codebases, issue trackers, chat
rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_.
.. _package installer: https://packaging.python.org/guides/tool-recommendations/
.. _Python Package Index: https://pypi.org
.. _Installation: https://pip.pypa.io/en/stable/installation/
.. _Usage: https://pip.pypa.io/en/stable/
.. _Release notes: https://pip.pypa.io/en/stable/news.html
.. _Release process: https://pip.pypa.io/en/latest/development/release-process/
.. _GitHub page: https://github.com/pypa/pip
.. _Development documentation: https://pip.pypa.io/en/latest/development
.. _made a big improvement to the heart of pip: https://pyfound.blogspot.com/2020/11/pip-20-3-new-resolver.html
.. _learn more: https://pip.pypa.io/en/latest/user_guide/#changes-to-the-pip-dependency-resolver-in-20-3-2020
.. _sign up for our user experience research studies: https://pyfound.blogspot.com/2020/03/new-pip-resolver-to-roll-out-this-year.html
.. _Python 2 support policy: https://pip.pypa.io/en/latest/development/release-process/#python-2-support
.. _Issue tracking: https://github.com/pypa/pip/issues
.. _Discourse channel: https://discuss.python.org/c/packaging
.. _Development mailing list: https://mail.python.org/mailman3/lists/distutils-sig.python.org/
.. _User IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa
.. _Development IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa-dev
.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,5 @@
Wheel-Version: 1.0
Generator: bdist_wheel (0.37.1)
Root-Is-Purelib: true
Tag: py3-none-any

View File

@ -0,0 +1,5 @@
[console_scripts]
pip = pip._internal.cli.main:main
pip3 = pip._internal.cli.main:main
pip3.9 = pip._internal.cli.main:main

View File

@ -0,0 +1 @@
pip

View File

@ -0,0 +1,13 @@
from typing import List, Optional
__version__ = "22.0.4"
def main(args: Optional[List[str]] = None) -> int:
"""This is an internal API only meant for use by pip's own console scripts.
For additional details, see https://github.com/pypa/pip/issues/7498.
"""
from pip._internal.utils.entrypoints import _wrapper
return _wrapper(args)

View File

@ -0,0 +1,31 @@
import os
import sys
import warnings
# Remove '' and current working directory from the first entry
# of sys.path, if present to avoid using current directory
# in pip commands check, freeze, install, list and show,
# when invoked as python -m pip <command>
if sys.path[0] in ("", os.getcwd()):
sys.path.pop(0)
# If we are running from a wheel, add the wheel to sys.path
# This allows the usage python pip-*.whl/pip install pip-*.whl
if __package__ == "":
# __file__ is pip-*.whl/pip/__main__.py
# first dirname call strips of '/__main__.py', second strips off '/pip'
# Resulting path is the name of the wheel itself
# Add that to sys.path so we can import pip
path = os.path.dirname(os.path.dirname(__file__))
sys.path.insert(0, path)
if __name__ == "__main__":
# Work around the error reported in #9540, pending a proper fix.
# Note: It is essential the warning filter is set *before* importing
# pip, as the deprecation happens at import time, not runtime.
warnings.filterwarnings(
"ignore", category=DeprecationWarning, module=".*packaging\\.version"
)
from pip._internal.cli.main import main as _main
sys.exit(_main())

View File

@ -0,0 +1,19 @@
from typing import List, Optional
import pip._internal.utils.inject_securetransport # noqa
from pip._internal.utils import _log
# init_logging() must be called before any call to logging.getLogger()
# which happens at import of most modules.
_log.init_logging()
def main(args: (Optional[List[str]]) = None) -> int:
"""This is preserved for old console scripts that may still be referencing
it.
For additional details, see https://github.com/pypa/pip/issues/7498.
"""
from pip._internal.utils.entrypoints import _wrapper
return _wrapper(args)

View File

@ -0,0 +1,296 @@
"""Build Environment used for isolation during sdist building
"""
import contextlib
import logging
import os
import pathlib
import sys
import textwrap
import zipfile
from collections import OrderedDict
from sysconfig import get_paths
from types import TracebackType
from typing import TYPE_CHECKING, Iterable, Iterator, List, Optional, Set, Tuple, Type
from pip._vendor.certifi import where
from pip._vendor.packaging.requirements import Requirement
from pip._vendor.packaging.version import Version
from pip import __file__ as pip_location
from pip._internal.cli.spinners import open_spinner
from pip._internal.locations import get_platlib, get_prefixed_libs, get_purelib
from pip._internal.metadata import get_environment
from pip._internal.utils.subprocess import call_subprocess
from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds
if TYPE_CHECKING:
from pip._internal.index.package_finder import PackageFinder
logger = logging.getLogger(__name__)
class _Prefix:
def __init__(self, path: str) -> None:
self.path = path
self.setup = False
self.bin_dir = get_paths(
"nt" if os.name == "nt" else "posix_prefix",
vars={"base": path, "platbase": path},
)["scripts"]
self.lib_dirs = get_prefixed_libs(path)
@contextlib.contextmanager
def _create_standalone_pip() -> Iterator[str]:
"""Create a "standalone pip" zip file.
The zip file's content is identical to the currently-running pip.
It will be used to install requirements into the build environment.
"""
source = pathlib.Path(pip_location).resolve().parent
# Return the current instance if `source` is not a directory. We can't build
# a zip from this, and it likely means the instance is already standalone.
if not source.is_dir():
yield str(source)
return
with TempDirectory(kind="standalone-pip") as tmp_dir:
pip_zip = os.path.join(tmp_dir.path, "__env_pip__.zip")
kwargs = {}
if sys.version_info >= (3, 8):
kwargs["strict_timestamps"] = False
with zipfile.ZipFile(pip_zip, "w", **kwargs) as zf:
for child in source.rglob("*"):
zf.write(child, child.relative_to(source.parent).as_posix())
yield os.path.join(pip_zip, "pip")
class BuildEnvironment:
"""Creates and manages an isolated environment to install build deps"""
def __init__(self) -> None:
temp_dir = TempDirectory(kind=tempdir_kinds.BUILD_ENV, globally_managed=True)
self._prefixes = OrderedDict(
(name, _Prefix(os.path.join(temp_dir.path, name)))
for name in ("normal", "overlay")
)
self._bin_dirs: List[str] = []
self._lib_dirs: List[str] = []
for prefix in reversed(list(self._prefixes.values())):
self._bin_dirs.append(prefix.bin_dir)
self._lib_dirs.extend(prefix.lib_dirs)
# Customize site to:
# - ensure .pth files are honored
# - prevent access to system site packages
system_sites = {
os.path.normcase(site) for site in (get_purelib(), get_platlib())
}
self._site_dir = os.path.join(temp_dir.path, "site")
if not os.path.exists(self._site_dir):
os.mkdir(self._site_dir)
with open(
os.path.join(self._site_dir, "sitecustomize.py"), "w", encoding="utf-8"
) as fp:
fp.write(
textwrap.dedent(
"""
import os, site, sys
# First, drop system-sites related paths.
original_sys_path = sys.path[:]
known_paths = set()
for path in {system_sites!r}:
site.addsitedir(path, known_paths=known_paths)
system_paths = set(
os.path.normcase(path)
for path in sys.path[len(original_sys_path):]
)
original_sys_path = [
path for path in original_sys_path
if os.path.normcase(path) not in system_paths
]
sys.path = original_sys_path
# Second, add lib directories.
# ensuring .pth file are processed.
for path in {lib_dirs!r}:
assert not path in sys.path
site.addsitedir(path)
"""
).format(system_sites=system_sites, lib_dirs=self._lib_dirs)
)
def __enter__(self) -> None:
self._save_env = {
name: os.environ.get(name, None)
for name in ("PATH", "PYTHONNOUSERSITE", "PYTHONPATH")
}
path = self._bin_dirs[:]
old_path = self._save_env["PATH"]
if old_path:
path.extend(old_path.split(os.pathsep))
pythonpath = [self._site_dir]
os.environ.update(
{
"PATH": os.pathsep.join(path),
"PYTHONNOUSERSITE": "1",
"PYTHONPATH": os.pathsep.join(pythonpath),
}
)
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
for varname, old_value in self._save_env.items():
if old_value is None:
os.environ.pop(varname, None)
else:
os.environ[varname] = old_value
def check_requirements(
self, reqs: Iterable[str]
) -> Tuple[Set[Tuple[str, str]], Set[str]]:
"""Return 2 sets:
- conflicting requirements: set of (installed, wanted) reqs tuples
- missing requirements: set of reqs
"""
missing = set()
conflicting = set()
if reqs:
env = get_environment(self._lib_dirs)
for req_str in reqs:
req = Requirement(req_str)
dist = env.get_distribution(req.name)
if not dist:
missing.add(req_str)
continue
if isinstance(dist.version, Version):
installed_req_str = f"{req.name}=={dist.version}"
else:
installed_req_str = f"{req.name}==={dist.version}"
if dist.version not in req.specifier:
conflicting.add((installed_req_str, req_str))
# FIXME: Consider direct URL?
return conflicting, missing
def install_requirements(
self,
finder: "PackageFinder",
requirements: Iterable[str],
prefix_as_string: str,
*,
kind: str,
) -> None:
prefix = self._prefixes[prefix_as_string]
assert not prefix.setup
prefix.setup = True
if not requirements:
return
with contextlib.ExitStack() as ctx:
pip_runnable = ctx.enter_context(_create_standalone_pip())
self._install_requirements(
pip_runnable,
finder,
requirements,
prefix,
kind=kind,
)
@staticmethod
def _install_requirements(
pip_runnable: str,
finder: "PackageFinder",
requirements: Iterable[str],
prefix: _Prefix,
*,
kind: str,
) -> None:
args: List[str] = [
sys.executable,
pip_runnable,
"install",
"--ignore-installed",
"--no-user",
"--prefix",
prefix.path,
"--no-warn-script-location",
]
if logger.getEffectiveLevel() <= logging.DEBUG:
args.append("-v")
for format_control in ("no_binary", "only_binary"):
formats = getattr(finder.format_control, format_control)
args.extend(
(
"--" + format_control.replace("_", "-"),
",".join(sorted(formats or {":none:"})),
)
)
index_urls = finder.index_urls
if index_urls:
args.extend(["-i", index_urls[0]])
for extra_index in index_urls[1:]:
args.extend(["--extra-index-url", extra_index])
else:
args.append("--no-index")
for link in finder.find_links:
args.extend(["--find-links", link])
for host in finder.trusted_hosts:
args.extend(["--trusted-host", host])
if finder.allow_all_prereleases:
args.append("--pre")
if finder.prefer_binary:
args.append("--prefer-binary")
args.append("--")
args.extend(requirements)
extra_environ = {"_PIP_STANDALONE_CERT": where()}
with open_spinner(f"Installing {kind}") as spinner:
call_subprocess(
args,
command_desc=f"pip subprocess to install {kind}",
spinner=spinner,
extra_environ=extra_environ,
)
class NoOpBuildEnvironment(BuildEnvironment):
"""A no-op drop-in replacement for BuildEnvironment"""
def __init__(self) -> None:
pass
def __enter__(self) -> None:
pass
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
pass
def cleanup(self) -> None:
pass
def install_requirements(
self,
finder: "PackageFinder",
requirements: Iterable[str],
prefix_as_string: str,
*,
kind: str,
) -> None:
raise NotImplementedError()

View File

@ -0,0 +1,264 @@
"""Cache Management
"""
import hashlib
import json
import logging
import os
from typing import Any, Dict, List, Optional, Set
from pip._vendor.packaging.tags import Tag, interpreter_name, interpreter_version
from pip._vendor.packaging.utils import canonicalize_name
from pip._internal.exceptions import InvalidWheelFilename
from pip._internal.models.format_control import FormatControl
from pip._internal.models.link import Link
from pip._internal.models.wheel import Wheel
from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds
from pip._internal.utils.urls import path_to_url
logger = logging.getLogger(__name__)
def _hash_dict(d: Dict[str, str]) -> str:
"""Return a stable sha224 of a dictionary."""
s = json.dumps(d, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
return hashlib.sha224(s.encode("ascii")).hexdigest()
class Cache:
"""An abstract class - provides cache directories for data from links
:param cache_dir: The root of the cache.
:param format_control: An object of FormatControl class to limit
binaries being read from the cache.
:param allowed_formats: which formats of files the cache should store.
('binary' and 'source' are the only allowed values)
"""
def __init__(
self, cache_dir: str, format_control: FormatControl, allowed_formats: Set[str]
) -> None:
super().__init__()
assert not cache_dir or os.path.isabs(cache_dir)
self.cache_dir = cache_dir or None
self.format_control = format_control
self.allowed_formats = allowed_formats
_valid_formats = {"source", "binary"}
assert self.allowed_formats.union(_valid_formats) == _valid_formats
def _get_cache_path_parts(self, link: Link) -> List[str]:
"""Get parts of part that must be os.path.joined with cache_dir"""
# We want to generate an url to use as our cache key, we don't want to
# just re-use the URL because it might have other items in the fragment
# and we don't care about those.
key_parts = {"url": link.url_without_fragment}
if link.hash_name is not None and link.hash is not None:
key_parts[link.hash_name] = link.hash
if link.subdirectory_fragment:
key_parts["subdirectory"] = link.subdirectory_fragment
# Include interpreter name, major and minor version in cache key
# to cope with ill-behaved sdists that build a different wheel
# depending on the python version their setup.py is being run on,
# and don't encode the difference in compatibility tags.
# https://github.com/pypa/pip/issues/7296
key_parts["interpreter_name"] = interpreter_name()
key_parts["interpreter_version"] = interpreter_version()
# Encode our key url with sha224, we'll use this because it has similar
# security properties to sha256, but with a shorter total output (and
# thus less secure). However the differences don't make a lot of
# difference for our use case here.
hashed = _hash_dict(key_parts)
# We want to nest the directories some to prevent having a ton of top
# level directories where we might run out of sub directories on some
# FS.
parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]]
return parts
def _get_candidates(self, link: Link, canonical_package_name: str) -> List[Any]:
can_not_cache = not self.cache_dir or not canonical_package_name or not link
if can_not_cache:
return []
formats = self.format_control.get_allowed_formats(canonical_package_name)
if not self.allowed_formats.intersection(formats):
return []
candidates = []
path = self.get_path_for_link(link)
if os.path.isdir(path):
for candidate in os.listdir(path):
candidates.append((candidate, path))
return candidates
def get_path_for_link(self, link: Link) -> str:
"""Return a directory to store cached items in for link."""
raise NotImplementedError()
def get(
self,
link: Link,
package_name: Optional[str],
supported_tags: List[Tag],
) -> Link:
"""Returns a link to a cached item if it exists, otherwise returns the
passed link.
"""
raise NotImplementedError()
class SimpleWheelCache(Cache):
"""A cache of wheels for future installs."""
def __init__(self, cache_dir: str, format_control: FormatControl) -> None:
super().__init__(cache_dir, format_control, {"binary"})
def get_path_for_link(self, link: Link) -> str:
"""Return a directory to store cached wheels for link
Because there are M wheels for any one sdist, we provide a directory
to cache them in, and then consult that directory when looking up
cache hits.
We only insert things into the cache if they have plausible version
numbers, so that we don't contaminate the cache with things that were
not unique. E.g. ./package might have dozens of installs done for it
and build a version of 0.0...and if we built and cached a wheel, we'd
end up using the same wheel even if the source has been edited.
:param link: The link of the sdist for which this will cache wheels.
"""
parts = self._get_cache_path_parts(link)
assert self.cache_dir
# Store wheels within the root cache_dir
return os.path.join(self.cache_dir, "wheels", *parts)
def get(
self,
link: Link,
package_name: Optional[str],
supported_tags: List[Tag],
) -> Link:
candidates = []
if not package_name:
return link
canonical_package_name = canonicalize_name(package_name)
for wheel_name, wheel_dir in self._get_candidates(link, canonical_package_name):
try:
wheel = Wheel(wheel_name)
except InvalidWheelFilename:
continue
if canonicalize_name(wheel.name) != canonical_package_name:
logger.debug(
"Ignoring cached wheel %s for %s as it "
"does not match the expected distribution name %s.",
wheel_name,
link,
package_name,
)
continue
if not wheel.supported(supported_tags):
# Built for a different python/arch/etc
continue
candidates.append(
(
wheel.support_index_min(supported_tags),
wheel_name,
wheel_dir,
)
)
if not candidates:
return link
_, wheel_name, wheel_dir = min(candidates)
return Link(path_to_url(os.path.join(wheel_dir, wheel_name)))
class EphemWheelCache(SimpleWheelCache):
"""A SimpleWheelCache that creates it's own temporary cache directory"""
def __init__(self, format_control: FormatControl) -> None:
self._temp_dir = TempDirectory(
kind=tempdir_kinds.EPHEM_WHEEL_CACHE,
globally_managed=True,
)
super().__init__(self._temp_dir.path, format_control)
class CacheEntry:
def __init__(
self,
link: Link,
persistent: bool,
):
self.link = link
self.persistent = persistent
class WheelCache(Cache):
"""Wraps EphemWheelCache and SimpleWheelCache into a single Cache
This Cache allows for gracefully degradation, using the ephem wheel cache
when a certain link is not found in the simple wheel cache first.
"""
def __init__(self, cache_dir: str, format_control: FormatControl) -> None:
super().__init__(cache_dir, format_control, {"binary"})
self._wheel_cache = SimpleWheelCache(cache_dir, format_control)
self._ephem_cache = EphemWheelCache(format_control)
def get_path_for_link(self, link: Link) -> str:
return self._wheel_cache.get_path_for_link(link)
def get_ephem_path_for_link(self, link: Link) -> str:
return self._ephem_cache.get_path_for_link(link)
def get(
self,
link: Link,
package_name: Optional[str],
supported_tags: List[Tag],
) -> Link:
cache_entry = self.get_cache_entry(link, package_name, supported_tags)
if cache_entry is None:
return link
return cache_entry.link
def get_cache_entry(
self,
link: Link,
package_name: Optional[str],
supported_tags: List[Tag],
) -> Optional[CacheEntry]:
"""Returns a CacheEntry with a link to a cached item if it exists or
None. The cache entry indicates if the item was found in the persistent
or ephemeral cache.
"""
retval = self._wheel_cache.get(
link=link,
package_name=package_name,
supported_tags=supported_tags,
)
if retval is not link:
return CacheEntry(retval, persistent=True)
retval = self._ephem_cache.get(
link=link,
package_name=package_name,
supported_tags=supported_tags,
)
if retval is not link:
return CacheEntry(retval, persistent=False)
return None

View File

@ -0,0 +1,4 @@
"""Subpackage containing all of pip's command line interface related code
"""
# This file intentionally does not import submodules

View File

@ -0,0 +1,171 @@
"""Logic that powers autocompletion installed by ``pip completion``.
"""
import optparse
import os
import sys
from itertools import chain
from typing import Any, Iterable, List, Optional
from pip._internal.cli.main_parser import create_main_parser
from pip._internal.commands import commands_dict, create_command
from pip._internal.metadata import get_default_environment
def autocomplete() -> None:
"""Entry Point for completion of main and subcommand options."""
# Don't complete if user hasn't sourced bash_completion file.
if "PIP_AUTO_COMPLETE" not in os.environ:
return
cwords = os.environ["COMP_WORDS"].split()[1:]
cword = int(os.environ["COMP_CWORD"])
try:
current = cwords[cword - 1]
except IndexError:
current = ""
parser = create_main_parser()
subcommands = list(commands_dict)
options = []
# subcommand
subcommand_name: Optional[str] = None
for word in cwords:
if word in subcommands:
subcommand_name = word
break
# subcommand options
if subcommand_name is not None:
# special case: 'help' subcommand has no options
if subcommand_name == "help":
sys.exit(1)
# special case: list locally installed dists for show and uninstall
should_list_installed = not current.startswith("-") and subcommand_name in [
"show",
"uninstall",
]
if should_list_installed:
env = get_default_environment()
lc = current.lower()
installed = [
dist.canonical_name
for dist in env.iter_installed_distributions(local_only=True)
if dist.canonical_name.startswith(lc)
and dist.canonical_name not in cwords[1:]
]
# if there are no dists installed, fall back to option completion
if installed:
for dist in installed:
print(dist)
sys.exit(1)
should_list_installables = (
not current.startswith("-") and subcommand_name == "install"
)
if should_list_installables:
for path in auto_complete_paths(current, "path"):
print(path)
sys.exit(1)
subcommand = create_command(subcommand_name)
for opt in subcommand.parser.option_list_all:
if opt.help != optparse.SUPPRESS_HELP:
for opt_str in opt._long_opts + opt._short_opts:
options.append((opt_str, opt.nargs))
# filter out previously specified options from available options
prev_opts = [x.split("=")[0] for x in cwords[1 : cword - 1]]
options = [(x, v) for (x, v) in options if x not in prev_opts]
# filter options by current input
options = [(k, v) for k, v in options if k.startswith(current)]
# get completion type given cwords and available subcommand options
completion_type = get_path_completion_type(
cwords,
cword,
subcommand.parser.option_list_all,
)
# get completion files and directories if ``completion_type`` is
# ``<file>``, ``<dir>`` or ``<path>``
if completion_type:
paths = auto_complete_paths(current, completion_type)
options = [(path, 0) for path in paths]
for option in options:
opt_label = option[0]
# append '=' to options which require args
if option[1] and option[0][:2] == "--":
opt_label += "="
print(opt_label)
else:
# show main parser options only when necessary
opts = [i.option_list for i in parser.option_groups]
opts.append(parser.option_list)
flattened_opts = chain.from_iterable(opts)
if current.startswith("-"):
for opt in flattened_opts:
if opt.help != optparse.SUPPRESS_HELP:
subcommands += opt._long_opts + opt._short_opts
else:
# get completion type given cwords and all available options
completion_type = get_path_completion_type(cwords, cword, flattened_opts)
if completion_type:
subcommands = list(auto_complete_paths(current, completion_type))
print(" ".join([x for x in subcommands if x.startswith(current)]))
sys.exit(1)
def get_path_completion_type(
cwords: List[str], cword: int, opts: Iterable[Any]
) -> Optional[str]:
"""Get the type of path completion (``file``, ``dir``, ``path`` or None)
:param cwords: same as the environmental variable ``COMP_WORDS``
:param cword: same as the environmental variable ``COMP_CWORD``
:param opts: The available options to check
:return: path completion type (``file``, ``dir``, ``path`` or None)
"""
if cword < 2 or not cwords[cword - 2].startswith("-"):
return None
for opt in opts:
if opt.help == optparse.SUPPRESS_HELP:
continue
for o in str(opt).split("/"):
if cwords[cword - 2].split("=")[0] == o:
if not opt.metavar or any(
x in ("path", "file", "dir") for x in opt.metavar.split("/")
):
return opt.metavar
return None
def auto_complete_paths(current: str, completion_type: str) -> Iterable[str]:
"""If ``completion_type`` is ``file`` or ``path``, list all regular files
and directories starting with ``current``; otherwise only list directories
starting with ``current``.
:param current: The word to be completed
:param completion_type: path completion type(``file``, ``path`` or ``dir``)
:return: A generator of regular files and/or directories
"""
directory, filename = os.path.split(current)
current_path = os.path.abspath(directory)
# Don't complete paths if they can't be accessed
if not os.access(current_path, os.R_OK):
return
filename = os.path.normcase(filename)
# list all files that start with ``filename``
file_list = (
x for x in os.listdir(current_path) if os.path.normcase(x).startswith(filename)
)
for f in file_list:
opt = os.path.join(current_path, f)
comp_file = os.path.normcase(os.path.join(directory, f))
# complete regular files when there is not ``<dir>`` after option
# complete directories when there is ``<file>``, ``<path>`` or
# ``<dir>``after option
if completion_type != "dir" and os.path.isfile(opt):
yield comp_file
elif os.path.isdir(opt):
yield os.path.join(comp_file, "")

View File

@ -0,0 +1,223 @@
"""Base Command class, and related routines"""
import functools
import logging
import logging.config
import optparse
import os
import sys
import traceback
from optparse import Values
from typing import Any, Callable, List, Optional, Tuple
from pip._vendor.rich import traceback as rich_traceback
from pip._internal.cli import cmdoptions
from pip._internal.cli.command_context import CommandContextMixIn
from pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter
from pip._internal.cli.status_codes import (
ERROR,
PREVIOUS_BUILD_DIR_ERROR,
UNKNOWN_ERROR,
VIRTUALENV_NOT_FOUND,
)
from pip._internal.exceptions import (
BadCommand,
CommandError,
DiagnosticPipError,
InstallationError,
NetworkConnectionError,
PreviousBuildDirError,
UninstallationError,
)
from pip._internal.utils.filesystem import check_path_owner
from pip._internal.utils.logging import BrokenStdoutLoggingError, setup_logging
from pip._internal.utils.misc import get_prog, normalize_path
from pip._internal.utils.temp_dir import TempDirectoryTypeRegistry as TempDirRegistry
from pip._internal.utils.temp_dir import global_tempdir_manager, tempdir_registry
from pip._internal.utils.virtualenv import running_under_virtualenv
__all__ = ["Command"]
logger = logging.getLogger(__name__)
class Command(CommandContextMixIn):
usage: str = ""
ignore_require_venv: bool = False
def __init__(self, name: str, summary: str, isolated: bool = False) -> None:
super().__init__()
self.name = name
self.summary = summary
self.parser = ConfigOptionParser(
usage=self.usage,
prog=f"{get_prog()} {name}",
formatter=UpdatingDefaultsHelpFormatter(),
add_help_option=False,
name=name,
description=self.__doc__,
isolated=isolated,
)
self.tempdir_registry: Optional[TempDirRegistry] = None
# Commands should add options to this option group
optgroup_name = f"{self.name.capitalize()} Options"
self.cmd_opts = optparse.OptionGroup(self.parser, optgroup_name)
# Add the general options
gen_opts = cmdoptions.make_option_group(
cmdoptions.general_group,
self.parser,
)
self.parser.add_option_group(gen_opts)
self.add_options()
def add_options(self) -> None:
pass
def handle_pip_version_check(self, options: Values) -> None:
"""
This is a no-op so that commands by default do not do the pip version
check.
"""
# Make sure we do the pip version check if the index_group options
# are present.
assert not hasattr(options, "no_index")
def run(self, options: Values, args: List[str]) -> int:
raise NotImplementedError
def parse_args(self, args: List[str]) -> Tuple[Values, List[str]]:
# factored out for testability
return self.parser.parse_args(args)
def main(self, args: List[str]) -> int:
try:
with self.main_context():
return self._main(args)
finally:
logging.shutdown()
def _main(self, args: List[str]) -> int:
# We must initialize this before the tempdir manager, otherwise the
# configuration would not be accessible by the time we clean up the
# tempdir manager.
self.tempdir_registry = self.enter_context(tempdir_registry())
# Intentionally set as early as possible so globally-managed temporary
# directories are available to the rest of the code.
self.enter_context(global_tempdir_manager())
options, args = self.parse_args(args)
# Set verbosity so that it can be used elsewhere.
self.verbosity = options.verbose - options.quiet
level_number = setup_logging(
verbosity=self.verbosity,
no_color=options.no_color,
user_log_file=options.log,
)
# TODO: Try to get these passing down from the command?
# without resorting to os.environ to hold these.
# This also affects isolated builds and it should.
if options.no_input:
os.environ["PIP_NO_INPUT"] = "1"
if options.exists_action:
os.environ["PIP_EXISTS_ACTION"] = " ".join(options.exists_action)
if options.require_venv and not self.ignore_require_venv:
# If a venv is required check if it can really be found
if not running_under_virtualenv():
logger.critical("Could not find an activated virtualenv (required).")
sys.exit(VIRTUALENV_NOT_FOUND)
if options.cache_dir:
options.cache_dir = normalize_path(options.cache_dir)
if not check_path_owner(options.cache_dir):
logger.warning(
"The directory '%s' or its parent directory is not owned "
"or is not writable by the current user. The cache "
"has been disabled. Check the permissions and owner of "
"that directory. If executing pip with sudo, you should "
"use sudo's -H flag.",
options.cache_dir,
)
options.cache_dir = None
if "2020-resolver" in options.features_enabled:
logger.warning(
"--use-feature=2020-resolver no longer has any effect, "
"since it is now the default dependency resolver in pip. "
"This will become an error in pip 21.0."
)
def intercepts_unhandled_exc(
run_func: Callable[..., int]
) -> Callable[..., int]:
@functools.wraps(run_func)
def exc_logging_wrapper(*args: Any) -> int:
try:
status = run_func(*args)
assert isinstance(status, int)
return status
except DiagnosticPipError as exc:
logger.error("[present-diagnostic] %s", exc)
logger.debug("Exception information:", exc_info=True)
return ERROR
except PreviousBuildDirError as exc:
logger.critical(str(exc))
logger.debug("Exception information:", exc_info=True)
return PREVIOUS_BUILD_DIR_ERROR
except (
InstallationError,
UninstallationError,
BadCommand,
NetworkConnectionError,
) as exc:
logger.critical(str(exc))
logger.debug("Exception information:", exc_info=True)
return ERROR
except CommandError as exc:
logger.critical("%s", exc)
logger.debug("Exception information:", exc_info=True)
return ERROR
except BrokenStdoutLoggingError:
# Bypass our logger and write any remaining messages to
# stderr because stdout no longer works.
print("ERROR: Pipe to stdout was broken", file=sys.stderr)
if level_number <= logging.DEBUG:
traceback.print_exc(file=sys.stderr)
return ERROR
except KeyboardInterrupt:
logger.critical("Operation cancelled by user")
logger.debug("Exception information:", exc_info=True)
return ERROR
except BaseException:
logger.critical("Exception:", exc_info=True)
return UNKNOWN_ERROR
return exc_logging_wrapper
try:
if not options.debug_mode:
run = intercepts_unhandled_exc(self.run)
else:
run = self.run
rich_traceback.install(show_locals=True)
return run(options, args)
finally:
self.handle_pip_version_check(options)

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,27 @@
from contextlib import ExitStack, contextmanager
from typing import ContextManager, Iterator, TypeVar
_T = TypeVar("_T", covariant=True)
class CommandContextMixIn:
def __init__(self) -> None:
super().__init__()
self._in_main_context = False
self._main_context = ExitStack()
@contextmanager
def main_context(self) -> Iterator[None]:
assert not self._in_main_context
self._in_main_context = True
try:
with self._main_context:
yield
finally:
self._in_main_context = False
def enter_context(self, context_provider: ContextManager[_T]) -> _T:
assert self._in_main_context
return self._main_context.enter_context(context_provider)

View File

@ -0,0 +1,70 @@
"""Primary application entrypoint.
"""
import locale
import logging
import os
import sys
from typing import List, Optional
from pip._internal.cli.autocompletion import autocomplete
from pip._internal.cli.main_parser import parse_command
from pip._internal.commands import create_command
from pip._internal.exceptions import PipError
from pip._internal.utils import deprecation
logger = logging.getLogger(__name__)
# Do not import and use main() directly! Using it directly is actively
# discouraged by pip's maintainers. The name, location and behavior of
# this function is subject to change, so calling it directly is not
# portable across different pip versions.
# In addition, running pip in-process is unsupported and unsafe. This is
# elaborated in detail at
# https://pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program.
# That document also provides suggestions that should work for nearly
# all users that are considering importing and using main() directly.
# However, we know that certain users will still want to invoke pip
# in-process. If you understand and accept the implications of using pip
# in an unsupported manner, the best approach is to use runpy to avoid
# depending on the exact location of this entry point.
# The following example shows how to use runpy to invoke pip in that
# case:
#
# sys.argv = ["pip", your, args, here]
# runpy.run_module("pip", run_name="__main__")
#
# Note that this will exit the process after running, unlike a direct
# call to main. As it is not safe to do any processing after calling
# main, this should not be an issue in practice.
def main(args: Optional[List[str]] = None) -> int:
if args is None:
args = sys.argv[1:]
# Configure our deprecation warnings to be sent through loggers
deprecation.install_warning_logger()
autocomplete()
try:
cmd_name, cmd_args = parse_command(args)
except PipError as exc:
sys.stderr.write(f"ERROR: {exc}")
sys.stderr.write(os.linesep)
sys.exit(1)
# Needed for locale.getpreferredencoding(False) to work
# in pip._internal.utils.encoding.auto_decode
try:
locale.setlocale(locale.LC_ALL, "")
except locale.Error as e:
# setlocale can apparently crash if locale are uninitialized
logger.debug("Ignoring error %s when setting locale", e)
command = create_command(cmd_name, isolated=("--isolated" in cmd_args))
return command.main(cmd_args)

View File

@ -0,0 +1,87 @@
"""A single place for constructing and exposing the main parser
"""
import os
import sys
from typing import List, Tuple
from pip._internal.cli import cmdoptions
from pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter
from pip._internal.commands import commands_dict, get_similar_commands
from pip._internal.exceptions import CommandError
from pip._internal.utils.misc import get_pip_version, get_prog
__all__ = ["create_main_parser", "parse_command"]
def create_main_parser() -> ConfigOptionParser:
"""Creates and returns the main parser for pip's CLI"""
parser = ConfigOptionParser(
usage="\n%prog <command> [options]",
add_help_option=False,
formatter=UpdatingDefaultsHelpFormatter(),
name="global",
prog=get_prog(),
)
parser.disable_interspersed_args()
parser.version = get_pip_version()
# add the general options
gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, parser)
parser.add_option_group(gen_opts)
# so the help formatter knows
parser.main = True # type: ignore
# create command listing for description
description = [""] + [
f"{name:27} {command_info.summary}"
for name, command_info in commands_dict.items()
]
parser.description = "\n".join(description)
return parser
def parse_command(args: List[str]) -> Tuple[str, List[str]]:
parser = create_main_parser()
# Note: parser calls disable_interspersed_args(), so the result of this
# call is to split the initial args into the general options before the
# subcommand and everything else.
# For example:
# args: ['--timeout=5', 'install', '--user', 'INITools']
# general_options: ['--timeout==5']
# args_else: ['install', '--user', 'INITools']
general_options, args_else = parser.parse_args(args)
# --version
if general_options.version:
sys.stdout.write(parser.version)
sys.stdout.write(os.linesep)
sys.exit()
# pip || pip help -> print_help()
if not args_else or (args_else[0] == "help" and len(args_else) == 1):
parser.print_help()
sys.exit()
# the subcommand name
cmd_name = args_else[0]
if cmd_name not in commands_dict:
guess = get_similar_commands(cmd_name)
msg = [f'unknown command "{cmd_name}"']
if guess:
msg.append(f'maybe you meant "{guess}"')
raise CommandError(" - ".join(msg))
# all the args without the subcommand
cmd_args = args[:]
cmd_args.remove(cmd_name)
return cmd_name, cmd_args

View File

@ -0,0 +1,292 @@
"""Base option parser setup"""
import logging
import optparse
import shutil
import sys
import textwrap
from contextlib import suppress
from typing import Any, Dict, Iterator, List, Tuple
from pip._internal.cli.status_codes import UNKNOWN_ERROR
from pip._internal.configuration import Configuration, ConfigurationError
from pip._internal.utils.misc import redact_auth_from_url, strtobool
logger = logging.getLogger(__name__)
class PrettyHelpFormatter(optparse.IndentedHelpFormatter):
"""A prettier/less verbose help formatter for optparse."""
def __init__(self, *args: Any, **kwargs: Any) -> None:
# help position must be aligned with __init__.parseopts.description
kwargs["max_help_position"] = 30
kwargs["indent_increment"] = 1
kwargs["width"] = shutil.get_terminal_size()[0] - 2
super().__init__(*args, **kwargs)
def format_option_strings(self, option: optparse.Option) -> str:
return self._format_option_strings(option)
def _format_option_strings(
self, option: optparse.Option, mvarfmt: str = " <{}>", optsep: str = ", "
) -> str:
"""
Return a comma-separated list of option strings and metavars.
:param option: tuple of (short opt, long opt), e.g: ('-f', '--format')
:param mvarfmt: metavar format string
:param optsep: separator
"""
opts = []
if option._short_opts:
opts.append(option._short_opts[0])
if option._long_opts:
opts.append(option._long_opts[0])
if len(opts) > 1:
opts.insert(1, optsep)
if option.takes_value():
assert option.dest is not None
metavar = option.metavar or option.dest.lower()
opts.append(mvarfmt.format(metavar.lower()))
return "".join(opts)
def format_heading(self, heading: str) -> str:
if heading == "Options":
return ""
return heading + ":\n"
def format_usage(self, usage: str) -> str:
"""
Ensure there is only one newline between usage and the first heading
if there is no description.
"""
msg = "\nUsage: {}\n".format(self.indent_lines(textwrap.dedent(usage), " "))
return msg
def format_description(self, description: str) -> str:
# leave full control over description to us
if description:
if hasattr(self.parser, "main"):
label = "Commands"
else:
label = "Description"
# some doc strings have initial newlines, some don't
description = description.lstrip("\n")
# some doc strings have final newlines and spaces, some don't
description = description.rstrip()
# dedent, then reindent
description = self.indent_lines(textwrap.dedent(description), " ")
description = f"{label}:\n{description}\n"
return description
else:
return ""
def format_epilog(self, epilog: str) -> str:
# leave full control over epilog to us
if epilog:
return epilog
else:
return ""
def indent_lines(self, text: str, indent: str) -> str:
new_lines = [indent + line for line in text.split("\n")]
return "\n".join(new_lines)
class UpdatingDefaultsHelpFormatter(PrettyHelpFormatter):
"""Custom help formatter for use in ConfigOptionParser.
This is updates the defaults before expanding them, allowing
them to show up correctly in the help listing.
Also redact auth from url type options
"""
def expand_default(self, option: optparse.Option) -> str:
default_values = None
if self.parser is not None:
assert isinstance(self.parser, ConfigOptionParser)
self.parser._update_defaults(self.parser.defaults)
assert option.dest is not None
default_values = self.parser.defaults.get(option.dest)
help_text = super().expand_default(option)
if default_values and option.metavar == "URL":
if isinstance(default_values, str):
default_values = [default_values]
# If its not a list, we should abort and just return the help text
if not isinstance(default_values, list):
default_values = []
for val in default_values:
help_text = help_text.replace(val, redact_auth_from_url(val))
return help_text
class CustomOptionParser(optparse.OptionParser):
def insert_option_group(
self, idx: int, *args: Any, **kwargs: Any
) -> optparse.OptionGroup:
"""Insert an OptionGroup at a given position."""
group = self.add_option_group(*args, **kwargs)
self.option_groups.pop()
self.option_groups.insert(idx, group)
return group
@property
def option_list_all(self) -> List[optparse.Option]:
"""Get a list of all options, including those in option groups."""
res = self.option_list[:]
for i in self.option_groups:
res.extend(i.option_list)
return res
class ConfigOptionParser(CustomOptionParser):
"""Custom option parser which updates its defaults by checking the
configuration files and environmental variables"""
def __init__(
self,
*args: Any,
name: str,
isolated: bool = False,
**kwargs: Any,
) -> None:
self.name = name
self.config = Configuration(isolated)
assert self.name
super().__init__(*args, **kwargs)
def check_default(self, option: optparse.Option, key: str, val: Any) -> Any:
try:
return option.check_value(key, val)
except optparse.OptionValueError as exc:
print(f"An error occurred during configuration: {exc}")
sys.exit(3)
def _get_ordered_configuration_items(self) -> Iterator[Tuple[str, Any]]:
# Configuration gives keys in an unordered manner. Order them.
override_order = ["global", self.name, ":env:"]
# Pool the options into different groups
section_items: Dict[str, List[Tuple[str, Any]]] = {
name: [] for name in override_order
}
for section_key, val in self.config.items():
# ignore empty values
if not val:
logger.debug(
"Ignoring configuration key '%s' as it's value is empty.",
section_key,
)
continue
section, key = section_key.split(".", 1)
if section in override_order:
section_items[section].append((key, val))
# Yield each group in their override order
for section in override_order:
for key, val in section_items[section]:
yield key, val
def _update_defaults(self, defaults: Dict[str, Any]) -> Dict[str, Any]:
"""Updates the given defaults with values from the config files and
the environ. Does a little special handling for certain types of
options (lists)."""
# Accumulate complex default state.
self.values = optparse.Values(self.defaults)
late_eval = set()
# Then set the options with those values
for key, val in self._get_ordered_configuration_items():
# '--' because configuration supports only long names
option = self.get_option("--" + key)
# Ignore options not present in this parser. E.g. non-globals put
# in [global] by users that want them to apply to all applicable
# commands.
if option is None:
continue
assert option.dest is not None
if option.action in ("store_true", "store_false"):
try:
val = strtobool(val)
except ValueError:
self.error(
"{} is not a valid value for {} option, " # noqa
"please specify a boolean value like yes/no, "
"true/false or 1/0 instead.".format(val, key)
)
elif option.action == "count":
with suppress(ValueError):
val = strtobool(val)
with suppress(ValueError):
val = int(val)
if not isinstance(val, int) or val < 0:
self.error(
"{} is not a valid value for {} option, " # noqa
"please instead specify either a non-negative integer "
"or a boolean value like yes/no or false/true "
"which is equivalent to 1/0.".format(val, key)
)
elif option.action == "append":
val = val.split()
val = [self.check_default(option, key, v) for v in val]
elif option.action == "callback":
assert option.callback is not None
late_eval.add(option.dest)
opt_str = option.get_opt_string()
val = option.convert_value(opt_str, val)
# From take_action
args = option.callback_args or ()
kwargs = option.callback_kwargs or {}
option.callback(option, opt_str, val, self, *args, **kwargs)
else:
val = self.check_default(option, key, val)
defaults[option.dest] = val
for key in late_eval:
defaults[key] = getattr(self.values, key)
self.values = None
return defaults
def get_default_values(self) -> optparse.Values:
"""Overriding to make updating the defaults after instantiation of
the option parser possible, _update_defaults() does the dirty work."""
if not self.process_default_values:
# Old, pre-Optik 1.5 behaviour.
return optparse.Values(self.defaults)
# Load the configuration, or error out in case of an error
try:
self.config.load()
except ConfigurationError as err:
self.exit(UNKNOWN_ERROR, str(err))
defaults = self._update_defaults(self.defaults.copy()) # ours
for option in self._get_all_options():
assert option.dest is not None
default = defaults.get(option.dest)
if isinstance(default, str):
opt_str = option.get_opt_string()
defaults[option.dest] = option.check_value(opt_str, default)
return optparse.Values(defaults)
def error(self, msg: str) -> None:
self.print_usage(sys.stderr)
self.exit(UNKNOWN_ERROR, f"{msg}\n")

View File

@ -0,0 +1,321 @@
import functools
import itertools
import sys
from signal import SIGINT, default_int_handler, signal
from typing import Any, Callable, Iterator, Optional, Tuple
from pip._vendor.progress.bar import Bar, FillingCirclesBar, IncrementalBar
from pip._vendor.progress.spinner import Spinner
from pip._vendor.rich.progress import (
BarColumn,
DownloadColumn,
FileSizeColumn,
Progress,
ProgressColumn,
SpinnerColumn,
TextColumn,
TimeElapsedColumn,
TimeRemainingColumn,
TransferSpeedColumn,
)
from pip._internal.utils.compat import WINDOWS
from pip._internal.utils.logging import get_indentation
from pip._internal.utils.misc import format_size
try:
from pip._vendor import colorama
# Lots of different errors can come from this, including SystemError and
# ImportError.
except Exception:
colorama = None
DownloadProgressRenderer = Callable[[Iterator[bytes]], Iterator[bytes]]
def _select_progress_class(preferred: Bar, fallback: Bar) -> Bar:
encoding = getattr(preferred.file, "encoding", None)
# If we don't know what encoding this file is in, then we'll just assume
# that it doesn't support unicode and use the ASCII bar.
if not encoding:
return fallback
# Collect all of the possible characters we want to use with the preferred
# bar.
characters = [
getattr(preferred, "empty_fill", ""),
getattr(preferred, "fill", ""),
]
characters += list(getattr(preferred, "phases", []))
# Try to decode the characters we're using for the bar using the encoding
# of the given file, if this works then we'll assume that we can use the
# fancier bar and if not we'll fall back to the plaintext bar.
try:
"".join(characters).encode(encoding)
except UnicodeEncodeError:
return fallback
else:
return preferred
_BaseBar: Any = _select_progress_class(IncrementalBar, Bar)
class InterruptibleMixin:
"""
Helper to ensure that self.finish() gets called on keyboard interrupt.
This allows downloads to be interrupted without leaving temporary state
(like hidden cursors) behind.
This class is similar to the progress library's existing SigIntMixin
helper, but as of version 1.2, that helper has the following problems:
1. It calls sys.exit().
2. It discards the existing SIGINT handler completely.
3. It leaves its own handler in place even after an uninterrupted finish,
which will have unexpected delayed effects if the user triggers an
unrelated keyboard interrupt some time after a progress-displaying
download has already completed, for example.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
"""
Save the original SIGINT handler for later.
"""
# https://github.com/python/mypy/issues/5887
super().__init__(*args, **kwargs) # type: ignore
self.original_handler = signal(SIGINT, self.handle_sigint)
# If signal() returns None, the previous handler was not installed from
# Python, and we cannot restore it. This probably should not happen,
# but if it does, we must restore something sensible instead, at least.
# The least bad option should be Python's default SIGINT handler, which
# just raises KeyboardInterrupt.
if self.original_handler is None:
self.original_handler = default_int_handler
def finish(self) -> None:
"""
Restore the original SIGINT handler after finishing.
This should happen regardless of whether the progress display finishes
normally, or gets interrupted.
"""
super().finish() # type: ignore
signal(SIGINT, self.original_handler)
def handle_sigint(self, signum, frame): # type: ignore
"""
Call self.finish() before delegating to the original SIGINT handler.
This handler should only be in place while the progress display is
active.
"""
self.finish()
self.original_handler(signum, frame)
class SilentBar(Bar):
def update(self) -> None:
pass
class BlueEmojiBar(IncrementalBar):
suffix = "%(percent)d%%"
bar_prefix = " "
bar_suffix = " "
phases = ("\U0001F539", "\U0001F537", "\U0001F535")
class DownloadProgressMixin:
def __init__(self, *args: Any, **kwargs: Any) -> None:
# https://github.com/python/mypy/issues/5887
super().__init__(*args, **kwargs) # type: ignore
self.message: str = (" " * (get_indentation() + 2)) + self.message
@property
def downloaded(self) -> str:
return format_size(self.index) # type: ignore
@property
def download_speed(self) -> str:
# Avoid zero division errors...
if self.avg == 0.0: # type: ignore
return "..."
return format_size(1 / self.avg) + "/s" # type: ignore
@property
def pretty_eta(self) -> str:
if self.eta: # type: ignore
return f"eta {self.eta_td}" # type: ignore
return ""
def iter(self, it): # type: ignore
for x in it:
yield x
# B305 is incorrectly raised here
# https://github.com/PyCQA/flake8-bugbear/issues/59
self.next(len(x)) # noqa: B305
self.finish()
class WindowsMixin:
def __init__(self, *args: Any, **kwargs: Any) -> None:
# The Windows terminal does not support the hide/show cursor ANSI codes
# even with colorama. So we'll ensure that hide_cursor is False on
# Windows.
# This call needs to go before the super() call, so that hide_cursor
# is set in time. The base progress bar class writes the "hide cursor"
# code to the terminal in its init, so if we don't set this soon
# enough, we get a "hide" with no corresponding "show"...
if WINDOWS and self.hide_cursor: # type: ignore
self.hide_cursor = False
# https://github.com/python/mypy/issues/5887
super().__init__(*args, **kwargs) # type: ignore
# Check if we are running on Windows and we have the colorama module,
# if we do then wrap our file with it.
if WINDOWS and colorama:
self.file = colorama.AnsiToWin32(self.file) # type: ignore
# The progress code expects to be able to call self.file.isatty()
# but the colorama.AnsiToWin32() object doesn't have that, so we'll
# add it.
self.file.isatty = lambda: self.file.wrapped.isatty()
# The progress code expects to be able to call self.file.flush()
# but the colorama.AnsiToWin32() object doesn't have that, so we'll
# add it.
self.file.flush = lambda: self.file.wrapped.flush()
class BaseDownloadProgressBar(WindowsMixin, InterruptibleMixin, DownloadProgressMixin):
file = sys.stdout
message = "%(percent)d%%"
suffix = "%(downloaded)s %(download_speed)s %(pretty_eta)s"
class DefaultDownloadProgressBar(BaseDownloadProgressBar, _BaseBar):
pass
class DownloadSilentBar(BaseDownloadProgressBar, SilentBar):
pass
class DownloadBar(BaseDownloadProgressBar, Bar):
pass
class DownloadFillingCirclesBar(BaseDownloadProgressBar, FillingCirclesBar):
pass
class DownloadBlueEmojiProgressBar(BaseDownloadProgressBar, BlueEmojiBar):
pass
class DownloadProgressSpinner(
WindowsMixin, InterruptibleMixin, DownloadProgressMixin, Spinner
):
file = sys.stdout
suffix = "%(downloaded)s %(download_speed)s"
def next_phase(self) -> str:
if not hasattr(self, "_phaser"):
self._phaser = itertools.cycle(self.phases)
return next(self._phaser)
def update(self) -> None:
message = self.message % self
phase = self.next_phase()
suffix = self.suffix % self
line = "".join(
[
message,
" " if message else "",
phase,
" " if suffix else "",
suffix,
]
)
self.writeln(line)
BAR_TYPES = {
"off": (DownloadSilentBar, DownloadSilentBar),
"on": (DefaultDownloadProgressBar, DownloadProgressSpinner),
"ascii": (DownloadBar, DownloadProgressSpinner),
"pretty": (DownloadFillingCirclesBar, DownloadProgressSpinner),
"emoji": (DownloadBlueEmojiProgressBar, DownloadProgressSpinner),
}
def _legacy_progress_bar(
progress_bar: str, max: Optional[int]
) -> DownloadProgressRenderer:
if max is None or max == 0:
return BAR_TYPES[progress_bar][1]().iter # type: ignore
else:
return BAR_TYPES[progress_bar][0](max=max).iter
#
# Modern replacement, for our legacy progress bars.
#
def _rich_progress_bar(
iterable: Iterator[bytes],
*,
bar_type: str,
size: int,
) -> Iterator[bytes]:
assert bar_type == "on", "This should only be used in the default mode."
if not size:
total = float("inf")
columns: Tuple[ProgressColumn, ...] = (
TextColumn("[progress.description]{task.description}"),
SpinnerColumn("line", speed=1.5),
FileSizeColumn(),
TransferSpeedColumn(),
TimeElapsedColumn(),
)
else:
total = size
columns = (
TextColumn("[progress.description]{task.description}"),
BarColumn(),
DownloadColumn(),
TransferSpeedColumn(),
TextColumn("eta"),
TimeRemainingColumn(),
)
progress = Progress(*columns, refresh_per_second=30)
task_id = progress.add_task(" " * (get_indentation() + 2), total=total)
with progress:
for chunk in iterable:
yield chunk
progress.update(task_id, advance=len(chunk))
def get_download_progress_renderer(
*, bar_type: str, size: Optional[int] = None
) -> DownloadProgressRenderer:
"""Get an object that can be used to render the download progress.
Returns a callable, that takes an iterable to "wrap".
"""
if bar_type == "on":
return functools.partial(_rich_progress_bar, bar_type=bar_type, size=size)
elif bar_type == "off":
return iter # no-op, when passed an iterator
else:
return _legacy_progress_bar(bar_type, size)

View File

@ -0,0 +1,506 @@
"""Contains the Command base classes that depend on PipSession.
The classes in this module are in a separate module so the commands not
needing download / PackageFinder capability don't unnecessarily import the
PackageFinder machinery and all its vendored dependencies, etc.
"""
import logging
import os
import sys
from functools import partial
from optparse import Values
from typing import Any, List, Optional, Tuple
from pip._internal.cache import WheelCache
from pip._internal.cli import cmdoptions
from pip._internal.cli.base_command import Command
from pip._internal.cli.command_context import CommandContextMixIn
from pip._internal.exceptions import CommandError, PreviousBuildDirError
from pip._internal.index.collector import LinkCollector
from pip._internal.index.package_finder import PackageFinder
from pip._internal.models.selection_prefs import SelectionPreferences
from pip._internal.models.target_python import TargetPython
from pip._internal.network.session import PipSession
from pip._internal.operations.prepare import RequirementPreparer
from pip._internal.req.constructors import (
install_req_from_editable,
install_req_from_line,
install_req_from_parsed_requirement,
install_req_from_req_string,
)
from pip._internal.req.req_file import parse_requirements
from pip._internal.req.req_install import InstallRequirement
from pip._internal.req.req_tracker import RequirementTracker
from pip._internal.resolution.base import BaseResolver
from pip._internal.self_outdated_check import pip_self_version_check
from pip._internal.utils.deprecation import deprecated
from pip._internal.utils.temp_dir import (
TempDirectory,
TempDirectoryTypeRegistry,
tempdir_kinds,
)
from pip._internal.utils.virtualenv import running_under_virtualenv
logger = logging.getLogger(__name__)
class SessionCommandMixin(CommandContextMixIn):
"""
A class mixin for command classes needing _build_session().
"""
def __init__(self) -> None:
super().__init__()
self._session: Optional[PipSession] = None
@classmethod
def _get_index_urls(cls, options: Values) -> Optional[List[str]]:
"""Return a list of index urls from user-provided options."""
index_urls = []
if not getattr(options, "no_index", False):
url = getattr(options, "index_url", None)
if url:
index_urls.append(url)
urls = getattr(options, "extra_index_urls", None)
if urls:
index_urls.extend(urls)
# Return None rather than an empty list
return index_urls or None
def get_default_session(self, options: Values) -> PipSession:
"""Get a default-managed session."""
if self._session is None:
self._session = self.enter_context(self._build_session(options))
# there's no type annotation on requests.Session, so it's
# automatically ContextManager[Any] and self._session becomes Any,
# then https://github.com/python/mypy/issues/7696 kicks in
assert self._session is not None
return self._session
def _build_session(
self,
options: Values,
retries: Optional[int] = None,
timeout: Optional[int] = None,
) -> PipSession:
assert not options.cache_dir or os.path.isabs(options.cache_dir)
session = PipSession(
cache=(
os.path.join(options.cache_dir, "http") if options.cache_dir else None
),
retries=retries if retries is not None else options.retries,
trusted_hosts=options.trusted_hosts,
index_urls=self._get_index_urls(options),
)
# Handle custom ca-bundles from the user
if options.cert:
session.verify = options.cert
# Handle SSL client certificate
if options.client_cert:
session.cert = options.client_cert
# Handle timeouts
if options.timeout or timeout:
session.timeout = timeout if timeout is not None else options.timeout
# Handle configured proxies
if options.proxy:
session.proxies = {
"http": options.proxy,
"https": options.proxy,
}
# Determine if we can prompt the user for authentication or not
session.auth.prompting = not options.no_input
return session
class IndexGroupCommand(Command, SessionCommandMixin):
"""
Abstract base class for commands with the index_group options.
This also corresponds to the commands that permit the pip version check.
"""
def handle_pip_version_check(self, options: Values) -> None:
"""
Do the pip version check if not disabled.
This overrides the default behavior of not doing the check.
"""
# Make sure the index_group options are present.
assert hasattr(options, "no_index")
if options.disable_pip_version_check or options.no_index:
return
# Otherwise, check if we're using the latest version of pip available.
session = self._build_session(
options, retries=0, timeout=min(5, options.timeout)
)
with session:
pip_self_version_check(session, options)
KEEPABLE_TEMPDIR_TYPES = [
tempdir_kinds.BUILD_ENV,
tempdir_kinds.EPHEM_WHEEL_CACHE,
tempdir_kinds.REQ_BUILD,
]
def warn_if_run_as_root() -> None:
"""Output a warning for sudo users on Unix.
In a virtual environment, sudo pip still writes to virtualenv.
On Windows, users may run pip as Administrator without issues.
This warning only applies to Unix root users outside of virtualenv.
"""
if running_under_virtualenv():
return
if not hasattr(os, "getuid"):
return
# On Windows, there are no "system managed" Python packages. Installing as
# Administrator via pip is the correct way of updating system environments.
#
# We choose sys.platform over utils.compat.WINDOWS here to enable Mypy platform
# checks: https://mypy.readthedocs.io/en/stable/common_issues.html
if sys.platform == "win32" or sys.platform == "cygwin":
return
if os.getuid() != 0:
return
logger.warning(
"Running pip as the 'root' user can result in broken permissions and "
"conflicting behaviour with the system package manager. "
"It is recommended to use a virtual environment instead: "
"https://pip.pypa.io/warnings/venv"
)
def with_cleanup(func: Any) -> Any:
"""Decorator for common logic related to managing temporary
directories.
"""
def configure_tempdir_registry(registry: TempDirectoryTypeRegistry) -> None:
for t in KEEPABLE_TEMPDIR_TYPES:
registry.set_delete(t, False)
def wrapper(
self: RequirementCommand, options: Values, args: List[Any]
) -> Optional[int]:
assert self.tempdir_registry is not None
if options.no_clean:
configure_tempdir_registry(self.tempdir_registry)
try:
return func(self, options, args)
except PreviousBuildDirError:
# This kind of conflict can occur when the user passes an explicit
# build directory with a pre-existing folder. In that case we do
# not want to accidentally remove it.
configure_tempdir_registry(self.tempdir_registry)
raise
return wrapper
class RequirementCommand(IndexGroupCommand):
def __init__(self, *args: Any, **kw: Any) -> None:
super().__init__(*args, **kw)
self.cmd_opts.add_option(cmdoptions.no_clean())
@staticmethod
def determine_resolver_variant(options: Values) -> str:
"""Determines which resolver should be used, based on the given options."""
if "legacy-resolver" in options.deprecated_features_enabled:
return "legacy"
return "2020-resolver"
@staticmethod
def determine_build_failure_suppression(options: Values) -> bool:
"""Determines whether build failures should be suppressed and backtracked on."""
if "backtrack-on-build-failures" not in options.deprecated_features_enabled:
return False
if "legacy-resolver" in options.deprecated_features_enabled:
raise CommandError("Cannot backtrack with legacy resolver.")
deprecated(
reason=(
"Backtracking on build failures can mask issues related to how "
"a package generates metadata or builds a wheel. This flag will "
"be removed in pip 22.2."
),
gone_in=None,
replacement=(
"avoiding known-bad versions by explicitly telling pip to ignore them "
"(either directly as requirements, or via a constraints file)"
),
feature_flag=None,
issue=10655,
)
return True
@classmethod
def make_requirement_preparer(
cls,
temp_build_dir: TempDirectory,
options: Values,
req_tracker: RequirementTracker,
session: PipSession,
finder: PackageFinder,
use_user_site: bool,
download_dir: Optional[str] = None,
verbosity: int = 0,
) -> RequirementPreparer:
"""
Create a RequirementPreparer instance for the given parameters.
"""
temp_build_dir_path = temp_build_dir.path
assert temp_build_dir_path is not None
resolver_variant = cls.determine_resolver_variant(options)
if resolver_variant == "2020-resolver":
lazy_wheel = "fast-deps" in options.features_enabled
if lazy_wheel:
logger.warning(
"pip is using lazily downloaded wheels using HTTP "
"range requests to obtain dependency information. "
"This experimental feature is enabled through "
"--use-feature=fast-deps and it is not ready for "
"production."
)
else:
lazy_wheel = False
if "fast-deps" in options.features_enabled:
logger.warning(
"fast-deps has no effect when used with the legacy resolver."
)
in_tree_build = "out-of-tree-build" not in options.deprecated_features_enabled
if "in-tree-build" in options.features_enabled:
deprecated(
reason="In-tree builds are now the default.",
replacement="to remove the --use-feature=in-tree-build flag",
gone_in="22.1",
)
if "out-of-tree-build" in options.deprecated_features_enabled:
deprecated(
reason="Out-of-tree builds are deprecated.",
replacement=None,
gone_in="22.1",
)
if options.progress_bar not in {"on", "off"}:
deprecated(
reason="Custom progress bar styles are deprecated",
replacement="to use the default progress bar style.",
gone_in="22.1",
)
return RequirementPreparer(
build_dir=temp_build_dir_path,
src_dir=options.src_dir,
download_dir=download_dir,
build_isolation=options.build_isolation,
req_tracker=req_tracker,
session=session,
progress_bar=options.progress_bar,
finder=finder,
require_hashes=options.require_hashes,
use_user_site=use_user_site,
lazy_wheel=lazy_wheel,
verbosity=verbosity,
in_tree_build=in_tree_build,
)
@classmethod
def make_resolver(
cls,
preparer: RequirementPreparer,
finder: PackageFinder,
options: Values,
wheel_cache: Optional[WheelCache] = None,
use_user_site: bool = False,
ignore_installed: bool = True,
ignore_requires_python: bool = False,
force_reinstall: bool = False,
upgrade_strategy: str = "to-satisfy-only",
use_pep517: Optional[bool] = None,
py_version_info: Optional[Tuple[int, ...]] = None,
) -> BaseResolver:
"""
Create a Resolver instance for the given parameters.
"""
make_install_req = partial(
install_req_from_req_string,
isolated=options.isolated_mode,
use_pep517=use_pep517,
)
suppress_build_failures = cls.determine_build_failure_suppression(options)
resolver_variant = cls.determine_resolver_variant(options)
# The long import name and duplicated invocation is needed to convince
# Mypy into correctly typechecking. Otherwise it would complain the
# "Resolver" class being redefined.
if resolver_variant == "2020-resolver":
import pip._internal.resolution.resolvelib.resolver
return pip._internal.resolution.resolvelib.resolver.Resolver(
preparer=preparer,
finder=finder,
wheel_cache=wheel_cache,
make_install_req=make_install_req,
use_user_site=use_user_site,
ignore_dependencies=options.ignore_dependencies,
ignore_installed=ignore_installed,
ignore_requires_python=ignore_requires_python,
force_reinstall=force_reinstall,
upgrade_strategy=upgrade_strategy,
py_version_info=py_version_info,
suppress_build_failures=suppress_build_failures,
)
import pip._internal.resolution.legacy.resolver
return pip._internal.resolution.legacy.resolver.Resolver(
preparer=preparer,
finder=finder,
wheel_cache=wheel_cache,
make_install_req=make_install_req,
use_user_site=use_user_site,
ignore_dependencies=options.ignore_dependencies,
ignore_installed=ignore_installed,
ignore_requires_python=ignore_requires_python,
force_reinstall=force_reinstall,
upgrade_strategy=upgrade_strategy,
py_version_info=py_version_info,
)
def get_requirements(
self,
args: List[str],
options: Values,
finder: PackageFinder,
session: PipSession,
) -> List[InstallRequirement]:
"""
Parse command-line arguments into the corresponding requirements.
"""
requirements: List[InstallRequirement] = []
for filename in options.constraints:
for parsed_req in parse_requirements(
filename,
constraint=True,
finder=finder,
options=options,
session=session,
):
req_to_add = install_req_from_parsed_requirement(
parsed_req,
isolated=options.isolated_mode,
user_supplied=False,
)
requirements.append(req_to_add)
for req in args:
req_to_add = install_req_from_line(
req,
None,
isolated=options.isolated_mode,
use_pep517=options.use_pep517,
user_supplied=True,
)
requirements.append(req_to_add)
for req in options.editables:
req_to_add = install_req_from_editable(
req,
user_supplied=True,
isolated=options.isolated_mode,
use_pep517=options.use_pep517,
)
requirements.append(req_to_add)
# NOTE: options.require_hashes may be set if --require-hashes is True
for filename in options.requirements:
for parsed_req in parse_requirements(
filename, finder=finder, options=options, session=session
):
req_to_add = install_req_from_parsed_requirement(
parsed_req,
isolated=options.isolated_mode,
use_pep517=options.use_pep517,
user_supplied=True,
)
requirements.append(req_to_add)
# If any requirement has hash options, enable hash checking.
if any(req.has_hash_options for req in requirements):
options.require_hashes = True
if not (args or options.editables or options.requirements):
opts = {"name": self.name}
if options.find_links:
raise CommandError(
"You must give at least one requirement to {name} "
'(maybe you meant "pip {name} {links}"?)'.format(
**dict(opts, links=" ".join(options.find_links))
)
)
else:
raise CommandError(
"You must give at least one requirement to {name} "
'(see "pip help {name}")'.format(**opts)
)
return requirements
@staticmethod
def trace_basic_info(finder: PackageFinder) -> None:
"""
Trace basic information about the provided objects.
"""
# Display where finder is looking for packages
search_scope = finder.search_scope
locations = search_scope.get_formatted_locations()
if locations:
logger.info(locations)
def _build_package_finder(
self,
options: Values,
session: PipSession,
target_python: Optional[TargetPython] = None,
ignore_requires_python: Optional[bool] = None,
) -> PackageFinder:
"""
Create a package finder appropriate to this requirement command.
:param ignore_requires_python: Whether to ignore incompatible
"Requires-Python" values in links. Defaults to False.
"""
link_collector = LinkCollector.create(session, options=options)
selection_prefs = SelectionPreferences(
allow_yanked=True,
format_control=options.format_control,
allow_all_prereleases=options.pre,
prefer_binary=options.prefer_binary,
ignore_requires_python=ignore_requires_python,
)
return PackageFinder.create(
link_collector=link_collector,
selection_prefs=selection_prefs,
target_python=target_python,
use_deprecated_html5lib="html5lib" in options.deprecated_features_enabled,
)

View File

@ -0,0 +1,157 @@
import contextlib
import itertools
import logging
import sys
import time
from typing import IO, Iterator
from pip._vendor.progress import HIDE_CURSOR, SHOW_CURSOR
from pip._internal.utils.compat import WINDOWS
from pip._internal.utils.logging import get_indentation
logger = logging.getLogger(__name__)
class SpinnerInterface:
def spin(self) -> None:
raise NotImplementedError()
def finish(self, final_status: str) -> None:
raise NotImplementedError()
class InteractiveSpinner(SpinnerInterface):
def __init__(
self,
message: str,
file: IO[str] = None,
spin_chars: str = "-\\|/",
# Empirically, 8 updates/second looks nice
min_update_interval_seconds: float = 0.125,
):
self._message = message
if file is None:
file = sys.stdout
self._file = file
self._rate_limiter = RateLimiter(min_update_interval_seconds)
self._finished = False
self._spin_cycle = itertools.cycle(spin_chars)
self._file.write(" " * get_indentation() + self._message + " ... ")
self._width = 0
def _write(self, status: str) -> None:
assert not self._finished
# Erase what we wrote before by backspacing to the beginning, writing
# spaces to overwrite the old text, and then backspacing again
backup = "\b" * self._width
self._file.write(backup + " " * self._width + backup)
# Now we have a blank slate to add our status
self._file.write(status)
self._width = len(status)
self._file.flush()
self._rate_limiter.reset()
def spin(self) -> None:
if self._finished:
return
if not self._rate_limiter.ready():
return
self._write(next(self._spin_cycle))
def finish(self, final_status: str) -> None:
if self._finished:
return
self._write(final_status)
self._file.write("\n")
self._file.flush()
self._finished = True
# Used for dumb terminals, non-interactive installs (no tty), etc.
# We still print updates occasionally (once every 60 seconds by default) to
# act as a keep-alive for systems like Travis-CI that take lack-of-output as
# an indication that a task has frozen.
class NonInteractiveSpinner(SpinnerInterface):
def __init__(self, message: str, min_update_interval_seconds: float = 60.0) -> None:
self._message = message
self._finished = False
self._rate_limiter = RateLimiter(min_update_interval_seconds)
self._update("started")
def _update(self, status: str) -> None:
assert not self._finished
self._rate_limiter.reset()
logger.info("%s: %s", self._message, status)
def spin(self) -> None:
if self._finished:
return
if not self._rate_limiter.ready():
return
self._update("still running...")
def finish(self, final_status: str) -> None:
if self._finished:
return
self._update(f"finished with status '{final_status}'")
self._finished = True
class RateLimiter:
def __init__(self, min_update_interval_seconds: float) -> None:
self._min_update_interval_seconds = min_update_interval_seconds
self._last_update: float = 0
def ready(self) -> bool:
now = time.time()
delta = now - self._last_update
return delta >= self._min_update_interval_seconds
def reset(self) -> None:
self._last_update = time.time()
@contextlib.contextmanager
def open_spinner(message: str) -> Iterator[SpinnerInterface]:
# Interactive spinner goes directly to sys.stdout rather than being routed
# through the logging system, but it acts like it has level INFO,
# i.e. it's only displayed if we're at level INFO or better.
# Non-interactive spinner goes through the logging system, so it is always
# in sync with logging configuration.
if sys.stdout.isatty() and logger.getEffectiveLevel() <= logging.INFO:
spinner: SpinnerInterface = InteractiveSpinner(message)
else:
spinner = NonInteractiveSpinner(message)
try:
with hidden_cursor(sys.stdout):
yield spinner
except KeyboardInterrupt:
spinner.finish("canceled")
raise
except Exception:
spinner.finish("error")
raise
else:
spinner.finish("done")
@contextlib.contextmanager
def hidden_cursor(file: IO[str]) -> Iterator[None]:
# The Windows terminal does not support the hide/show cursor ANSI codes,
# even via colorama. So don't even try.
if WINDOWS:
yield
# We don't want to clutter the output with control characters if we're
# writing to a file, or if the user is running with --quiet.
# See https://github.com/pypa/pip/issues/3418
elif not file.isatty() or logger.getEffectiveLevel() > logging.INFO:
yield
else:
file.write(HIDE_CURSOR)
try:
yield
finally:
file.write(SHOW_CURSOR)

View File

@ -0,0 +1,6 @@
SUCCESS = 0
ERROR = 1
UNKNOWN_ERROR = 2
VIRTUALENV_NOT_FOUND = 3
PREVIOUS_BUILD_DIR_ERROR = 4
NO_MATCHES_FOUND = 23

View File

@ -0,0 +1,127 @@
"""
Package containing all pip commands
"""
import importlib
from collections import namedtuple
from typing import Any, Dict, Optional
from pip._internal.cli.base_command import Command
CommandInfo = namedtuple("CommandInfo", "module_path, class_name, summary")
# This dictionary does a bunch of heavy lifting for help output:
# - Enables avoiding additional (costly) imports for presenting `--help`.
# - The ordering matters for help display.
#
# Even though the module path starts with the same "pip._internal.commands"
# prefix, the full path makes testing easier (specifically when modifying
# `commands_dict` in test setup / teardown).
commands_dict: Dict[str, CommandInfo] = {
"install": CommandInfo(
"pip._internal.commands.install",
"InstallCommand",
"Install packages.",
),
"download": CommandInfo(
"pip._internal.commands.download",
"DownloadCommand",
"Download packages.",
),
"uninstall": CommandInfo(
"pip._internal.commands.uninstall",
"UninstallCommand",
"Uninstall packages.",
),
"freeze": CommandInfo(
"pip._internal.commands.freeze",
"FreezeCommand",
"Output installed packages in requirements format.",
),
"list": CommandInfo(
"pip._internal.commands.list",
"ListCommand",
"List installed packages.",
),
"show": CommandInfo(
"pip._internal.commands.show",
"ShowCommand",
"Show information about installed packages.",
),
"check": CommandInfo(
"pip._internal.commands.check",
"CheckCommand",
"Verify installed packages have compatible dependencies.",
),
"config": CommandInfo(
"pip._internal.commands.configuration",
"ConfigurationCommand",
"Manage local and global configuration.",
),
"search": CommandInfo(
"pip._internal.commands.search",
"SearchCommand",
"Search PyPI for packages.",
),
"cache": CommandInfo(
"pip._internal.commands.cache",
"CacheCommand",
"Inspect and manage pip's wheel cache.",
),
"index": CommandInfo(
"pip._internal.commands.index",
"IndexCommand",
"Inspect information available from package indexes.",
),
"wheel": CommandInfo(
"pip._internal.commands.wheel",
"WheelCommand",
"Build wheels from your requirements.",
),
"hash": CommandInfo(
"pip._internal.commands.hash",
"HashCommand",
"Compute hashes of package archives.",
),
"completion": CommandInfo(
"pip._internal.commands.completion",
"CompletionCommand",
"A helper command used for command completion.",
),
"debug": CommandInfo(
"pip._internal.commands.debug",
"DebugCommand",
"Show information useful for debugging.",
),
"help": CommandInfo(
"pip._internal.commands.help",
"HelpCommand",
"Show help for commands.",
),
}
def create_command(name: str, **kwargs: Any) -> Command:
"""
Create an instance of the Command class with the given name.
"""
module_path, class_name, summary = commands_dict[name]
module = importlib.import_module(module_path)
command_class = getattr(module, class_name)
command = command_class(name=name, summary=summary, **kwargs)
return command
def get_similar_commands(name: str) -> Optional[str]:
"""Command name auto-correct."""
from difflib import get_close_matches
name = name.lower()
close_commands = get_close_matches(name, commands_dict.keys())
if close_commands:
return close_commands[0]
else:
return None

Some files were not shown because too many files have changed in this diff Show More