Search is not available for this dataset
content
stringlengths
60
399M
max_stars_repo_name
stringlengths
6
110
<|start_filename|>emoticonlib/src/main/java/com/pandaq/emoticonlib/base/BaseActivity.java<|end_filename|> package com.pandaq.emoticonlib.base; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import com.pandaq.emoticonlib.R; /** * Created by huxinyu on 2017/11/20 0020. * description : */ public class BaseActivity extends AppCompatActivity { private PermissionCall mPermissionCall; private final int permissionRequestCode = 110; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected void onResume() { super.onResume(); } @Override protected void onStart() { super.onStart(); } @Override protected void onStop() { super.onStop(); } @Override protected void onDestroy() { super.onDestroy(); } /* 处理权限问题*/ /** * 对子类提供的申请权限方法 * * @param permissions 申请的权限 */ @RequiresApi(api = Build.VERSION_CODES.M) public void requestRunTimePermissions(String[] permissions, PermissionCall call) { if (permissions == null || permissions.length == 0) return; mPermissionCall = call; if ((Build.VERSION.SDK_INT < Build.VERSION_CODES.M) || checkPermissionGranted(permissions)) { //提示已经拥有权限 mPermissionCall.requestSuccess(); } else { //申请权限 requestPermission(permissions, permissionRequestCode); } } public boolean checkPermissionGranted(String... permissions) { boolean result = true; for (String p : permissions) { if (ActivityCompat.checkSelfPermission(this, p) != PackageManager.PERMISSION_GRANTED) { result = false; break; } } return result; } private void requestPermission(final String[] permissions, final int requestCode) { new AlertDialog.Builder(this) .setTitle(R.string.attention) .setMessage(R.string.content_to_request_permission) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ActivityCompat.requestPermissions(BaseActivity.this, permissions, requestCode); } }).show(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == permissionRequestCode) { if (verifyPermissions(grantResults)) { mPermissionCall.requestSuccess(); mPermissionCall = null; } else { mPermissionCall.refused(); mPermissionCall = null; } } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } public boolean verifyPermissions(int[] grantResults) { // At least one result must be checked. if (grantResults.length < 1) { return false; } // Verify that each required permission has been granted, otherwise return false. for (int result : grantResults) { if (result != PackageManager.PERMISSION_GRANTED) { return false; } } return true; } public interface PermissionCall { //申请成功 void requestSuccess(); //拒绝 void refused(); } } <|start_filename|>app/src/main/java/com/pandaq/pandaemoview/activity/MainActivity.java<|end_filename|> package com.pandaq.pandaemoview.activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.pandaq.emoticonlib.KeyBoardManager; import com.pandaq.emoticonlib.PandaEmoManager; import com.pandaq.emoticonlib.PandaEmoTranslator; import com.pandaq.emoticonlib.emoticons.EmoticonManager; import com.pandaq.emoticonlib.emoticons.gif.AnimatedGifDrawable; import com.pandaq.emoticonlib.listeners.IEmoticonMenuClickListener; import com.pandaq.emoticonlib.listeners.IStickerSelectedListener; import com.pandaq.emoticonlib.photopicker.ManageCustomActivity; import com.pandaq.emoticonlib.view.PandaEmoEditText; import com.pandaq.emoticonlib.view.PandaEmoView; import com.pandaq.pandaemoview.R; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import butterknife.BindView; import butterknife.ButterKnife; public class MainActivity extends AppCompatActivity { @BindView(R.id.toptitle) TextView mToptitle; @BindView(R.id.iv_call_menu) ImageView mIvCallMenu; @BindView(R.id.iv_call_emoticon) ImageView mIvCallEmoticon; @BindView(R.id.et_input) PandaEmoEditText mEtInput; @BindView(R.id.text_title) TextView mTextTitle; @BindView(R.id.tv_input_content) TextView mTvInputContent; @BindView(R.id.img_title) TextView mImgTitle; @BindView(R.id.iv_img_pic) ImageView mIvImgPic; @BindView(R.id.rl_content) RelativeLayout mRlContent; @BindView(R.id.emoticonView) PandaEmoView mEmoticonView; @BindView(R.id.rl_bottom_layout) RelativeLayout mRlBottomLayout; @BindView(R.id.tv_send) TextView mTvSend; private KeyBoardManager emotionKeyboard; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); mEmoticonView.attachEditText(mEtInput); // Tab 菜单按钮监听 mEmoticonView.setEmoticonMenuClickListener(new IEmoticonMenuClickListener() { @Override public void onTabAddClick(View view) { Intent intent = new Intent(MainActivity.this, AddEmoActivity.class); startActivity(intent); } @Override public void onTabSettingClick(View view) { Intent intent = new Intent(MainActivity.this, SettingActivity.class); startActivity(intent); } }); // 表情贴图选中监听 mEmoticonView.setEmoticonSelectedListener(new IStickerSelectedListener() { @Override public void onStickerSelected(String title, String stickerBitmapPath) { PandaEmoManager.getInstance().getIImageLoader().displayImage(stickerBitmapPath, mIvImgPic); } @Override public void onCustomAdd() { //添加按钮 Toast.makeText(MainActivity.this, "点击添加自定义表情", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(MainActivity.this, ManageCustomActivity.class); startActivity(intent); } }); mEtInput.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (!TextUtils.isEmpty(mEtInput.getText())) { mTvSend.setVisibility(View.VISIBLE); mIvCallMenu.setVisibility(View.GONE); } else { mTvSend.setVisibility(View.GONE); mIvCallMenu.setVisibility(View.VISIBLE); } } }); mTvSend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String send = mEtInput.getText().toString(); mTvInputContent.setText(PandaEmoTranslator .getInstance() .makeGifSpannable(getLocalClassName(), send, new AnimatedGifDrawable.RunGifCallBack() { @Override public void run() { mTvInputContent.postInvalidate(); } })); mEtInput.setText(""); } }); initEmotionKeyboard(); // 将测试表情包压缩文件copy到SD卡 copyStickerAndUnZip("ziptest", getApplicationContext().getFilesDir().getAbsolutePath()); } private void initEmotionKeyboard() { emotionKeyboard = KeyBoardManager.with(this) .bindToEmotionButton(mIvCallEmoticon, mIvCallMenu) .setEmotionView(mEmoticonView) .bindToLockContent(mRlContent) .setOnInputListener(new KeyBoardManager.OnInputShowListener() { @Override public void showInputView(boolean show) { } }); emotionKeyboard.setOnEmotionButtonOnClickListener(new KeyBoardManager.OnEmotionButtonOnClickListener() { @Override public boolean onEmotionButtonOnClickListener(View view) { if (view.getId() == R.id.iv_call_menu) { int softInputHeight = emotionKeyboard.getKeyBoardHeight(); ViewGroup.LayoutParams params = mRlBottomLayout.getLayoutParams(); if (mRlBottomLayout.isShown()) { mRlBottomLayout.setVisibility(View.GONE); emotionKeyboard.showInputLayout(); } else { params.height = softInputHeight; mRlBottomLayout.setLayoutParams(params); mRlBottomLayout.setVisibility(View.VISIBLE); emotionKeyboard.hideInputLayout(); } // 重写逻辑时一定要返回 ture 拦截 KeyBoardManager 中的默认逻辑 return true; } else if (view.getId() == R.id.iv_call_emoticon) { mRlBottomLayout.setVisibility(View.GONE); return false;// 不破坏表情按钮的处理逻辑,只是隐藏显示的菜单页 } return false; } }); } @Override public void onBackPressed() { if (!mRlBottomLayout.isShown()) { if (!emotionKeyboard.interceptBackPress()) { finish(); } } else { mRlBottomLayout.setVisibility(View.GONE); } } private void copyStickerAndUnZip(String assetDir, String dir) { copyStickerToSdCard(assetDir, dir); } private void copyStickerToSdCard(String assetDir, String dir) { String[] files; try { files = this.getResources().getAssets().list(assetDir); } catch (IOException e1) { e1.printStackTrace(); return; } File mWorkingPath = new File(dir); // if this directory does not exists, make one. if (!mWorkingPath.exists()) { mWorkingPath.mkdirs(); } for (String file : files) { try { // we make sure file name not contains '.' to be a folder. if (!file.contains(".")) { if (0 == assetDir.length()) { copyStickerToSdCard(file, dir + file + "/"); } else { copyStickerToSdCard(assetDir + "/" + file, dir + file + "/"); } continue; } File outFile = new File(mWorkingPath, file); if (outFile.exists()) { outFile.delete(); } InputStream in; if (0 != assetDir.length()) { in = this.getAssets().open(assetDir + "/" + file); } else { in = this.getAssets().open(file); } OutputStream out = new FileOutputStream(outFile); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } } @Override protected void onResume() { super.onResume(); PandaEmoTranslator.getInstance().resumeGif(getLocalClassName()); } @Override protected void onPause() { super.onPause(); PandaEmoTranslator.getInstance().pauseGif(); } @Override protected void onDestroy() { super.onDestroy(); PandaEmoTranslator.getInstance().clearGif(getLocalClassName()); } } <|start_filename|>app/src/main/java/com/pandaq/pandaemoview/StickerEntity.java<|end_filename|> package com.pandaq.pandaemoview; /** * Created by huxinyu on 2017/12/4 0004. * description : */ public class StickerEntity { public String picCover; //封面图路径 public String downLoadUrl; //表情包下载路径 public String name; // 文件名 public boolean isDownLoaded; //是否已经下载 } <|start_filename|>emoticonlib/src/main/java/com/pandaq/emoticonlib/photopicker/LineGridView.java<|end_filename|> package com.pandaq.emoticonlib.photopicker; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; import android.widget.GridView; import com.pandaq.emoticonlib.R; /** * Created by huxinyu on 2017/11/20 0020. * description : */ public class LineGridView extends GridView { public LineGridView(Context context) { super(context); } public LineGridView(Context context, AttributeSet attrs) { super(context, attrs); } public LineGridView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); View localView1 = getChildAt(0); if (localView1 == null) { return; } int column = getWidth() / localView1.getWidth(); int childCount = getChildCount(); Paint localPaint; localPaint = new Paint(); localPaint.setStyle(Paint.Style.STROKE); localPaint.setStrokeWidth(3); localPaint.setColor(getContext().getResources().getColor(R.color.grid_line)); for (int i = 0; i < childCount; i++) { View cellView = getChildAt(i); if ((i + 1) % column == 0) { canvas.drawLine(cellView.getLeft(), cellView.getBottom(), cellView.getRight(), cellView.getBottom(), localPaint); } else if ((i + 1) > (childCount - (childCount % column))) { canvas.drawLine(cellView.getRight(), cellView.getTop(), cellView.getRight(), cellView.getBottom(), localPaint); } else { canvas.drawLine(cellView.getRight(), cellView.getTop(), cellView.getRight(), cellView.getBottom(), localPaint); canvas.drawLine(cellView.getLeft(), cellView.getBottom(), cellView.getRight(), cellView.getBottom(), localPaint); } } if (childCount % column != 0 && childCount >= column) { for (int j = 0; j < (column - childCount % column); j++) { View lastView = getChildAt(childCount - 1); canvas.drawLine(lastView.getRight() + lastView.getWidth() * j, lastView.getTop(), lastView.getRight() + lastView.getWidth() * j, lastView.getBottom(), localPaint); } } } } <|start_filename|>emoticonlib/src/main/java/com/pandaq/emoticonlib/sticker/StickerCategory.java<|end_filename|> package com.pandaq.emoticonlib.sticker; import java.util.List; /** * Created by huxinyu on 2017/10/19 0019. * description :贴图文件对象 */ public class StickerCategory { private String name; //贴图包文件夹名 private String title; //贴图标签名称 private int order = 0; //默认顺序 private String coverPath; //tab栏图标 private String filePath; // 文件路径 private boolean isDefault; //是否是自定义sticker(带添加按钮) private transient List<StickerItem> stickers; public StickerCategory(String name, int order) { this.name = name; this.order = order; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } public List<StickerItem> getStickers() { return stickers; } public void setStickers(List<StickerItem> stickers) { this.stickers = stickers; } public boolean hasStickers() { return stickers != null && stickers.size() > 0; } public int getCount() { if (stickers == null || stickers.isEmpty()) { return 0; } return stickers.size(); } @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof StickerCategory)) { return false; } if (obj == this) { return true; } StickerCategory r = (StickerCategory) obj; return r.getName().equals(getName()); } public String getCoverPath() { return "file://" + coverPath; } public boolean isDefault() { return isDefault; } public void setDefault(boolean aDefault) { isDefault = aDefault; } public void setCoverPath(String coverPath) { this.coverPath = coverPath; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } } <|start_filename|>emoticonlib/src/main/java/com/pandaq/emoticonlib/emoticons/gif/GifRunnable.java<|end_filename|> package com.pandaq.emoticonlib.emoticons.gif; import android.os.Handler; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by huxinyu on 2017/10/11 0011. * description :gif 运行类 */ public class GifRunnable implements Runnable { private Map<String, List<AnimatedGifDrawable>> mGifDrawableMap = new HashMap<>();// 用来存储每个 Activity 显示的Drawable private Map<String, List<AnimatedGifDrawable.RunGifCallBack>> listenersMap = new HashMap<>(); private Handler mHandler; private boolean isRunning = false; private String currentActivity = null; private long frameDuration = 200; public GifRunnable(AnimatedGifDrawable gifDrawable, Handler handler) { addGifDrawable(gifDrawable); mHandler = handler; } @Override public void run() { isRunning = true; if (currentActivity != null) { List<AnimatedGifDrawable> runningDrawables = mGifDrawableMap.get(currentActivity); if (runningDrawables != null) { for (AnimatedGifDrawable gifDrawable : runningDrawables) { AnimatedGifDrawable.RunGifCallBack listener = gifDrawable.getUpdateListener(); List<AnimatedGifDrawable.RunGifCallBack> runningListener = listenersMap.get(currentActivity); if (runningListener != null) { if (!runningListener.contains(listener)) { runningListener.add(listener); } } else { // 为空时肯定不存在直接添加 runningListener = new ArrayList<>(); runningListener.add(listener); listenersMap.put(currentActivity, runningListener); } gifDrawable.nextFrame(); } for (AnimatedGifDrawable.RunGifCallBack callBack : listenersMap.get(currentActivity)) { if (callBack != null) { callBack.run(); } } frameDuration = runningDrawables.get(0).getFrameDuration(); } } mHandler.postDelayed(this, frameDuration); } public void addGifDrawable(AnimatedGifDrawable gifDrawable) { List<AnimatedGifDrawable> runningDrawables = mGifDrawableMap.get(gifDrawable.getContainerTag()); if (runningDrawables != null) { if (!runningDrawables.contains(gifDrawable)) { runningDrawables.add(gifDrawable); } } else { // 为空时肯定不存在直接添加 runningDrawables = new ArrayList<>(); runningDrawables.add(gifDrawable); mGifDrawableMap.put(gifDrawable.getContainerTag(), runningDrawables); } } /** * 使用了表情转换的界面退出时调用,停止动态图handler */ public void pauseHandler() { //暂停时空执行 currentActivity = null; } /** * 使用了表情转换的界面退出时调用,停止动态图handler */ public void clearHandler(String activityName) { currentActivity = null; //清除当前页的数据 mGifDrawableMap.remove(activityName); // 当退出当前Activity后没表情显示时停止 Runable 清除所有动态表情数据 listenersMap.remove(activityName); if (mGifDrawableMap.size() == 0) { clearAll(); } } private void clearAll() { mHandler.removeCallbacks(this); mHandler.removeCallbacksAndMessages(null); mGifDrawableMap.clear(); isRunning = false; } /** * 启动运行 */ public void resumeHandler(String activityName) { currentActivity = activityName; if (mGifDrawableMap != null && mGifDrawableMap.size() > 0 && !isRunning) { run(); } } boolean isRunning() { return isRunning; } } <|start_filename|>app/src/main/java/com/pandaq/pandaemoview/ItemStickerAdapter.java<|end_filename|> package com.pandaq.pandaemoview; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.pandaq.emoticonlib.PandaEmoManager; import com.pandaq.emoticonlib.sticker.StickerManager; import com.squareup.picasso.Picasso; import java.io.File; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by huxinyu on 2017/11/27 0027. * description : */ public class ItemStickerAdapter extends RecyclerView.Adapter { private ArrayList<StickerEntity> mStickerCategories; private Context mContext; public ItemStickerAdapter(Context context, List<StickerEntity> categories) { mStickerCategories = (ArrayList<StickerEntity>) categories; mContext = context; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View item = LayoutInflater.from(mContext).inflate(R.layout.item_stickers, null, false); return new ViewHolder(item); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { final StickerEntity entity = mStickerCategories.get(position); final ViewHolder viewHolder = (ViewHolder) holder; viewHolder.mTvEmoticonName.setText(entity.name); Picasso.with(mContext) .load(entity.picCover) .into(viewHolder.mIvCover); if (entity.isDownLoaded) { viewHolder.mBtnLoad.setText("删除"); viewHolder.mBtnLoad.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 删除表情库 File file = new File(entity.downLoadUrl); deleteFile(file); file.deleteOnExit(); PandaEmoManager.getInstance().getManagedView().reloadEmos(0); } }); } else { viewHolder.mBtnLoad.setText("下载"); viewHolder.mBtnLoad.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { StickerManager.getInstance().addZipResource(entity.downLoadUrl); viewHolder.mBtnLoad.setText("已完成"); } }); } } @Override public int getItemCount() { return mStickerCategories.size(); } static class ViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.iv_cover) ImageView mIvCover; @BindView(R.id.tv_emoticon_name) TextView mTvEmoticonName; @BindView(R.id.btn_load) Button mBtnLoad; ViewHolder(View view) { super(view); ButterKnife.bind(this, view); } } private void deleteFile(File file) { if (file.exists()) { // 判断文件是否存在 if (file.isFile()) { // 判断是否是文件 file.delete(); // delete()方法 你应该知道 是删除的意思; } else if (file.isDirectory()) { // 否则如果它是一个目录 File files[] = file.listFiles(); // 声明目录下所有的文件 files[]; for (File file1 : files) { // 遍历目录下所有的文件 this.deleteFile(file1); // 把每个文件 用这个方法进行迭代 } } file.delete(); } else { Log.d("PandEmoView", "文件不存在!"); } } } <|start_filename|>emoticonlib/src/main/java/com/pandaq/emoticonlib/photopicker/CheckPicAdapter.java<|end_filename|> package com.pandaq.emoticonlib.photopicker; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import com.pandaq.emoticonlib.PandaEmoManager; import com.pandaq.emoticonlib.R; import com.pandaq.emoticonlib.utils.Constant; import java.util.ArrayList; /** * Created by PandaQ on 2017/3/30. * email:<EMAIL> */ public class CheckPicAdapter extends BaseAdapter { private ArrayList<String> mPicPaths; private ArrayList<String> mSelectedPaths; private Context mContext; private boolean showCheckBox; CheckPicAdapter(Context context, ArrayList<String> picPaths) { mPicPaths = picPaths; mContext = context; mSelectedPaths = new ArrayList<>(); } @Override public int getCount() { return mPicPaths == null ? 0 : mPicPaths.size(); } @Override public String getItem(int position) { return mPicPaths.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(final int position, View convertView, ViewGroup parent) { final ViewHolder holder; if (convertView == null) { convertView = LayoutInflater.from(mContext).inflate(R.layout.check_pic_item, null, false); holder = new ViewHolder(convertView); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } String path = mPicPaths.get(position); switch (path) { case Constant.IC_ACTION_CAMERA: holder.mIvPic.setImageResource(R.drawable.ic_action_camera); holder.mCheckBox.setVisibility(View.GONE); holder.mIvPic.setClickable(false); break; case Constant.IC_ACTION_ADD: holder.mIvPic.setImageResource(R.drawable.ic_action_add); holder.mCheckBox.setVisibility(View.GONE); holder.mIvPic.setClickable(false); break; default: PandaEmoManager.getInstance().getIImageLoader().displayImage("file://" + mPicPaths.get(position), holder.mIvPic); if (showCheckBox) { holder.mCheckBox.setVisibility(View.VISIBLE); holder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { if (!mSelectedPaths.contains(mPicPaths.get(position))) mSelectedPaths.add(mPicPaths.get(position)); } else { mSelectedPaths.remove(mPicPaths.get(position)); } } }); holder.mIvPic.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { holder.mCheckBox.setChecked(!holder.mCheckBox.isChecked()); } }); } else { holder.mCheckBox.setVisibility(View.GONE); holder.mIvPic.setClickable(false); } break; } return convertView; } void setPicPaths(ArrayList<String> picPaths) { mPicPaths = picPaths; notifyDataSetChanged(); } void showCheckBox(boolean show) { showCheckBox = show; notifyDataSetChanged(); } private class ViewHolder { SquareImage mIvPic; CheckBox mCheckBox; ViewHolder(View view) { mIvPic = (SquareImage) view.findViewById(R.id.iv_pic); mCheckBox = (CheckBox) view.findViewById(R.id.checkbox); } } ArrayList<String> getSelectedPath() { return mSelectedPaths; } void notifyDelete() { mPicPaths.removeAll(mSelectedPaths); notifyDataSetChanged(); } } <|start_filename|>emoticonlib/src/main/java/com/pandaq/emoticonlib/photopicker/PickImageActivity.java<|end_filename|> package com.pandaq.emoticonlib.photopicker; import android.Manifest; import android.content.ContentResolver; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.BottomSheetBehavior; import android.support.design.widget.BottomSheetDialog; import android.support.v4.content.FileProvider; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.widget.AdapterView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.pandaq.emoticonlib.PandaEmoManager; import com.pandaq.emoticonlib.R; import com.pandaq.emoticonlib.base.SwipeBackActivity; import com.pandaq.emoticonlib.utils.Constant; import com.pandaq.emoticonlib.utils.EmoticonUtils; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * Created by huxinyu on 2017/11/9 0010. * description : */ public class PickImageActivity extends SwipeBackActivity implements AdapterView.OnItemClickListener, View.OnClickListener { private LineGridView mGvPictures; private Map<String, ArrayList<String>> picMap = new HashMap<>(); private CheckPicAdapter mPicAdapter; private BottomSheetDialog mBottomSheetDialog; private ArrayList<ImageFileBean> mImageBeen; private final int ACTION_TAKE_PHOTO = 20; private static final String takePhotoPath = "images/user_take.jpg"; private static final String defaultStickerPath = PandaEmoManager.getInstance().getStickerPath() + "/selfSticker"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_choose_photo); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); TextView tvSelectAlbum = (TextView) findViewById(R.id.tv_bottom_left); TextView tvBottomRight = (TextView) findViewById(R.id.tv_bottom_right); TextView tvActionManage = (TextView) findViewById(R.id.tv_action_manage); RelativeLayout rlBottomLayout = (RelativeLayout) findViewById(R.id.rl_bottom_layout); mGvPictures = (LineGridView) findViewById(R.id.gv_pictures); View toolbarSplit = findViewById(R.id.toolbar_split); tvBottomRight.setVisibility(View.GONE); rlBottomLayout.setVisibility(View.VISIBLE); tvActionManage.setVisibility(View.GONE); toolbarSplit.setVisibility(View.GONE); toolbar.setTitle("选择图片"); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { PickImageActivity.this.finish(); } }); mImageBeen = new ArrayList<>(); mGvPictures.setOnItemClickListener(this); tvSelectAlbum.setOnClickListener(this); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestRunTimePermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, new PermissionCall() { @Override public void requestSuccess() { initImages(); } @Override public void refused() { Toast.makeText(PickImageActivity.this, "请授予必要权限!!", Toast.LENGTH_SHORT).show(); } }); } else { initImages(); } } private void initImages() { if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { Toast.makeText(this, "未发现存储设备!", Toast.LENGTH_SHORT).show(); } Uri imageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; ContentResolver contentResolver = this.getContentResolver(); Cursor cursor = contentResolver.query(imageUri, null, MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?" , new String[]{"image/jpeg", "image/jpg"}, MediaStore.Images.Media.DATE_MODIFIED); if (cursor == null) { Toast.makeText(this, "未发现存储设备!", Toast.LENGTH_SHORT).show(); return; } while (cursor.moveToNext()) { //图片路径名 String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)); //图片父路径名 String parentPath = new File(path).getParentFile().getName(); if (!picMap.containsKey(parentPath)) { ArrayList<String> childList = new ArrayList<>(); childList.add(path); picMap.put(parentPath, childList); } else { picMap.get(parentPath).add(path); } } cursor.close(); ArrayList<String> allPath = new ArrayList<>(); for (Map.Entry<String, ArrayList<String>> entry : picMap.entrySet()) { ImageFileBean imageFileBean = new ImageFileBean(); imageFileBean.setFileName(entry.getKey()); imageFileBean.setImages(entry.getValue()); imageFileBean.setTopImage(entry.getValue().get(0)); mImageBeen.add(imageFileBean); allPath.addAll(entry.getValue()); } allPath.add(0, "ic_action_camera"); ImageFileBean all = new ImageFileBean(); all.setFileName(getString(R.string.all_pictures)); if (allPath.size() > 1) { all.setTopImage(allPath.get(1)); //去掉相机图片 } all.setImages(allPath); mImageBeen.add(0, all); showPics(allPath); initBottomDialog(); } private void showPics(ArrayList<String> value) { if (mPicAdapter == null) { mPicAdapter = new CheckPicAdapter(this, value); mGvPictures.setAdapter(mPicAdapter); } else { mPicAdapter.setPicPaths(value); } } private void initBottomDialog() { mBottomSheetDialog = new BottomSheetDialog(this); View view = LayoutInflater.from(this).inflate(R.layout.dialog_bottom_sheet, null, false); mBottomSheetDialog.setContentView(view); RecyclerView recyclerView = (RecyclerView) mBottomSheetDialog.findViewById(R.id.rv_album_list); assert recyclerView != null; recyclerView.setHasFixedSize(true); LinearLayoutManager layoutManager = new LinearLayoutManager(this); layoutManager.setSmoothScrollbarEnabled(true); recyclerView.setLayoutManager(layoutManager); AlbumAdapter adapter = new AlbumAdapter(mImageBeen, this); adapter.setItemClickListener(new AlbumAdapter.OnItemClickListener() { @Override public void OnItemClick(ArrayList<String> images) { showPics(images); mBottomSheetDialog.dismiss(); } }); recyclerView.setAdapter(adapter); setBehaviorCallback(); } private void setBehaviorCallback() { View view = mBottomSheetDialog.getDelegate().findViewById(android.support.design.R.id.design_bottom_sheet); assert view != null; final BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from(view); bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() { @Override public void onStateChanged(@NonNull View bottomSheet, int newState) { if (newState == BottomSheetBehavior.STATE_HIDDEN) { mBottomSheetDialog.dismiss(); bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); } } @Override public void onSlide(@NonNull View bottomSheet, float slideOffset) { } }); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String imagePath = mPicAdapter.getItem(position); if (imagePath.equals("ic_action_camera")) { takePhoto(); } else { Intent intent = new Intent(this, StickerAddPreviewActivity.class); intent.putExtra(Constant.SOURCE_PATH, imagePath); intent.putExtra(Constant.TARGET_PATH, defaultStickerPath); startActivityForResult(intent, 110); this.finish(); } } /** * 拍照 */ private void takePhoto() { try { Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); File file = new File(EmoticonUtils.getAppFile(this, "images")); File mPhotoFile = new File(EmoticonUtils.getAppFile(this, takePhotoPath)); if (!file.exists()) { boolean result = file.mkdirs(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); Uri contentUri = FileProvider.getUriForFile(this, getApplicationInfo().packageName + ".fileprovider", mPhotoFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri); } else { intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mPhotoFile)); } startActivityForResult(intent, ACTION_TAKE_PHOTO); } catch (Exception e) { e.printStackTrace(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { File mPhotoFile = new File(EmoticonUtils.getAppFile(this, takePhotoPath)); switch (requestCode) { case ACTION_TAKE_PHOTO: if (mPhotoFile.exists()) { Intent intent = new Intent(this, StickerAddPreviewActivity.class); intent.putExtra(Constant.SOURCE_PATH, mPhotoFile.getAbsolutePath()); intent.putExtra(Constant.TARGET_PATH, defaultStickerPath); startActivityForResult(intent, 110); this.finish(); } break; } } @Override public void onClick(View v) { if (mBottomSheetDialog == null) { return; } if (mBottomSheetDialog.isShowing()) { mBottomSheetDialog.dismiss(); } else { mBottomSheetDialog.show(); } } } <|start_filename|>emoticonlib/src/main/java/com/pandaq/emoticonlib/photopicker/ManageCustomActivity.java<|end_filename|> package com.pandaq.emoticonlib.photopicker; import android.Manifest; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.support.annotation.Nullable; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.AdapterView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.pandaq.emoticonlib.PandaEmoManager; import com.pandaq.emoticonlib.R; import com.pandaq.emoticonlib.base.SwipeBackActivity; import com.pandaq.emoticonlib.utils.Constant; import java.io.File; import java.util.ArrayList; /** * Created by huxinyu on 2017/11/9 0009. * description :显示已添加自定义表情类 */ @SuppressWarnings("ResultOfMethodCallIgnored") public class ManageCustomActivity extends SwipeBackActivity implements AdapterView.OnItemClickListener, View.OnClickListener { private static final String defaultStickerPath = PandaEmoManager.getInstance().getStickerPath() + "/selfSticker"; private LineGridView mGridView; private CheckPicAdapter mPicAdapter; private ArrayList<String> pics = new ArrayList<>(); private boolean showCheckBox = false; private RelativeLayout mBottomLayout; private Toolbar mToolbar; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_choose_photo); TextView topAction = (TextView) findViewById(R.id.tv_action_manage); topAction.setOnClickListener(this); mBottomLayout = (RelativeLayout) findViewById(R.id.rl_bottom_layout); TextView tvBottomRight = (TextView) findViewById(R.id.tv_bottom_right); tvBottomRight.setOnClickListener(this); TextView tvSelectAlbum = (TextView) findViewById(R.id.tv_bottom_left); mToolbar = (Toolbar) findViewById(R.id.toolbar); mGridView = (LineGridView) findViewById(R.id.gv_pictures); setSupportActionBar(mToolbar); tvSelectAlbum.setVisibility(View.GONE); mGridView.setNumColumns(5); mToolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ManageCustomActivity.this.finish(); } }); mGridView.setOnItemClickListener(this); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestRunTimePermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, new PermissionCall() { @Override public void requestSuccess() { initImages(); } @Override public void refused() { Toast.makeText(ManageCustomActivity.this, "请授予必要权限!!", Toast.LENGTH_SHORT).show(); } }); } else { initImages(); } } private void initImages() { if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { Toast.makeText(this, "未发现存储设备!", Toast.LENGTH_SHORT).show(); } File parentFile = new File(defaultStickerPath); File[] files = parentFile.listFiles(); if (files != null) { for (File file : files) { if (file != null) { pics.add(file.getAbsolutePath()); } } } pics.add(Constant.IC_ACTION_ADD); showPics(pics); } private void showPics(ArrayList<String> value) { if (mPicAdapter == null) { String num = "(" + (value.size() - 1) + "/" + PandaEmoManager.getInstance().getMaxCustomSticker() + ")"; mToolbar.setTitle("已添加表情" + num); mPicAdapter = new CheckPicAdapter(this, value); mGridView.setAdapter(mPicAdapter); } else { mPicAdapter.setPicPaths(value); } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String path = mPicAdapter.getItem(position); if (Constant.IC_ACTION_ADD.equals(path)) { Intent intent = new Intent(ManageCustomActivity.this, PickImageActivity.class); startActivityForResult(intent, 110); } } private void manageStickers() { if (showCheckBox) { //hideBox mPicAdapter.showCheckBox(false); mBottomLayout.setVisibility(View.GONE); } else { // showBox mPicAdapter.showCheckBox(true); mBottomLayout.setVisibility(View.VISIBLE); } showCheckBox = !showCheckBox; } private void deleteSelected(ArrayList<String> selectedPaths) { for (String path : selectedPaths) { File file = new File(path); file.delete(); } mPicAdapter.notifyDelete(); mPicAdapter.showCheckBox(false); mBottomLayout.setVisibility(View.GONE); PandaEmoManager.getInstance().getManagedView().reloadEmos(1); } @Override public void onClick(View v) { int i = v.getId(); if (i == R.id.tv_action_manage) { manageStickers(); } else if (i == R.id.tv_bottom_right) { deleteSelected(mPicAdapter.getSelectedPath()); } } } <|start_filename|>emoticonlib/src/main/java/com/pandaq/emoticonlib/PandaEmoTranslator.java<|end_filename|> package com.pandaq.emoticonlib; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Handler; import android.text.Editable; import android.text.Spannable; import android.text.SpannableString; import android.text.TextUtils; import android.text.style.ImageSpan; import com.pandaq.emoticonlib.emoticons.EmoticonManager; import com.pandaq.emoticonlib.emoticons.gif.AnimatedGifDrawable; import com.pandaq.emoticonlib.emoticons.gif.AnimatedImageSpan; import com.pandaq.emoticonlib.emoticons.gif.GifRunnable; import com.pandaq.emoticonlib.utils.EmoticonUtils; import java.util.HashSet; import java.util.regex.Matcher; /** * Created by huxinyu on 2017/11/2 0002. * description :表情文字转表情图的转换类 */ public class PandaEmoTranslator { private static PandaEmoTranslator sEmoTranslator; private int MAX_PER_VIEW = 5; private GifRunnable mGifRunnable; private Handler mHandler = new Handler(); /* faceInfo 用于存放表情的起始位置和对应文字 * 每一个表情在字符串中的起始位置不同因此用位置数组作为 key 避免相同表情时覆盖信息 */ private HashSet<int[]> faceInfo = new HashSet<>(); public static PandaEmoTranslator getInstance() { if (sEmoTranslator == null) { synchronized (PandaEmoTranslator.class) { if (sEmoTranslator == null) { sEmoTranslator = new PandaEmoTranslator(); } } } sEmoTranslator.MAX_PER_VIEW = PandaEmoManager.getInstance().getMaxGifPerView(); return sEmoTranslator; } /** * 设置单个 TextView 最多显示的动态图个数 * 超过这个个数则所有表情显示为静态图 * * @param maxGifPerView 阈值 */ public PandaEmoTranslator setMaxGifPerView(int maxGifPerView) { MAX_PER_VIEW = maxGifPerView; return this; } /** * 图文混排工具方法 * * @param classTag 当前显示界面的 Tag(一般是Activity), * 用于在退出界面时将界面内的动图对象从 Runable 中移除 * @param value 要转换的文字 * @param callBack 动图刷新回调 * @return 图文混排后显示的内容 */ public SpannableString makeGifSpannable(String classTag, String value, AnimatedGifDrawable.RunGifCallBack callBack) { if (TextUtils.isEmpty(value)) { value = ""; } faceInfo.clear(); int start, end; SpannableString spannableString = new SpannableString(value); Matcher matcher = PandaEmoManager.getInstance().getPattern().matcher(value); /* 单个 TextView 中显示动态图太多刷新绘制比较消耗内存, 因此做类似QQ动态表情的限制, 超过 MAX_PER_VIEW 个就显示静态表情 */ while (matcher.find()) { start = matcher.start(); end = matcher.end(); faceInfo.add(new int[]{start, end}); } int faces = faceInfo.size(); for (int[] faceIndex : faceInfo) { if (faces > MAX_PER_VIEW) { Drawable drawable = getEmotDrawable(PandaEmoManager.getInstance().getContext(), value.substring(faceIndex[0], faceIndex[1])); if (drawable != null) { ImageSpan span = new ImageSpan(drawable); spannableString.setSpan(span, faceIndex[0], faceIndex[1], Spannable.SPAN_INCLUSIVE_INCLUSIVE); } } else { AnimatedGifDrawable gifDrawable = EmoticonManager.getInstance().getDrawableGif(PandaEmoManager.getInstance().getContext(), value.substring(faceIndex[0], faceIndex[1])); if (gifDrawable != null) { gifDrawable.setRunCallBack(callBack); gifDrawable.setContainerTag(classTag); // 如果动态图执行类不存在,则创建一个新的执行类。存在则将此次转化的表情加入执行类中 if (mGifRunnable == null) { mGifRunnable = new GifRunnable(gifDrawable, mHandler); } else { mGifRunnable.addGifDrawable(gifDrawable); } AnimatedImageSpan span = new AnimatedImageSpan(gifDrawable, mGifRunnable); spannableString.setSpan(span, faceIndex[0], faceIndex[1], Spannable.SPAN_INCLUSIVE_INCLUSIVE); } else { //不存在动态图资源时用静态图代替 Drawable drawable = getEmotDrawable(PandaEmoManager.getInstance().getContext(), value.substring(faceIndex[0], faceIndex[1])); if (drawable != null) { ImageSpan span = new ImageSpan(drawable); spannableString.setSpan(span, faceIndex[0], faceIndex[1], Spannable.SPAN_INCLUSIVE_INCLUSIVE); } } } } return spannableString; } /** * 将带表情的文本转换成图文混排的文本(动态图也转换为静态图) * * @param value 待转换文本 * @return 转换结果 */ public SpannableString makeEmojiSpannable(String value) { if (TextUtils.isEmpty(value)) { value = ""; } int start; int end; SpannableString mSpannableString = new SpannableString(value); Matcher matcher = PandaEmoManager.getInstance().getPattern().matcher(value); while (matcher.find()) { start = matcher.start(); end = matcher.end(); String emot = value.substring(start, end); Drawable drawable = getEmotDrawable(PandaEmoManager.getInstance().getContext(), emot); if (drawable != null) { ImageSpan span = new ImageSpan(drawable); mSpannableString.setSpan(span, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE); } } return mSpannableString; } /** * 将 EditText 文本替换为静态表情图 */ public void replaceEmoticons(Editable editable, int start, int count) { if (count <= 0 || editable.length() < start + count) return; CharSequence s = editable.subSequence(start, start + count); Matcher matcher = PandaEmoManager.getInstance().getPattern().matcher(s); while (matcher.find()) { int from = start + matcher.start(); int to = start + matcher.end(); String emot = editable.subSequence(from, to).toString(); Drawable d = getEmotDrawable(PandaEmoManager.getInstance().getContext(), emot); if (d != null) { ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BOTTOM); editable.setSpan(span, from, to, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } } /** * 获取静态表情 Drawable 对象 * * @param context 上下文 * @param text 表情对应的文本信息 * @return 静态表情 Drawable对象 */ private Drawable getEmotDrawable(Context context, String text) { Drawable drawable = EmoticonManager.getInstance().getDrawable(context, text); int size = EmoticonUtils.dp2px(context, PandaEmoManager.getInstance().getDefaultEmoBoundsDp()); if (drawable != null) { drawable.setBounds(10, 0, size, size); } return drawable; } /** * 开始执行某一个界面的动态表情显示 * * @param activityTag 停止界面 activity 的 Tag */ public void resumeGif(String activityTag) { if (mGifRunnable != null) { mGifRunnable.resumeHandler(activityTag); } } /** * 暂停当前界面的动态表情执行 */ public void pauseGif() { if (mGifRunnable != null) { mGifRunnable.pauseHandler(); } } /** * 停止某个界面的动态表情执行,将任务移除 * * @param activityTag 停止界面 activity 的 Tag */ public void clearGif(String activityTag) { if (mGifRunnable != null) { mGifRunnable.clearHandler(activityTag); } } } <|start_filename|>emoticonlib/src/main/java/com/pandaq/emoticonlib/view/EmotionViewPagerAdapter.java<|end_filename|> package com.pandaq.emoticonlib.view; import android.content.Context; import android.support.annotation.NonNull; import android.support.v4.view.PagerAdapter; import android.text.Editable; import android.text.TextUtils; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.EditText; import android.widget.GridView; import android.widget.RelativeLayout; import com.pandaq.emoticonlib.PandaEmoManager; import com.pandaq.emoticonlib.PandaEmoTranslator; import com.pandaq.emoticonlib.emoticons.EmoticonManager; import com.pandaq.emoticonlib.emoticons.gif.EmojiAdapter; import com.pandaq.emoticonlib.listeners.IStickerSelectedListener; import com.pandaq.emoticonlib.sticker.StickerAdapter; import com.pandaq.emoticonlib.sticker.StickerCategory; import com.pandaq.emoticonlib.sticker.StickerItem; import com.pandaq.emoticonlib.sticker.StickerManager; import java.util.List; /** * 表情控件的ViewPager适配器(emoji + 贴图) */ public class EmotionViewPagerAdapter extends PagerAdapter { private int mPageCount = 0; private int mTabPosi = 0; private int mEmotionLayoutWidth; private int mEmotionLayoutHeight; private IStickerSelectedListener listener; private EditText mMessageEditText; void attachEditText(EditText messageEditText) { mMessageEditText = messageEditText; } EmotionViewPagerAdapter(int emotionLayoutWidth, int emotionLayoutHeight, int tabPosi, IStickerSelectedListener listener) { mEmotionLayoutWidth = emotionLayoutWidth; mEmotionLayoutHeight = emotionLayoutHeight; mTabPosi = tabPosi; if (mTabPosi == 0) { // 默认的 emoji 或者 gif emoji mPageCount = (int) Math.ceil(EmoticonManager.getInstance().getDisplayCount() / (float) PandaEmoManager.getInstance().getEmojiPerPage()); } else { //贴图表情 System.out.println(StickerManager.getInstance().getStickerCategories().get(mTabPosi - 1).getStickers().size() + "??????????"); mPageCount = (int) Math.ceil(StickerManager.getInstance().getStickerCategories().get(mTabPosi - 1).getStickers().size() / (float) PandaEmoManager.getInstance().getStickerPerPage()); } this.listener = listener; } @Override public int getCount() { return mPageCount == 0 ? 1 : mPageCount; } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { return view == object; } @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { Context context = container.getContext(); RelativeLayout rl = new RelativeLayout(context); rl.setGravity(Gravity.CENTER); GridView gridView = new GridView(context); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT); params.addRule(RelativeLayout.CENTER_IN_PARENT); gridView.setLayoutParams(params); gridView.setGravity(Gravity.CENTER); gridView.setTag(position);//标记自己是第几页 if (mTabPosi == 0) { gridView.setOnItemClickListener(emojiListener); gridView.setAdapter(new EmojiAdapter(context, mEmotionLayoutWidth, mEmotionLayoutHeight, position * PandaEmoManager.getInstance().getEmojiPerPage())); gridView.setNumColumns(PandaEmoManager.getInstance().getEmojiColumn()); } else { StickerCategory category = StickerManager.getInstance().getCategory(StickerManager.getInstance().getStickerCategories().get(mTabPosi - 1).getName()); gridView.setOnItemClickListener(stickerListener); gridView.setAdapter(new StickerAdapter(context, category, mEmotionLayoutWidth, mEmotionLayoutHeight, position * PandaEmoManager.getInstance().getStickerPerPage())); gridView.setNumColumns(PandaEmoManager.getInstance().getStickerColumn()); } rl.addView(gridView); container.addView(rl); return rl; } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { container.removeView((View) object); } private AdapterView.OnItemClickListener emojiListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { int index = position + (Integer) parent.getTag() * PandaEmoManager.getInstance().getEmojiPerPage(); int count = EmoticonManager.getInstance().getDisplayCount(); if (position == PandaEmoManager.getInstance().getEmojiPerPage() || index >= count) { onEmojiSelected("/DEL"); } else { String text = EmoticonManager.getInstance().getDisplayText((int) id); if (!TextUtils.isEmpty(text)) { onEmojiSelected(text); } } } }; private AdapterView.OnItemClickListener stickerListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { StickerCategory category = StickerManager.getInstance().getStickerCategories().get(mTabPosi - 1); List<StickerItem> stickers = category.getStickers(); int index; if (mTabPosi == 1) { index = position + (Integer) parent.getTag() * PandaEmoManager.getInstance().getStickerPerPage() - 1; } else { index = position + (Integer) parent.getTag() * PandaEmoManager.getInstance().getStickerPerPage(); } if (index >= stickers.size()) { Log.i("PandaQ", "index " + index + " larger than size " + stickers.size()); return; } if (listener != null) { if (index < 0) { listener.onCustomAdd(); } else { StickerItem sticker = stickers.get(index); if (sticker.getSourcePath() == null) { return; } listener.onStickerSelected(sticker.getTitle(), sticker.getSourcePath()); } } } }; private void onEmojiSelected(String key) { if (mMessageEditText == null) return; Editable editable = mMessageEditText.getText(); if (key.equals("/DEL")) { mMessageEditText.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL)); } else { int start = mMessageEditText.getSelectionStart(); int end = mMessageEditText.getSelectionEnd(); start = (start < 0 ? 0 : start); end = (start < 0 ? 0 : end); editable.replace(start, end, key); int editEnd = mMessageEditText.getSelectionEnd(); PandaEmoTranslator.getInstance().replaceEmoticons(editable, 0, editable.toString().length()); mMessageEditText.setSelection(editEnd); } } void setTabPosi(int tabPosi) { mTabPosi = tabPosi; if (mTabPosi == 0) { // 默认的 emoji 或者 gif emoji mPageCount = (int) Math.ceil(EmoticonManager.getInstance().getDisplayCount() / (float) PandaEmoManager.getInstance().getEmojiPerPage()); } else { //贴图表情 mPageCount = (int) Math.ceil(StickerManager.getInstance().getStickerCategories().get(mTabPosi - 1).getStickers().size() / (float) PandaEmoManager.getInstance().getStickerPerPage()); } } } <|start_filename|>emoticonlib/src/main/java/com/pandaq/emoticonlib/photopicker/PickerUtils.java<|end_filename|> package com.pandaq.emoticonlib.photopicker; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.widget.Toast; import com.pandaq.emoticonlib.PandaEmoManager; import com.pandaq.emoticonlib.utils.EmoticonUtils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; /** * Created by huxinyu on 2017/11/15 0015. * description :默认 PhotoPicker 的工具类 */ class PickerUtils { /** * 文件存储默认名称为:文件顺序+_+MD5(传入图片路径).jpeg */ static String compressAndCopyToSd(String imagePath, String savePath) { FileOutputStream fos; try { File[] files = new File(savePath).listFiles(); if (files == null) return null; if (files.length == PandaEmoManager.getInstance().getMaxCustomSticker()) { Toast.makeText(PandaEmoManager.getInstance().getContext(), "表情已达上限,无法添加", Toast.LENGTH_SHORT).show(); return null; } String filename = files.length + "_" + EmoticonUtils.getMD5Result(imagePath); for (File file : files) { String[] strs = file.getName().split("_"); if (strs.length >= 1 && strs[1].equals(EmoticonUtils.getMD5Result(imagePath))) { Toast.makeText(PandaEmoManager.getInstance().getContext(), "已经添加过此表情", Toast.LENGTH_SHORT).show(); return null; } } fos = new FileOutputStream(savePath + File.separator + filename); // 缩放图片,将图片大小降低 Bitmap bitmap = getZoomImage(BitmapFactory.decodeFile(imagePath), 400); bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos); fos.flush(); fos.close(); return savePath + File.separator + filename; } catch (IOException e) { e.printStackTrace(); return null; } } /** * 图片的缩放方法 * * @param orgBitmap :源图片资源 */ private static Bitmap getZoomImage(Bitmap orgBitmap, float maxSize) { if (null == orgBitmap) { return null; } if (orgBitmap.isRecycled()) { return null; } // 获取图片的宽和高 float width = orgBitmap.getWidth(); float height = orgBitmap.getHeight(); float max = Math.max(width, height); float scale; if (max < maxSize) { scale = 1; } else { scale = maxSize / max; } // 创建操作图片的matrix对象 Matrix matrix = new Matrix(); // 缩放图片动作 matrix.postScale(scale, scale); return Bitmap.createBitmap(orgBitmap, 0, 0, (int) width, (int) height, matrix, true); } } <|start_filename|>emoticonlib/src/main/java/com/pandaq/emoticonlib/listeners/IEmoticonMenuClickListener.java<|end_filename|> package com.pandaq.emoticonlib.listeners; import android.view.View; /** * Created by huxinyu on 2017/10/19 0019. * description :底部功能 tab 回调事件 */ public interface IEmoticonMenuClickListener { void onTabAddClick(View view); void onTabSettingClick(View view); } <|start_filename|>emoticonlib/src/main/java/com/pandaq/emoticonlib/emoticons/gif/AnimatedGifDrawable.java<|end_filename|> package com.pandaq.emoticonlib.emoticons.gif; import android.graphics.Bitmap; import android.graphics.drawable.AnimationDrawable; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import java.io.InputStream; /** * Created by huxinyu on 2017/10/19 0019. * description : GifDrawable 类 */ public class AnimatedGifDrawable extends AnimationDrawable { private String containerTag; // 显示此表情的界面的 Tag private int mCurrentIndex = 0; private RunGifCallBack mGifCallBack; public AnimatedGifDrawable(InputStream source, int bounds) { GifDecoder decoder = new GifDecoder(); decoder.read(source); // Iterate through the gif frames, add each as animation frame for (int i = 0; i < decoder.getFrameCount(); i++) { Bitmap bitmap = decoder.getFrame(i); BitmapDrawable drawable = new BitmapDrawable(bitmap); // Explicitly set the bounds in order for the frames to display drawable.setBounds(10, 0, bounds, bounds); addFrame(drawable, decoder.getDelay(i)); if (i == 0) { // Also set the bounds for this container drawable setBounds(10, 0, bounds, bounds); } } } /** * Naive method to proceed to next frame. Also notifies listener. */ public void nextFrame() { mCurrentIndex = (mCurrentIndex + 1) % getNumberOfFrames(); } /** * Return display duration for current frame */ public int getFrameDuration() { return getDuration(mCurrentIndex); } /** * Return drawable for current frame */ public Drawable getDrawable() { return getFrame(mCurrentIndex); } /** * Interface to notify listener to update/redraw * Can't figure out how to invalidate the drawable (or span in which it sits) itself to force redraw */ public interface RunGifCallBack { void run(); } public RunGifCallBack getUpdateListener() { return mGifCallBack; } public void setRunCallBack(RunGifCallBack gifCallBack) { mGifCallBack = gifCallBack; } public String getContainerTag() { return containerTag; } public void setContainerTag(String containerTag) { this.containerTag = containerTag; } } <|start_filename|>emoticonlib/src/main/java/com/pandaq/emoticonlib/view/PandaEmoView.java<|end_filename|> package com.pandaq.emoticonlib.view; import android.content.Context; import android.graphics.drawable.Drawable; import android.graphics.drawable.StateListDrawable; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import com.pandaq.emoticonlib.PandaEmoManager; import com.pandaq.emoticonlib.PandaEmoTranslator; import com.pandaq.emoticonlib.R; import com.pandaq.emoticonlib.emoticons.EmoticonManager; import com.pandaq.emoticonlib.listeners.IEmoticonMenuClickListener; import com.pandaq.emoticonlib.listeners.IStickerSelectedListener; import com.pandaq.emoticonlib.sticker.StickerCategory; import com.pandaq.emoticonlib.sticker.StickerManager; import com.pandaq.emoticonlib.utils.EmoticonUtils; import java.util.ArrayList; import java.util.List; /** * Created by huxinyu on 2017/10/19 0019. * description : 表情输入键盘视图 View */ public class PandaEmoView extends RelativeLayout { private int mMeasuredWidth; private int mMeasuredHeight; private Context mContext; private ViewPager mEmoticonPager; private LinearLayout mIndicatorLayout; private LinearLayout mBottomTabLayout; private EmotionTab mAddTab; private EmotionTab mSettingTab; private int mTabCount; private ArrayList<View> mTabs = new ArrayList<>(); private int mTabPosi = 0; private PandaEmoEditText mAttachedEditText; private IStickerSelectedListener mEmoticonSelectedListener; private IEmoticonMenuClickListener mEmoticonExtClickListener; private boolean loadedResource = false; private EmotionViewPagerAdapter adapter; public PandaEmoView(Context context) { this(context, null); } public PandaEmoView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public PandaEmoView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mContext = context; this.setVisibility(GONE); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); if (getHeight() != 0 && !loadedResource) { init(); initListener(); loadedResource = true; } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); mMeasuredWidth = measureWidth(widthMeasureSpec); mMeasuredHeight = measureHeight(heightMeasureSpec); setMeasuredDimension(mMeasuredWidth, mMeasuredHeight); } //计算控件布局宽度 private int measureWidth(int measureSpec) { int result; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { // 精确模式直接显示真实 Size result = specSize; } else { //非精确模式时显示默认 Size 如果是限制类型则显示默认值和限制值中较小的一个 result = EmoticonUtils.dp2px(mContext, 200); if (specMode == MeasureSpec.AT_MOST) { result = Math.min(result, specSize); } } return result; } //计算控件布局高度 private int measureHeight(int measureSpec) { int result; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { // 精确模式直接显示真实 Size result = specSize; } else { //非精确模式时显示默认 Size 如果是限制类型则显示默认值和限制值中较小的一个 result = EmoticonUtils.dp2px(mContext, 200); if (specMode == MeasureSpec.AT_MOST) { result = Math.min(result, specSize); } } return result; } private void init() { LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (inflater != null) { inflater.inflate(R.layout.emoticon_layout, this); } mEmoticonPager = (ViewPager) findViewById(R.id.vpEmoticon); mIndicatorLayout = (LinearLayout) findViewById(R.id.llIndicator); mBottomTabLayout = (LinearLayout) findViewById(R.id.llTabContainer); mAddTab = (EmotionTab) findViewById(R.id.tabAdd); if (PandaEmoManager.getInstance().isShowAddButton()) { mAddTab.setVisibility(VISIBLE); } else { mAddTab.setVisibility(GONE); } initTabs(); } /** * 初始化底部按钮 */ private void initTabs() { if (mBottomTabLayout == null) return; mTabs.clear(); mBottomTabLayout.removeAllViews(); //添加默认表情 Tab EmotionTab emojiTab = new EmotionTab(mContext, PandaEmoManager.getInstance().getDefaultIconRes()); mBottomTabLayout.addView(emojiTab); mTabs.add(emojiTab); //添加所有的贴图tab if (PandaEmoManager.getInstance().isShowStickers()) { // 是否显示 List<StickerCategory> stickerCategories = StickerManager.getInstance().getStickerCategories(); for (int i = 0; i < stickerCategories.size(); i++) { StickerCategory category = stickerCategories.get(i); EmotionTab tab; if (category.getName().equals(StickerManager.selfSticker)) { tab = new EmotionTab(mContext, R.drawable.icon_self); mBottomTabLayout.addView(tab); mTabs.add(tab); } else { tab = new EmotionTab(mContext, category.getCoverPath()); mBottomTabLayout.addView(tab); mTabs.add(tab); } } } //最后添加一个表情设置Tab if (PandaEmoManager.getInstance().isShowSetButton()) { mSettingTab = new EmotionTab(mContext, R.drawable.ic_emotion_setting); StateListDrawable drawable = new StateListDrawable(); Drawable unSelected = mContext.getResources().getDrawable(R.color.white); drawable.addState(new int[]{-android.R.attr.state_pressed}, unSelected); Drawable selected = mContext.getResources().getDrawable(R.color.gray_text); drawable.addState(new int[]{android.R.attr.state_pressed}, selected); mSettingTab.setBackground(drawable); mBottomTabLayout.addView(mSettingTab); mTabs.add(mSettingTab); } selectTab(0); //默认底一个被选中 } /** * 选择选中的 Item */ private void selectTab(int tabPosi) { if (PandaEmoManager.getInstance().isShowSetButton()) { if (tabPosi == mTabs.size() - 1) return; } for (int i = 0; i < mTabCount; i++) { View tab = mTabs.get(i); tab.setBackgroundResource(R.drawable.shape_tab_normal); } mTabs.get(tabPosi).setBackgroundResource(R.drawable.shape_tab_press); //显示表情内容 fillVpEmotioin(tabPosi); } private void fillVpEmotioin(int tabPosi) { if (adapter == null) { adapter = new EmotionViewPagerAdapter(mMeasuredWidth, mMeasuredHeight, tabPosi, mEmoticonSelectedListener); } else { adapter.setTabPosi(tabPosi); } mEmoticonPager.setAdapter(adapter); mIndicatorLayout.removeAllViews(); setCurPageCommon(0); if (tabPosi == 0) { adapter.attachEditText(mAttachedEditText); } } private void initListener() { if (mBottomTabLayout == null) return; if (PandaEmoManager.getInstance().isShowSetButton()) { mTabCount = mBottomTabLayout.getChildCount() - 1;//不包含最后的设置按钮 } else { mTabCount = mBottomTabLayout.getChildCount(); } for (int position = 0; position < mTabCount; position++) { View tab = mBottomTabLayout.getChildAt(position); tab.setTag(position); tab.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mTabPosi = (int) v.getTag(); selectTab(mTabPosi); } }); } mEmoticonPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { setCurPageCommon(position); } @Override public void onPageSelected(int position) { } @Override public void onPageScrollStateChanged(int state) { } }); if (mAddTab != null) { mAddTab.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mEmoticonExtClickListener != null) { mEmoticonExtClickListener.onTabAddClick(v); } } }); } if (mSettingTab != null) { mSettingTab.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mEmoticonExtClickListener != null) { mEmoticonExtClickListener.onTabSettingClick(v); } } }); } } private void setCurPageCommon(int position) { if (mTabPosi == 0) { int emojiPerpage = PandaEmoManager.getInstance().getEmojiPerPage(); setCurPage(position, (int) Math.ceil(EmoticonManager.getInstance().getDisplayCount() / (float) emojiPerpage)); } else { int stickerPerPage = PandaEmoManager.getInstance().getStickerPerPage(); StickerCategory category = StickerManager.getInstance().getStickerCategories().get(mTabPosi - 1); setCurPage(position, (int) Math.ceil(category.getStickers().size() / (float) stickerPerPage)); } } private void setCurPage(int page, int pageCount) { int hasCount = mIndicatorLayout.getChildCount(); int forMax = Math.max(hasCount, pageCount); ImageView ivCur; for (int i = 0; i < forMax; i++) { if (pageCount <= hasCount) { if (i >= pageCount) { mIndicatorLayout.getChildAt(i).setVisibility(View.GONE); continue; } else { ivCur = (ImageView) mIndicatorLayout.getChildAt(i); } } else { if (i < hasCount) { ivCur = (ImageView) mIndicatorLayout.getChildAt(i); } else { ivCur = new ImageView(mContext); ivCur.setBackgroundResource(R.drawable.selector_view_pager_indicator); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(EmoticonUtils.dp2px(mContext, 8), EmoticonUtils.dp2px(mContext, 8)); ivCur.setLayoutParams(params); params.leftMargin = EmoticonUtils.dp2px(mContext, 3); params.rightMargin = EmoticonUtils.dp2px(mContext, 3); mIndicatorLayout.addView(ivCur); } } ivCur.setId(i); ivCur.setSelected(i == page); ivCur.setVisibility(View.VISIBLE); } } public void attachEditText(PandaEmoEditText inputEditText) { if (mAttachedEditText != null) { // 绑定下一个焦点输入控件时将上一个控件吊起的输入框隐藏,并将已输入的内容转成表情放入 mAttachedEditText.setText(PandaEmoTranslator.getInstance() .makeEmojiSpannable(mAttachedEditText.getText().toString())); mAttachedEditText.getKeyBoardManager().hideInputLayout(); if (mTabPosi == 0 && adapter != null) { // 重新为表情输入栏绑定输入控件 adapter.attachEditText(inputEditText); } } mAttachedEditText = inputEditText; } public PandaEmoEditText getAttachEditText() { return mAttachedEditText; } public void setEmoticonSelectedListener(IStickerSelectedListener emotionSelectedListener) { mEmoticonSelectedListener = emotionSelectedListener; } public void setEmoticonMenuClickListener(IEmoticonMenuClickListener emotionExtClickListener) { mEmoticonExtClickListener = emotionExtClickListener; } /** * 新增了表情库后调用 */ public void reloadEmos(int position) { mTabPosi = position; StickerManager.getInstance().loadStickerCategory(); initTabs(); initListener(); invalidate(); if (0 <= position && position < mTabs.size()) { selectTab(position); } } } <|start_filename|>emoticonlib/src/main/java/com/pandaq/emoticonlib/base/SwipeBackActivity.java<|end_filename|> package com.pandaq.emoticonlib.base; import android.animation.ArgbEvaluator; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import com.pandaq.emoticonlib.R; /** * Created by huxinyu on 2017/11/22 0022. * description :带侧滑返回功能的 Activity */ public class SwipeBackActivity extends BaseActivity implements SwipeBackLayout.SwipeListener { protected SwipeBackLayout layout; private ArgbEvaluator argbEvaluator; private int currentStatusColor; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); layout = (SwipeBackLayout) LayoutInflater.from(this).inflate( R.layout.swipeback_base, null); layout.attachToActivity(this); argbEvaluator = new ArgbEvaluator(); layout.addSwipeListener(this); if (Build.VERSION.SDK_INT >= 23) { currentStatusColor = getResources().getColor(R.color.colorPrimaryDark, null); } else { currentStatusColor = getResources().getColor(R.color.colorPrimaryDark); } } public void addViewPager(ViewPager pager) { layout.addViewPager(pager); } @Override public void swipeValue(double value) { int statusColor = (int) argbEvaluator.evaluate((float) value, currentStatusColor, Color.parseColor("#00ffffff")); // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // getWindow().setStatusBarColor(statusColor); // } } } <|start_filename|>emoticonlib/src/main/java/com/pandaq/emoticonlib/photopicker/StickerAddPreviewActivity.java<|end_filename|> package com.pandaq.emoticonlib.photopicker; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.pandaq.emoticonlib.PandaEmoManager; import com.pandaq.emoticonlib.R; import com.pandaq.emoticonlib.base.SwipeBackActivity; import static com.pandaq.emoticonlib.utils.Constant.SOURCE_PATH; import static com.pandaq.emoticonlib.utils.Constant.TARGET_PATH; /** * Created by huxinyu on 2017/11/15 0015. * description :添加自定义贴图表情预览界面 */ public class StickerAddPreviewActivity extends SwipeBackActivity implements View.OnClickListener { private ImageView mImageView; private String sourcePath; private String targetPath; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_img_preview); initView(); initData(); } private void initView() { Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setTitle("表情预览"); TextView actionManage = (TextView) findViewById(R.id.tv_action_manage); mImageView = (ImageView) findViewById(R.id.iv_pic); actionManage.setOnClickListener(this); } private void initData() { sourcePath = getIntent().getStringExtra(SOURCE_PATH); targetPath = getIntent().getStringExtra(TARGET_PATH); PandaEmoManager.getInstance().getIImageLoader().displayImage("file://" + sourcePath, mImageView); } @Override public void onClick(View v) { PickerUtils.compressAndCopyToSd(sourcePath, targetPath); Intent intent = new Intent(this, ManageCustomActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); PandaEmoManager.getInstance().getManagedView().reloadEmos(1); Toast.makeText(this, "已添加", Toast.LENGTH_SHORT).show(); this.finish(); } } <|start_filename|>app/src/main/java/com/pandaq/pandaemoview/activity/SettingActivity.java<|end_filename|> package com.pandaq.pandaemoview.activity; import android.graphics.Bitmap; import android.net.Uri; import android.net.http.SslError; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.View; import android.webkit.SslErrorHandler; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.TextView; import com.pandaq.emoticonlib.PandaEmoManager; import com.pandaq.emoticonlib.base.SwipeBackActivity; import com.pandaq.emoticonlib.sticker.StickerCategory; import com.pandaq.emoticonlib.sticker.StickerManager; import com.pandaq.pandaemoview.ItemStickerAdapter; import com.pandaq.pandaemoview.R; import com.pandaq.pandaemoview.StickerEntity; import java.io.File; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by huxinyu on 2017/11/27 0027. * description : */ public class SettingActivity extends SwipeBackActivity { @BindView(R.id.toolbar) Toolbar mToolbar; @BindView(R.id.rv_emoticon_list) RecyclerView mRvEmoticonList; @BindView(R.id.toptitle) TextView mToptitle; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_setting); ButterKnife.bind(this); setSupportActionBar(mToolbar); mToptitle.setText("设置"); init(); } private void init() { ArrayList<StickerEntity> entities = new ArrayList<>(); StickerEntity entity = new StickerEntity(); entity.downLoadUrl = PandaEmoManager.getInstance().getStickerPath() + File.separator + "soAngry"; entity.name = "我好气啊"; entity.isDownLoaded = true; entity.picCover = "https://b-ssl.duitang.com/uploads/item/201607/24/20160724220001_reK4C.jpeg"; entities.add(entity); mToolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); ItemStickerAdapter itemStickerAdapter = new ItemStickerAdapter(this, entities); mRvEmoticonList.setLayoutManager(new LinearLayoutManager(this)); mRvEmoticonList.setAdapter(itemStickerAdapter); } } <|start_filename|>app/src/main/java/com/pandaq/pandaemoview/activity/AddEmoActivity.java<|end_filename|> package com.pandaq.pandaemoview.activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.TextView; import com.pandaq.emoticonlib.base.SwipeBackActivity; import com.pandaq.pandaemoview.ItemStickerAdapter; import com.pandaq.pandaemoview.R; import com.pandaq.pandaemoview.StickerEntity; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by huxinyu on 2017/11/27 0027. * description : */ public class AddEmoActivity extends SwipeBackActivity { @BindView(R.id.toolbar) Toolbar mToolbar; @BindView(R.id.rv_emoticon_list) RecyclerView mRvEmoticonList; @BindView(R.id.toptitle) TextView mToptitle; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_setting); ButterKnife.bind(this); setSupportActionBar(mToolbar); mToptitle.setText("添加表情"); init(); } private void init() { ArrayList<StickerEntity> entities = new ArrayList<>(); StickerEntity entity = new StickerEntity(); entity.downLoadUrl = getApplicationContext().getFilesDir().getAbsolutePath() + "/soAngry.zip"; entity.name = "我好气啊"; entity.isDownLoaded = false; entity.picCover = "https://b-ssl.duitang.com/uploads/item/201607/24/20160724220001_reK4C.jpeg"; entities.add(entity); mToolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); ItemStickerAdapter itemStickerAdapter = new ItemStickerAdapter(this, entities); mRvEmoticonList.setLayoutManager(new LinearLayoutManager(this)); mRvEmoticonList.setAdapter(itemStickerAdapter); } } <|start_filename|>emoticonlib/src/main/java/com/pandaq/emoticonlib/utils/EmoticonUtils.java<|end_filename|> package com.pandaq.emoticonlib.utils; import android.content.Context; import android.os.Environment; import android.util.DisplayMetrics; import java.io.File; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * Created by huxinyu on 2017/10/19 0019. * description :表情库中使用到的一些公用工具方法 */ public class EmoticonUtils { /** * dp 转 px * * @param context 上下文 * @param dpValue dp 值 * @return px 值 */ public static int dp2px(Context context, float dpValue) { DisplayMetrics displayMetrics = context.getApplicationContext().getResources().getDisplayMetrics(); return (int) (dpValue * displayMetrics.density + 0.5f); } /** * px 转 dp * * @param context 上下文 * @param pxValue px 值 * @return dp 值 */ public static int px2dp(Context context, float pxValue) { DisplayMetrics displayMetrics = context.getApplicationContext().getResources().getDisplayMetrics(); return (int) (pxValue / displayMetrics.density + 0.5f); } public static int sp2px(Context context, float spValue) { DisplayMetrics displayMetrics = context.getApplicationContext().getResources().getDisplayMetrics(); return (int) (spValue * displayMetrics.scaledDensity + 0.5f); } /** * 获取本应用在系统的存储目录 */ public static String getAppFile(Context context, String uniqueName) { String cachePath = null; if ((Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) && context.getExternalCacheDir() != null) { cachePath = context.getExternalCacheDir().getParent(); } else { cachePath = context.getCacheDir().getParent(); } return cachePath + File.separator + uniqueName; } /** * 传入字符串参数,返回MD5加密结果(小写) * * @param value 待加密的字符串 * @return 加密结果 */ public static String getMD5Result(String value) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(value.getBytes("UTF-8")); byte[] result = md.digest(); return getString(result); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return "NoSuchAlgorithmException !"; } catch (UnsupportedEncodingException e) { e.printStackTrace(); return "UnsupportedEncodingException !"; } } private static String getString(byte[] result) { StringBuilder sb = new StringBuilder(); for (byte b : result) { int i = b & 0xff; if (i <= 0xf) { sb.append(0); } sb.append(Integer.toHexString(i)); } return sb.toString().toLowerCase(); } } <|start_filename|>emoticonlib/src/main/java/com/pandaq/emoticonlib/photopicker/SquareImage.java<|end_filename|> package com.pandaq.emoticonlib.photopicker; import android.content.Context; import android.support.annotation.Nullable; import android.util.AttributeSet; /** * Created by huxinyu on 2017/11/20 0020. * description : */ public class SquareImage extends android.support.v7.widget.AppCompatImageView { public SquareImage(Context context) { super(context); } public SquareImage(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public SquareImage(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec)); int childWidthSize = getMeasuredWidth(); widthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY); heightMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } } <|start_filename|>emoticonlib/src/main/java/com/pandaq/emoticonlib/photopicker/AlbumAdapter.java<|end_filename|> package com.pandaq.emoticonlib.photopicker; import android.content.Context; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.pandaq.emoticonlib.PandaEmoManager; import com.pandaq.emoticonlib.R; import java.util.ArrayList; /** * Created by PandaQ on 2017/3/31. * 相册列表Adapter */ public class AlbumAdapter extends RecyclerView.Adapter { private ArrayList<ImageFileBean> mImageBeen; private Context mContext; public AlbumAdapter(ArrayList<ImageFileBean> imageBeen, Context context) { mImageBeen = imageBeen; mContext = context; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.album_item, null, false); return new ViewHolder(view); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { ViewHolder mHolder = (ViewHolder) holder; mHolder.mTvFileCount.setText("" + mImageBeen.get(position).getImages().size() + "张"); mHolder.mTvFileName.setText(mImageBeen.get(position).getFileName()); PandaEmoManager.getInstance().getIImageLoader().displayImage("file://" + mImageBeen.get(position).getTopImage(), mHolder.mIvCover); mHolder.mCardItem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mItemClickListener != null) { mItemClickListener.OnItemClick(mImageBeen.get(position).getImages()); } } }); } @Override public int getItemCount() { return mImageBeen.size(); } interface OnItemClickListener { void OnItemClick(ArrayList<String> images); } private OnItemClickListener mItemClickListener; void setItemClickListener(OnItemClickListener itemClickListener) { mItemClickListener = itemClickListener; } private static class ViewHolder extends RecyclerView.ViewHolder { ImageView mIvCover; TextView mTvFileName; TextView mTvFileCount; CardView mCardItem; ViewHolder(View view) { super(view); mIvCover = (ImageView) view.findViewById(R.id.iv_cover); mTvFileName = (TextView) view.findViewById(R.id.tv_file_name); mTvFileCount = (TextView) view.findViewById(R.id.tv_file_count); mCardItem = (CardView) view.findViewById(R.id.card_item); } } } <|start_filename|>emoticonlib/src/main/java/com/pandaq/emoticonlib/emoticons/gif/EmojiAdapter.java<|end_filename|> package com.pandaq.emoticonlib.emoticons.gif; import android.content.Context; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.RelativeLayout; import com.pandaq.emoticonlib.PandaEmoManager; import com.pandaq.emoticonlib.R; import com.pandaq.emoticonlib.emoticons.EmoticonManager; import com.pandaq.emoticonlib.utils.EmoticonUtils; import com.pandaq.emoticonlib.view.PandaEmoView; public class EmojiAdapter extends BaseAdapter { private Context mContext; private int mStartIndex; private final float mPerHeight; private final float mIvSize; public EmojiAdapter(Context context, int emotionLayoutWidth, int emotionLayoutHeight, int startIndex) { mContext = context; mStartIndex = startIndex; if (emotionLayoutHeight <= 0) { emotionLayoutHeight = EmoticonUtils.dp2px(context, 270); } int mEmotionLayoutHeight = emotionLayoutHeight - EmoticonUtils.dp2px(mContext, 35 + 26 + 50); float perWidth = emotionLayoutWidth * 1f / PandaEmoManager.getInstance().getEmojiColumn(); mPerHeight = mEmotionLayoutHeight * 1f / PandaEmoManager.getInstance().getEmojiRow(); float ivWidth = perWidth * .6f; float ivHeight = mPerHeight * .6f; mIvSize = Math.min(ivWidth, ivHeight); } @Override public int getCount() { int count = EmoticonManager.getInstance().getDisplayCount() - mStartIndex + 1; count = Math.min(count, PandaEmoManager.getInstance().getEmojiPerPage() + 1); return count; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return mStartIndex + position; } @Override public View getView(int position, View convertView, ViewGroup parent) { RelativeLayout rl = new RelativeLayout(mContext); rl.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, (int) mPerHeight)); ImageView emojiThumb = new ImageView(mContext); int count = EmoticonManager.getInstance().getDisplayCount(); int index = mStartIndex + position; if (position == PandaEmoManager.getInstance().getEmojiPerPage()|| index == count) { emojiThumb.setBackgroundResource(R.drawable.ic_emoji_del); } else if (index < count) { emojiThumb.setBackground(EmoticonManager.getInstance().getDisplayDrawable(mContext, index)); } RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); layoutParams.width = (int) mIvSize; layoutParams.height = (int) mIvSize; emojiThumb.setLayoutParams(layoutParams); rl.setGravity(Gravity.CENTER); rl.addView(emojiThumb); return rl; } } <|start_filename|>app/src/main/java/com/pandaq/pandaemoview/BaseApplication.java<|end_filename|> package com.pandaq.pandaemoview; import android.app.Application; import android.widget.ImageView; import com.pandaq.emoticonlib.PandaEmoManager; import com.pandaq.emoticonlib.listeners.IImageLoader; import com.squareup.picasso.Picasso; /** * Created by huxinyu on 2017/10/23 0023. * description : */ public class BaseApplication extends Application { @Override public void onCreate() { super.onCreate(); configPandaEmoView(); } private void configPandaEmoView() { new PandaEmoManager.Builder() .with(getApplicationContext()) // 传递 Context .configFileName("emoji.xml")// 配置文件名称 .emoticonDir("face") // asset 下存放表情的目录路径(asset——> configFileName 之间的路径,结尾不带斜杠) .sourceDir("images") // 存放 emoji 表情资源文件夹路径(emoticonDir 图片资源之间的路径,结尾不带斜杠) .showAddTab(true)//tab栏是否显示添加按钮 .showStickers(true)//tab栏是否显示贴图切换按键 .showSetTab(true)//tab栏是否显示设置按钮 .defaultBounds(30)//emoji 表情显示出来的宽高 .cacheSize(50)//加载资源到内存时 LruCache 缓存大小,最小必须大于表情总数或者两页表情的数(否则会在显示时前面资源被回收) .defaultTabIcon(R.drawable.ic_default)//emoji表情Tab栏图标 .emojiColumn(7)//单页显示表情的列数 .emojiRow(3)//单页显示表情的行数 .stickerRow(2)//单页显示贴图表情的行数 .stickerColumn(4)//单页显示贴图表情的列数 .maxCustomStickers(30)//允许添加的收藏表情数 .imageLoader(new IImageLoader() { @Override public void displayImage(String path, ImageView imageView) { // 加载贴图表情的图片加载接口 Picasso.with(getApplicationContext()) .load(path) .fit() .centerCrop() .into(imageView); } }) .build(); //构建 PandaEmoManager 单利 } }
haojile/emoji-ime
<|start_filename|>node_modules/axe-core/lib/rules/presentation-role-conflict-matches.js<|end_filename|> import { getImplicitRole } from '../commons/aria'; function presentationRoleConflictMatches(node, virtualNode) { return getImplicitRole(virtualNode, { chromiumRoles: true }) !== null; } export default presentationRoleConflictMatches; <|start_filename|>node_modules/axe-core/lib/checks/aria/aria-prohibited-attr-evaluate.js<|end_filename|> import { getRole } from '../../commons/aria'; import { sanitize, subtreeText } from '../../commons/text'; import standards from '../../standards'; /** * Check that an element does not use any prohibited ARIA attributes. * * Prohibited attributes are taken from the `ariaAttrs` standards object from the attributes `prohibitedAttrs` property. * * ##### Data: * <table class="props"> * <thead> * <tr> * <th>Type</th> * <th>Description</th> * </tr> * </thead> * <tbody> * <tr> * <td><code>String[]</code></td> * <td>List of all prohibited attributes</td> * </tr> * </tbody> * </table> * * @memberof checks * @return {Boolean} True if the element uses any prohibited ARIA attributes. False otherwise. */ function ariaProhibitedAttrEvaluate(node, options = {}, virtualNode) { const extraElementsAllowedAriaLabel = options.elementsAllowedAriaLabel || []; const prohibitedList = listProhibitedAttrs( virtualNode, extraElementsAllowedAriaLabel ); const prohibited = prohibitedList.filter(attrName => { if (!virtualNode.attrNames.includes(attrName)) { return false; } return sanitize(virtualNode.attr(attrName)) !== ''; }); if (prohibited.length === 0) { return false; } this.data(prohibited); const hasTextContent = sanitize(subtreeText(virtualNode)) !== ''; // Don't fail if there is text content to announce return hasTextContent ? undefined : true; } function listProhibitedAttrs(virtualNode, elementsAllowedAriaLabel) { const role = getRole(virtualNode, { chromium: true }); const roleSpec = standards.ariaRoles[role]; if (roleSpec) { return roleSpec.prohibitedAttrs || []; } const { nodeName } = virtualNode.props; if (!!role || elementsAllowedAriaLabel.includes(nodeName)) { return []; } return ['aria-label', 'aria-labelledby']; } export default ariaProhibitedAttrEvaluate;
Al-dasouqi/React-app
<|start_filename|>scripts/mangleErrors.js<|end_filename|> const fs = require('fs') const helperModuleImports = require('@babel/helper-module-imports') /** * Converts an AST type into a javascript string so that it can be added to the error message lookup. * * Adapted from React (https://github.com/facebook/react/blob/master/scripts/shared/evalToString.js) with some * adjustments */ const evalToString = ast => { switch (ast.type) { case 'StringLiteral': case 'Literal': // ESLint return ast.value case 'BinaryExpression': // `+` if (ast.operator !== '+') { throw new Error('Unsupported binary operator ' + ast.operator) } return evalToString(ast.left) + evalToString(ast.right) case 'TemplateLiteral': return ast.quasis.reduce( (concatenatedValue, templateElement) => concatenatedValue + templateElement.value.raw, '' ) case 'Identifier': return ast.name default: throw new Error('Unsupported type ' + ast.type) } } /** * Takes a `throw new error` statement and transforms it depending on the minify argument. Either option results in a * smaller bundle size in production for consumers. * * If minify is enabled, we'll replace the error message with just an index that maps to an arrow object lookup. * * If minify is disabled, we'll add in a conditional statement to check the process.env.NODE_ENV which will output a * an error number index in production or the actual error message in development. This allows consumers using webpak * or another build tool to have these messages in development but have just the error index in production. * * E.g. * Before: * throw new Error("This is my error message."); * throw new Error("This is a second error message."); * * After (with minify): * throw new Error(0); * throw new Error(1); * * After: (without minify): * throw new Error(node.process.NODE_ENV === 'production' ? 0 : "This is my error message."); * throw new Error(node.process.NODE_ENV === 'production' ? 1 : "This is a second error message."); */ module.exports = babel => { const t = babel.types // When the plugin starts up, we'll load in the existing file. This allows us to continually add to it so that the // indexes do not change between builds. let errorsFiles = '' if (fs.existsSync('errors.json')) { errorsFiles = fs.readFileSync('errors.json').toString() } let errors = Object.values(JSON.parse(errorsFiles || '{}')) // This variable allows us to skip writing back to the file if the errors array hasn't changed let changeInArray = false return { pre: () => { changeInArray = false }, visitor: { ThrowStatement(path, file) { const arguments = path.node.argument.arguments const minify = file.opts.minify if (arguments && arguments[0]) { // Skip running this logic when certain types come up: // Identifier comes up when a variable is thrown (E.g. throw new error(message)) // NumericLiteral, CallExpression, and ConditionalExpression is code we have already processed if ( path.node.argument.arguments[0].type === 'Identifier' || path.node.argument.arguments[0].type === 'NumericLiteral' || path.node.argument.arguments[0].type === 'ConditionalExpression' || path.node.argument.arguments[0].type === 'CallExpression' ) { return } const errorMsgLiteral = evalToString(path.node.argument.arguments[0]) if (errorMsgLiteral.includes('Super expression')) { // ignore Babel runtime error message return } // Attempt to get the existing index of the error. If it is not found, add it to the array as a new error. let errorIndex = errors.indexOf(errorMsgLiteral) if (errorIndex === -1) { errors.push(errorMsgLiteral) errorIndex = errors.length - 1 changeInArray = true } // Import the error message function const formatProdErrorMessageIdentifier = helperModuleImports.addDefault( path, 'src/utils/formatProdErrorMessage', { nameHint: 'formatProdErrorMessage' } ) // Creates a function call to output the message to the error code page on the website const prodMessage = t.callExpression( formatProdErrorMessageIdentifier, [t.numericLiteral(errorIndex)] ) if (minify) { path.replaceWith( t.throwStatement( t.newExpression(t.identifier('Error'), [prodMessage]) ) ) } else { path.replaceWith( t.throwStatement( t.newExpression(t.identifier('Error'), [ t.conditionalExpression( t.binaryExpression( '===', t.identifier('process.env.NODE_ENV'), t.stringLiteral('production') ), prodMessage, path.node.argument.arguments[0] ) ]) ) ) } } } }, post: () => { // If there is a new error in the array, convert it to an indexed object and write it back to the file. if (changeInArray) { fs.writeFileSync('errors.json', JSON.stringify({ ...errors }, null, 2)) } } } } <|start_filename|>website/src/pages/errors.js<|end_filename|> import React from 'react' import Layout from '@theme/Layout' import { useLocation } from '@docusaurus/router' import useDocusaurusContext from '@docusaurus/useDocusaurusContext' import styles from './styles.module.css' import errorCodes from '../../../errors.json' import 'url-search-params-polyfill' function Errors() { const location = useLocation() const context = useDocusaurusContext() const { siteConfig = {} } = context const errorCode = new URLSearchParams(location.search).get('code') const error = errorCodes[errorCode] return ( <Layout title={`${siteConfig.title} - A predictable state container for JavaScript apps.`} description="A predictable state container for JavaScript apps." > <main className={styles.mainFull}> <h1>Production Error Codes</h1> <p> When Redux is built and running in production, error text is replaced by indexed error codes to save on bundle size. These errors will provide a link to this page with more information about the error below. </p> {error && ( <React.Fragment> <p> <strong> The full text of the error you just encountered is: </strong> </p> <code className={styles.errorDetails}>{error}</code> </React.Fragment> )} <h2>All Error Codes</h2> <table> <thead> <tr> <th>Code</th> <th>Message</th> </tr> </thead> <tbody> {Object.keys(errorCodes).map(code => ( <tr> <td>{code}</td> <td>{errorCodes[code]}</td> </tr> ))} </tbody> </table> </main> </Layout> ) } export default Errors <|start_filename|>website/src/pages/styles.module.css<|end_filename|> .heroBanner { padding: 4rem 0; text-align: center; position: relative; overflow: hidden; } @media screen and (max-width: 966px) { .heroBanner { padding: 2rem; } } .buttons { display: flex; align-items: center; justify-content: center; } .features { display: flex; align-items: center; padding: 2rem 0; width: 100%; } .featureTitle { text-align: center; margin: 1rem 0; } .featureImage { height: 100px; width: 100px; fill: var(--ifm-font-color-base); } .featureAnchor svg { margin-left: 5px; max-width: 16px; max-height: 16px; fill: var(--ifm-color-primary); } .mainFull { padding: 34px 16px; width: 100%; max-width: var(--ifm-container-width); margin: 0px auto; } .mainFull h1 { font-size: 3rem; color: var(--ifm-heading-color); font-weight: var(--ifm-heading-font-weight); line-height: var(--ifm-heading-line-height); } .mainFull p { margin-bottom: var(--ifm-leading); margin-top: 0; } .errorDetails { color: #ff6464; border-radius: 0.5rem; padding: 1rem; margin: 30px 0; font-weight: bold; background-color: rgba(255, 100, 100, 0.1); display: block; }
orendevops/redux
<|start_filename|>MTHawkeye/NetworkPlugins/Monitor/HawkeyeCore/MTHawkeyeUserDefaults+NetworkMonitor.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/21 // Created by: EuanC // #import "MTHawkeyeUserDefaults.h" NS_ASSUME_NONNULL_BEGIN @interface MTHawkeyeUserDefaults (NetworkMonitor) @property (nonatomic, assign) BOOL networkMonitorOn; @property (nonatomic, assign) BOOL networkTransactionBodyCacheOn; @property (nonatomic, assign) BOOL responseBodyCacheOn; @property (nonatomic, assign) float networkCacheLimitInMB; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeyeDemo/MTHawkeyeDemo/MemoryDemo/MemoryAllocationTestViewController.h<|end_filename|> // // MemoryAllocationTestViewController.h // MTHawkeyeDemo // // Created by EuanC on 29/07/2017. // Copyright © 2017 Meitu. All rights reserved. // #import <UIKit/UIKit.h> @interface MemoryAllocationTestViewController : UIViewController @end <|start_filename|>MTHawkeye/Utils/MTHawkeyeLFUCache.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/1/29 // Created by: 曹堃 // #include <list> #include <unordered_map> #include <dlfcn.h> // 所以包含 value 的头文件进来 #define KeyType uintptr_t #define ValueType Dl_info using namespace std; // map value 结构 typedef struct LFUMapValue { ValueType value; list<pair<int, list<KeyType>>>::iterator main_it; list<KeyType>::iterator sub_it; } LFUMapValue; class MTHawkeyeLFUCache { public: MTHawkeyeLFUCache(int capacity); ~MTHawkeyeLFUCache(); ValueType get(KeyType key); // 获取缓存,hash查找的复杂度 void put(KeyType key, ValueType value); // 加入缓存,相同的key会覆盖,hash插入的复杂度 void remove_key(KeyType key); // 删除一个key void clear(); // 删除全部 private: int max_cap; int cur_cap; // 储存 pair<count, subList<key> > 结构,count 访问次数,count 小到大,key 时间由新到旧 list<pair<int, list<KeyType>>> m_list; unordered_map<KeyType, LFUMapValue> u_map; // 储存 <key, LFUMapValue> 结构 unordered_map<KeyType, LFUMapValue>::iterator map_it; void right_move(LFUMapValue *value); // 把一个节点的key向右提高访问次数 }; <|start_filename|>MTHawkeye/TimeConsumingPlugins/ObjcCallTrace/HawkeyeCore/MTHawkeyeUserDefaults+ObjcCallTrace.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/21 // Created by: EuanC // #import "MTHawkeyeUserDefaults.h" NS_ASSUME_NONNULL_BEGIN @interface MTHawkeyeUserDefaults (ObjcCallTrace) @property (nonatomic, assign) BOOL objcCallTraceOn; @property (nonatomic, assign) CGFloat objcCallTraceTimeThresholdInMS; @property (nonatomic, assign) NSInteger objcCallTraceDepthLimit; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeyeDemo/MTHawkeyeDemo/MemoryDemo/FacebookProjects/GithubRepository.h<|end_filename|> // // GithubRepository.h // MTHawkeyeDemo // // Created by cqh on 29/06/2017. // Copyright © 2017 meitu. All rights reserved. // #import <Foundation/Foundation.h> @interface GithubRepository : NSObject @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSString *shortDescription; @property (nonatomic, copy) NSURL *url; - (instancetype)initWithName:(NSString *)name shortDescription:(NSString *)shortDescription url:(NSURL *)url; @end <|start_filename|>MTHawkeye/DefaultPlugins/MTHawkeyeDefaultPlugins.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 16/11/2017 // Created by: EuanC // #import <Foundation/Foundation.h> #import <MTHawkeye/MTHawkeyeClient.h> #import <MTHawkeye/MTHawkeyeUIClient.h> @interface MTHawkeyeDefaultPlugins : NSObject + (void)loadEarlyServices; + (void)addDefaultClientPluginsInto:(NSMutableArray<id<MTHawkeyePlugin>> *)clientPlugins; + (void)cleanDefaultClientPluginsFrom:(NSMutableArray<id<MTHawkeyePlugin>> *)clientPlugins; + (void)addDefaultUIClientMainPanelPluginsInto:(NSMutableArray<id<MTHawkeyeMainPanelPlugin>> *)mainPanelPlugins defaultFloatingWidgetsPluginsInto:(NSMutableArray<id<MTHawkeyeFloatingWidgetPlugin>> *)floatingWidgetPlugins defaultSettingUIPluginsInto:(NSMutableArray<id<MTHawkeyeSettingUIPlugin>> *)settingUIPlugins; + (void)cleanDefaultUIClientMainPanelPluginsFrom:(NSMutableArray<id<MTHawkeyeMainPanelPlugin>> *)mainPanelPlugins defaultFloatingWidgetsPluginsFrom:(NSMutableArray<id<MTHawkeyeFloatingWidgetPlugin>> *)floatingWidgetPlugins defaultSettingUIPluginsFrom:(NSMutableArray<id<MTHawkeyeSettingUIPlugin>> *)settingUIPlugins; @end <|start_filename|>MTHawkeye/MemoryPlugins/Allocations/Core/mtha_inner_allocate.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/7/27 // Created by: EuanC // #ifndef mtha_inner_allocate_h #define mtha_inner_allocate_h #include <malloc/malloc.h> #include <stdio.h> #include <sys/types.h> #define VM_AMKE_TAG_HAWKEYE_UNIQUING_TABLE 200 // #ifdef __cplusplus extern "C" { #endif void mtha_setup_hawkeye_malloc_zone(malloc_zone_t *zone); void *mtha_allocate_page(uint64_t memSize); int mtha_deallocate_pages(void *memPointer, uint64_t memSize); void *mtha_malloc(size_t size); void *mtha_realloc(void *ptr, size_t size); void mtha_free(void *ptr); #ifdef __cplusplus } #endif #endif /* mtha_inner_allocate_h */ <|start_filename|>MTHawkeyeDemo/MTHawkeyeDemo/GraphicsDemo/GLESTool.h<|end_filename|> // // GLESTool.h // MTHawkeyeDemo // // Created by David.Dai on 2019/3/20. // Copyright © 2019 Meitu. All rights reserved. // #import <Foundation/Foundation.h> #import <GLKit/GLKit.h> NS_ASSUME_NONNULL_BEGIN #define GLES_LONG_STRING(x) #x #define GLES_SHADER_STRING(name) @GLES_LONG_STRING(name) extern NSString *const kTexutreVertexShaderString; extern NSString *const kTextureFragmentShaderString; typedef struct { GLuint program; GLuint vertexShader; GLuint fragmentShader; } GLESProgram; typedef struct { GLint positionAttribute; GLint inputTextureCoorAttribute; GLint textureUniform; } GLESTextureProgramAttribute; typedef struct { GLuint texutreId; float width; float height; } GLESTextureInfo; @interface GLESTool : NSObject + (GLESProgram)programWithVertexShader:(NSString *)vertexShaderStr fragmentShader:(NSString *)fragmentShaderStr; + (void)releaseProgram:(GLESProgram)program; + (GLESTextureProgramAttribute)attchTextureAttributeToProgram:(GLESProgram)program; + (GLint)attributeIndex:(NSString *)attributeName program:(GLuint)program; + (GLint)uniformIndex:(NSString *)uniformName program:(GLuint)program; + (GLESTextureInfo)texture:(UIImage *)image; + (void)releaseTexture:(GLESTextureInfo)textureInfo; + (unsigned char *)pixelRGBABytesFromImageRef:(CGImageRef)imageRef; + (GLfloat *)textureVertexForViewSize:(CGSize)viewSize textureSize:(CGSize)textureSize; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/Utils/MTHawkeyeHooking.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 28/10/2017 // Created by: EuanC // #import <Foundation/Foundation.h> #import <objc/message.h> #import <objc/runtime.h> @interface MTHawkeyeHooking : NSObject // 生成的方法名每次都不一样,包含随机数 + (SEL)swizzledSelectorForSelector:(SEL)selector; // 生成的 selector 每次都一样,不包含随机数 + (SEL)swizzledSelectorForSelectorConstant:(SEL)selector; + (BOOL)instanceRespondsButDoesNotImplementSelector:(SEL)selector onClass:(Class)cls; + (void)replaceImplementationOfKnownSelector:(SEL)originalSelector onClass:(Class)cls withBlock:(id)block swizzledSelector:(SEL)swizzledSelector; + (void)replaceImplementationOfSelector:(SEL)selector withSelector:(SEL)swizzledSelector forClass:(Class)cls withMethodDescription:(struct objc_method_description)methodDescription implementationBlock:(id)implementationBlock undefinedBlock:(id)undefinedBlock; @end <|start_filename|>MTHawkeye/NetworkPlugins/HawkeyeUI/MTHNetworkMonitorFilterViewController.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2017/9/8 // Created by: 潘名扬 // #import <UIKit/UIKit.h> #import "MTHNetworkTransactionsURLFilter.h" NS_ASSUME_NONNULL_BEGIN @protocol MTHNetworkMonitorFilterDelegate <NSObject> - (void)filterUpdatedWithStatusCodes:(MTHNetworkTransactionStatusCode)statusCodes inspections:(nullable NSArray *)inspections hosts:(nullable NSArray *)hosts; @end @interface MTHNetworkMonitorFilterViewController : UITableViewController @property (nonatomic, weak) id<MTHNetworkMonitorFilterDelegate> filterDelegate; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/UISkeleton/Utils/MTHawkeyeWebViewController.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 6/10/17 // Created by: EuanC // #import <UIKit/UIKit.h> @interface MTHawkeyeWebViewController : UIViewController - (id)initWithURL:(NSURL *)url; - (id)initWithText:(NSString *)text; + (BOOL)supportsPathExtension:(NSString *)extension; @end <|start_filename|>MTHawkeye/NetworkPlugins/Monitor/Core/Observer/MTHURLSessionDelegateProxy.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 25/08/2017 // Created by: EuanC // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @class MTHNetworkObserver; @interface MTHURLSessionDelegateProxy : NSObject <NSURLSessionDelegate> - (instancetype)initWithOriginalDelegate:(nullable id)delegate observer:(MTHNetworkObserver *)observer; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/UISkeleton/Toast/MTHToastWindow.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 29/06/2018 // Created by: Huni // #import <UIKit/UIKit.h> @interface MTHToastWindow : UIWindow + (instancetype)sharedWindow; @end <|start_filename|>MTHawkeye/NetworkPlugins/HawkeyeUI/MTHNetworkHawkeyeUI.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/24 // Created by: EuanC // #import <Foundation/Foundation.h> #import <MTHawkeye/MTHawkeyeUIPlugin.h> NS_ASSUME_NONNULL_BEGIN @class MTHawkeyeSettingSectionEntity; @interface MTHNetworkHawkeyeSettingUI : NSObject <MTHawkeyeSettingUIPlugin> + (MTHawkeyeSettingSectionEntity *)networkInspecSection; @end @interface MTHNetworkMonitorHawkeyeMainPanelUI : NSObject <MTHawkeyeMainPanelPlugin> @end @interface MTHNetworkInspectHawkeyeMainPanelUI : NSObject <MTHawkeyeMainPanelPlugin> @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/UISkeleton/MTHawkeyeUserDefaults+UISkeleton.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/16 // Created by: EuanC // #import "MTHawkeyeUserDefaults.h" NS_ASSUME_NONNULL_BEGIN @interface MTHawkeyeUserDefaults (UISkeleton) @property (nonatomic, assign) BOOL displayFloatingWindow; // default YES. @property (nonatomic, assign) BOOL floatingWindowShowHideGesture; // default YES @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/NetworkPlugins/Monitor/Core/Stat/MTHNetworkStat.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 28/07/2017 // Created by: EuanC // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN extern NSInteger gMTHNetworkStatDefaultPoorBandwidth; // default 150 extern NSInteger gMTHNetworkStatDefaultModerateBandwidth; // default 550 extern NSInteger gMTHNetworkStatDefaultGoodBandwidth; // default 2000 // factor used to calculate the current bandwidth // depending upon the previous calculated value for bandwidth. // the smaller this value is, the less responsive to new samples the moving average becomes. extern CGFloat gMTHNetworkStatDefaultDecayConstant; // default: 0.1, facebook default: 0.05 // the lower bound for measured bandwidth in bits/ms. // reading lower than this are treated as effectively zero (therefore ignored). extern CGFloat gMTHNetworkStatBandwidthLowerBound; // default: 0.1, facebook default: 20 extern CGFloat gMTHNetworkStatBytesLowerBound; // default: 20 extern NSInteger gMTHNetworkStatDefaultSamplesToQualityChange; // default 3 /** 目前暂缺乏可用的 API 测量实际的下行带宽 此仅为网络质量的大概估算,实际应用过程中,如果为 Poor,请尽量减少网络请求的数量和请求包大小 Moderate 下,能满足普通应用的一般频率网络请求需求 */ typedef NS_ENUM(NSInteger, MTHawkeyeNetworkConnectionQuality) { MTHawkeyeNetworkConnectionQualityUnknown = 0, // Placeholder for unknown bandwidth. MTHawkeyeNetworkConnectionQualityPoor = 1, // Bandwidth under 150 kbps. MTHawkeyeNetworkConnectionQualityModerate = 2, // Bandwidth between 150 and 550 kbps. MTHawkeyeNetworkConnectionQualityGood = 3, // Bandwidth between 550 and 2000 kbps. MTHawkeyeNetworkConnectionQualityExcellent = 4, // EXCELLENT - Bandwidth over 2000 kbps. }; @interface MTHNetworkStat : NSObject @property (atomic, assign, readonly) MTHawkeyeNetworkConnectionQuality connQuality; + (instancetype)shared; - (void)addBandwidthWithBytes:(int64_t)bytes duration:(NSTimeInterval)timeInMs; - (void)reset; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/NetworkPlugins/Monitor/Core/Observer/MTHNetworkObserver.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 28/08/2017 // Created by: EuanC // #import <Foundation/Foundation.h> @interface MTHNetworkObserver : NSObject /// Swizzling occurs when the observer is enabled for the first time. /// NOTE: this setting persists between launches of the app. + (void)setEnabled:(BOOL)enabeld; + (BOOL)isEnabled; @end <|start_filename|>MTHawkeye/UISkeleton/ChartView/MTHMonitorChartView.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 04/07/2017 // Created by: EuanC // #import <UIKit/UIKit.h> @protocol MTHMonitorChartViewDelegate; @interface MTHMonitorChartView : UIView @property (weak, nonatomic) id<MTHMonitorChartViewDelegate> delegate; @property (copy, nonatomic) NSString *unitLabelTitle; - (void)reloadData; @end @protocol MTHMonitorChartViewDelegate <NSObject> @required - (NSInteger)numberOfPointsInChartView:(MTHMonitorChartView *)chartView; - (CGFloat)chartView:(MTHMonitorChartView *)chartView valueForPointAtIndex:(NSInteger)index; @optional - (BOOL)rangeSelectEnableForChartView:(MTHMonitorChartView *)chartView; - (void)chartView:(MTHMonitorChartView *)chartView didSelectedWithIndexRange:(NSRange)indexRange; @end <|start_filename|>MTHawkeye/Utils/MTHawkeyeWeakProxy.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2017/6/29 // Created by: YWH // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN /** A proxy used to hold a weak object. It can be used to avoid retain cycles, such as the target in NSTimer or CADisplayLink. sample code: @implementation MyView { NSTimer *_timer; } - (void)initTimer { MTHawkeyeWeakProxy *proxy = [MTHawkeyeWeakProxy proxyWithTarget:self]; _timer = [NSTimer timerWithTimeInterval:0.1 target:proxy selector:@selector(tick:) userInfo:nil repeats:YES]; } - (void)tick:(NSTimer *)timer {...} @end */ @interface MTHawkeyeWeakProxy : NSProxy /** The proxy target. */ @property (nullable, nonatomic, weak, readonly) id target; /** Creates a new weak proxy for target. @param target Target object. @return A new proxy object. */ - (instancetype)initWithTarget:(id)target; /** Creates a new weak proxy for target. @param target Target object. @return A new proxy object. */ + (instancetype)proxyWithTarget:(id)target; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/MemoryPlugins/Allocations/Core/mtha_inner_log.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/11/26 // Created by: EuanC // #ifndef mtha_inner_log_h #define mtha_inner_log_h #ifdef __has_include #if __has_include("MTHawkeyeLogMacros.h") #include "MTHawkeyeLogMacros.h" #else #define MTHLog(fmt, ...) NSLog((@"%s " fmt), ##__VA_ARGS__) #define MTHLogInfo(fmt, ...) NSLog((@"[Info] " fmt), ##__VA_ARGS__) #define MTHLogWarn(fmt, ...) NSLog((@"[Warn] " fmt), ##__VA_ARGS__) #define MTHLogError(fmt, ...) NSLog((@"[Error] " fmt), ##__VA_ARGS__) #endif #endif // __has_include #endif /* mtha_inner_log_h */ <|start_filename|>MTHawkeyeDemo/MTHawkeyeDemo/GraphicsDemo/GraphicsTextureGLKView.h<|end_filename|> // // GraphicsTextureGLKView.h // MTHawkeyeDemo // // Created by David.Dai on 2019/3/20. // Copyright © 2019 Meitu. All rights reserved. // #import <GLKit/GLKit.h> #import "GLESTool.h" NS_ASSUME_NONNULL_BEGIN @interface GraphicsTextureGLKView : GLKView @property (nonatomic, strong, nullable) UIImage *imageToRender; @property (nonatomic, assign) BOOL leakTexture; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeyeDemo/MTHawkeyeDemo/StorageDemo/StorageDemoTableViewController.h<|end_filename|> // // StorageDemoTableViewController.h // MTHawkeyeDemo // // Created by EuanC on 2019/3/7. // Copyright © 2019 Meitu. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface StorageDemoTableViewController : UITableViewController @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/UISkeleton/Toast/MTHToastViewMaker.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 07/06/2018 // Created by: Huni // #import <Foundation/Foundation.h> typedef NS_ENUM(NSInteger, MTHToastViewStyle) { MTHToastViewStyleSimple = 0, MTHToastViewStyleDetail }; @interface MTHToastViewMaker : NSObject @property (nonatomic, assign) MTHToastViewStyle style; @property (nonatomic, copy) NSString *title; @property (nonatomic, copy) NSString *shortContent; @property (nonatomic, copy) NSString *longContent; @property (nonatomic, assign) NSTimeInterval stayDuration; @property (nonatomic, assign) BOOL expendHidden; @end <|start_filename|>MTHawkeye/NetworkPlugins/Monitor/Core/Utils/NSData+MTHawkeyeNetwork.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 31/07/2017 // Created by: EuanC // #import <Foundation/Foundation.h> @interface NSData (MTHawkeyeNetwork) - (NSString *)MTHNetwork_MD5HexDigest; - (NSData *)MTHNetwork_gzippedData; @end <|start_filename|>MTHawkeye/UISkeleton/MTHawkeyeSettingUIEntity.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/14 // Created by: EuanC // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @protocol MTHawkeyeSettingUIPlugin; @protocol MTHawkeyeFloatingWidgetDisplaySwitcherPlugin; @class MTHawkeyeSettingTableEntity; @class MTHawkeyeSettingFoldedCellEntity; @interface MTHawkeyeSettingUIEntity : NSObject @property (readonly) NSMutableArray<id<MTHawkeyeSettingUIPlugin>> *plugins; @property (readonly) NSMutableArray<id<MTHawkeyeFloatingWidgetDisplaySwitcherPlugin>> *floatingWidgetCells; - (instancetype)initWithSettingPlugins:(NSArray<id<MTHawkeyeSettingUIPlugin>> *)settingPlugins floatingWidgetSwitchers:(NSArray<id<MTHawkeyeFloatingWidgetDisplaySwitcherPlugin>> *)floatingWidgetSwitchers; - (void)addSettingPlugin:(id<MTHawkeyeSettingUIPlugin>)plugin; - (void)removeSettingPlugin:(id<MTHawkeyeSettingUIPlugin>)plugin; - (void)removeAllSettingPlugins; - (void)addFloatingWidgetSwitcher:(id<MTHawkeyeFloatingWidgetDisplaySwitcherPlugin>)plugin; - (void)removeFloatingWidgetSwitcher:(id<MTHawkeyeFloatingWidgetDisplaySwitcherPlugin>)plugin; - (void)removeAllFloatingWidget; - (MTHawkeyeSettingTableEntity *)settingViewModelEntity; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/UISkeleton/Toast/MTHToastBtnHandler.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 03/09/2018 // Created by: Huni // #import <Foundation/Foundation.h> typedef NS_ENUM(NSInteger, MTHToastActionStyle) { MTHToastActionStyleLeft = 0, MTHToastActionStyleRight }; typedef void (^MTHToastAction)(void); @interface MTHToastBtnHandler : NSObject + (instancetype)actionWithTitle:(NSString *)title style:(MTHToastActionStyle)style handler:(MTHToastAction)handler; @property (nonatomic, readonly) NSString *title; @property (nonatomic, readonly) MTHToastActionStyle style; @property (nonatomic, readonly) MTHToastAction handler; @end <|start_filename|>MTHawkeye/NetworkPlugins/Monitor/Core/MTHNetworkMonitor.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 17/07/2017 // Created by: EuanC // #import <Foundation/Foundation.h> @interface MTHNetworkMonitor : NSObject + (instancetype)shared; - (void)start; - (void)stop; - (BOOL)isRunning; @end <|start_filename|>MTHawkeyeDemo/MTHawkeyeDemo/MemoryDemo/EnormousView.h<|end_filename|> // // EnormousView.h // MTHawkeyeDemo // // Created by EuanC on 16/08/2017. // Copyright © 2017 Meitu. All rights reserved. // #import <UIKit/UIKit.h> @interface EnormousView : UIView @end <|start_filename|>MTHawkeye/MemoryPlugins/Allocations/HawkeyeUI/MTHAllocationsViewController.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/11/20 // Created by: EuanC // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN /** The result of symbolics service. @param mallocReport Symbolicated malloc report, it will used to display on the next screen. @param vmReport Symbolicated vm report, it will used to display on the next screen. @param error Symbolics process error. */ typedef void (^MTHAllocationsReportSymbolicsCompletion)(NSString *mallocReport, NSString *vmReport, NSError *error); /** Implement your own symbolics service completely. @param mallocReportInJson The original malloc report in json style, the stack record inside need symbolicated. @param vmReportInJson The original vm report in json style, the stack record inside need symbolicated. @param dyldImagesInfoInJson The necessary dyld images info for symbolicate. @param completion Completion callback, see `MTHAllocationsReportSymolicateCompletion` */ typedef void (^MTHAllocationsReportSymbolicateHandler)(NSString *mallocReportInJson, NSString *vmReportInJson, NSString *dyldImagesInfoInJson, MTHAllocationsReportSymbolicsCompletion completion); /** Setup this handler to implement your own symbolics service completely. */ extern MTHAllocationsReportSymbolicateHandler mthAllocationSymbolicsHandler; @interface MTHAllocationsViewController : UIViewController @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/NetworkPlugins/HawkeyeUI/MTHNetworkTransactionAdviceDetailViewController.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2017/9/1 // Created by: 潘名扬 // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @class MTHNetworkTaskAdvice; @interface MTHNetworkTransactionAdviceDetailViewController : UITableViewController @property (nonatomic, strong) MTHNetworkTaskAdvice *advice; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/NetworkPlugins/HawkeyeUI/MTHNetworkTransactionTableViewCell.h<|end_filename|> // // Copyright (c) 2014-2016, Flipboard // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2/8/15 // Created by: <NAME> // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN extern NSString *const kMTHNetworkTransactionCellIdentifier; @class MTHNetworkTransaction; @interface MTHNetworkTransactionTableViewCell : UITableViewCell @property (nonatomic, strong) MTHNetworkTransaction *transaction; + (CGFloat)preferredCellHeight; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/Utils/MTHawkeyePropertyBox.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 10/10/2017 // Created by: EuanC // #import <Foundation/Foundation.h> #import <objc/runtime.h> /* https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html R The property is read-only (readonly). C The property is a copy of the value last assigned (copy). & The property is a reference to the value last assigned (retain). N The property is non-atomic (nonatomic). G<name> The property defines a custom getter selector name. The name follows the G (for example, GcustomGetter,). S<name> The property defines a custom setter selector name. The name follows the S (for example, ScustomSetter:,) D The property is dynamic (@dynamic). W The property is a weak reference (__weak). P The property is eligible for garbage collection. t<encoding> Specifies the type using old-style encoding. # The property is a Class struct eg: strongDelegate, T@"<PhotoDetailViewControllerDelegate1>",&,N,V_strongDelegate aString, T@"NSString",C,N,VaStringNewName fullScreenRatio, TB,R,N,V_fullScreenRatio networkReachability, T^{__SCNetworkReachability=},R,N,V_networkReachability completionHandler, T@?,C,N,V_completionHandler delegateQueue, T^{dispatch_queue_s=} statement, T^v,V_statement // void *statement; classProperty, T#,&,N,V_classProperty // Class classProperty; */ #ifdef __cplusplus extern "C" { #endif typedef struct _mthawkeye_property_box { const char *property_name; const char *attributtes_short; bool is_strong; bool is_copy; bool is_weak; bool is_readonly; bool is_nonatomic; bool is_dynamic; char ivar_name[512]; char type_name[128]; } mthawkeye_property_box; mthawkeye_property_box mthawkeye_extract_property(objc_property_t property); #ifdef __cplusplus } #endif <|start_filename|>MTHawkeye/MemoryPlugins/Allocations/Core/NSObject+MTHAllocTrack.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/10/16 // Created by: EuanC // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN typedef void(mtha_set_last_allocation_event_name_t)(void *ptr, const char *classname); extern mtha_set_last_allocation_event_name_t *mtha_allocation_event_logger; @interface NSObject (MTHAllocTrack) + (void)mtha_startAllocTrack; + (void)mtha_endAllocTrack; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/MemoryPlugins/LivingObjectSniffer/Core/MTHLivingObjectShadow.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/6 // Created by: EuanC // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN #define MTHLivingObjectSnifferPerformanceTestEnabled 0 #ifdef MTHLivingObjectSnifferPerformanceTestEnabled #define _InternalMTHLivingObjectSnifferPerformanceTestEnabled MTHLivingObjectSnifferPerformanceTestEnabled #else #define _InternalMTHLivingObjectSnifferPerformanceTestEnabled NO #endif extern BOOL mthawkeye_livingObjectsSnifferNSFoundationContainerEnabled; @class MTHLivingObjectShadow; @class MTHLivingObjectShadowPackage; @protocol MTHLivingObjectShadowing <NSObject> - (BOOL)mth_castShadowOver:(MTHLivingObjectShadowPackage *)shadowPackage withLight:(nullable id)light; - (MTHLivingObjectShadow *)mth_castShadowFromLight:(nullable id)light; - (BOOL)mth_shouldObjectAlive; @end @interface MTHLivingObjectShadow : NSObject @property (nonatomic, weak, nullable) id target; // when the target release, the shadow itself will released. @property (nonatomic, weak, nullable) id light; // when the light source 'released', the target should release. @property (nonatomic, copy, nullable) NSString *lightName; // the class name of the light. @property (nonatomic, assign) NSTimeInterval createAt; // shadow create time. - (instancetype)initWithTarget:(id)object; @end @interface MTHLivingObjectShadowPackage : NSObject @property (nonatomic, readonly) NSHashTable<MTHLivingObjectShadow *> *shadows; - (BOOL)addShadow:(MTHLivingObjectShadow *)shadow; @end /****************************************************************************/ #pragma mark - typedef enum : NSUInteger { MTHLivingObjectShadowTriggerTypeUnknown = 0, MTHLivingObjectShadowTriggerTypeViewController = 1, MTHLivingObjectShadowTriggerTypeView = 2, } MTHLivingObjectShadowTriggerType; /** Keep who collect the shadow, would be useful to restore how shadow create. */ @interface MTHLivingObjectShadowTrigger : NSObject - (instancetype)initWithType:(MTHLivingObjectShadowTriggerType)type; - (instancetype)initWithDictionary:(NSDictionary *)dict; - (NSDictionary *)inDictionary; @property (nonatomic, assign) NSTimeInterval startTime; @property (nonatomic, assign) NSTimeInterval endTime; @property (nonatomic, assign) MTHLivingObjectShadowTriggerType type; @property (nonatomic, copy) NSString *name; /** for ViewControllers that has childViewControllers, the trigger would be parent. we keep the child info under nameExtra. form in "childA,childB,childC". */ @property (nonatomic, copy) NSString *nameExtra; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/UISkeleton/FloatingWindow/MTHMonitorViewCell.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 30/06/2017 // Created by: EuanC // #import <UIKit/UIKit.h> @interface MTHMonitorViewCell : UITableViewCell @property (nonatomic, strong, readonly) UILabel *infoLabel; - (instancetype)init; - (void)updateWithString:(NSString *)content; - (void)updateWithString:(NSString *)content color:(UIColor *)color; - (void)updateWithValue:(NSString *)value unit:(NSString *)unit; - (void)updateWithValue:(NSString *)value valueColor:(UIColor *)valueColor unit:(NSString *)unit unitColor:(UIColor *)unitColor; - (void)updateWithAttributeString:(NSAttributedString *)content; - (void)flashingWithDuration:(CGFloat)durationInSeconds color:(UIColor *)flashColor; @end <|start_filename|>MTHawkeye/TimeConsumingPlugins/UITimeProfiler/HawkeyeUI/MTHTimeIntervalStepsViewCell.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/7/3 // Created by: 潘名扬 // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @class MTHCallTraceTimeCostModel; @class MTHTimeIntervalCustomEventRecord; @interface MTHTimeIntervalStepsViewCellModel : NSObject @property (nonatomic, assign) NSTimeInterval timeStamp; @property (nonatomic, copy, nullable) NSString *timeStampTitle; @property (nonatomic, strong, nullable) MTHCallTraceTimeCostModel *timeCostModel; @property (nonatomic, strong, nullable) MTHTimeIntervalCustomEventRecord *customEvent; @end @interface MTHTimeIntervalStepsViewCell : UITableViewCell @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/NetworkPlugins/Monitor/HawkeyeCore/MTHNetworkRecordsStorage.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/24 // Created by: EuanC // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @class MTHNetworkTransaction; @interface MTHNetworkRecordsStorage : NSObject + (instancetype)shared; - (void)storeNetworkTransaction:(MTHNetworkTransaction *)transaction; - (NSArray<MTHNetworkTransaction *> *)readNetworkTransactions; + (void)trimCurrentSessionLargeRecordsToCost:(NSUInteger)costLimitInMB; // MARK: - + (NSUInteger)getCurrentSessionRecordsFileSize; + (NSUInteger)getHistorySessionRecordsFileSize; + (void)removeAllCurrentSessionRecords; + (void)removeAllHistorySessionRecords; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeyeDemo/MTHawkeyeDemo/MemoryDemo/ALeakingViewController.h<|end_filename|> // // ALeakingViewController.h // MTHawkeyeDemo // // Created by cqh on 29/06/2017. // Copyright © 2017 meitu. All rights reserved. // #import <UIKit/UIKit.h> @interface ALeakingViewController : UIViewController @end <|start_filename|>MTHawkeye/TimeConsumingPlugins/UITimeProfiler/HawkeyeUI/MTHUITimeProfilerHawkeyeUI.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/24 // Created by: EuanC // #import <Foundation/Foundation.h> #import <MTHawkeye/MTHawkeyeUIPlugin.h> NS_ASSUME_NONNULL_BEGIN @interface MTHUITimeProfilerHawkeyeUI : NSObject <MTHawkeyeSettingUIPlugin, MTHawkeyeMainPanelPlugin> @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/UISkeleton/FloatingWindow/MTHMonitorViewConfiguration.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 02/12/2017 // Created by: EuanC // #import <Foundation/Foundation.h> @interface MTHMonitorViewConfiguration : NSObject @property (nonatomic, assign, class) CGFloat monitorWidth; @property (nonatomic, assign, class) CGFloat monitorCellHeight; @property (nonatomic, strong, class) UIFont *valueFont; @property (nonatomic, strong, class) UIColor *valueColor; @property (nonatomic, strong, class) UIFont *unitFont; @property (nonatomic, strong, class) UIColor *unitColor; @property (nonatomic, assign, class) CGPoint monitorInitPosition; @end <|start_filename|>MTHawkeye/UISkeleton/Utils/UIViewController+MTHawkeyeLayoutSupport.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 11/08/2017 // Created by: EuanC // #import <UIKit/UIKit.h> @interface UIViewController (MTHawkeyeLayoutSupport) - (id<UILayoutSupport>)mt_hawkeye_navigationBarTopLayoutGuide; - (id<UILayoutSupport>)mt_hawkeye_navigationBarBottomLayoutGuide; @end <|start_filename|>MTHawkeye/NetworkPlugins/Inspect/Core/MTHNetworkTaskAdvice.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 24/08/2017 // Created by: EuanC // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN typedef NS_ENUM(NSInteger, MTHNetworkTaskAdviceLevel) { MTHNetworkTaskAdviceLevelHigh = 0, MTHNetworkTaskAdviceLevelMiddle = 1, MTHNetworkTaskAdviceLevelLow = 2, }; @interface MTHNetworkTaskAdvice : NSObject @property (nonatomic, copy) NSString *typeId; // 标记问题类型,不同 Transaction 里的 advice 之间同 typeId 的可以聚合为一组 @property (nonatomic, assign) MTHNetworkTaskAdviceLevel level; @property (nonatomic, assign) NSInteger requestIndex; @property (nonatomic, copy, nullable) NSString *adviceTitleText; // the title of advice @property (nonatomic, copy, nullable) NSString *adviceDescText; // advice detail @property (nonatomic, copy, nullable) NSString *suggestDescText; // suggestion detail @property (nonatomic, copy, nullable) NSDictionary<NSString *, NSArray<NSNumber *> *> *userInfo; // 可用于存放关联的请求等信息 [key:string , value: [Int]] - (NSString *)levelText; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/Utils/MTHawkeyeInnerLogger.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/6/14 // Created by: EuanC // #if __has_include(<CocoaLumberjack/CocoaLumberjack.h>) #import <CocoaLumberjack/CocoaLumberjack.h> #import <Foundation/Foundation.h> @interface MTHawkeyeInnerLogger : NSObject /** Don't call directly, use MTHLog/MTHLogInfo/MTHLogWarn/MTHLogError */ + (void)log:(BOOL)asynchronous level:(DDLogLevel)level flag:(DDLogFlag)flag tag:(id __nullable)tag format:(nullable NSString *)format, ... NS_FORMAT_FUNCTION(5, 6); /** inner log format: "mm:ss:SSS log content" @param logLevel Log levels are used to filter out logs. Used together with flags. */ + (void)setupFileLoggerWithLevel:(DDLogLevel)logLevel; /** inner log format: "[hawkeye] mm:ss:SSS log content" */ + (void)setupConsoleLoggerWithLevel:(DDLogLevel)logLevel; + (void)configFileLoggerLevel:(DDLogLevel)logLevel; + (void)configConsoleLoggerLevel:(DDLogLevel)logLevel; @end #else // __has_include(<CocoaLumberjack/CocoaLumberjack.h>) #endif // __has_include(<CocoaLumberjack/CocoaLumberjack.h>) <|start_filename|>MTHawkeye/NetworkPlugins/Monitor/Core/Recorder/MTHNetworkRecorder.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 25/07/2017 // Created by: EuanC // #import <Foundation/Foundation.h> #import "MTHNetworkTransaction.h" NS_ASSUME_NONNULL_BEGIN @class MTHNetworkTaskAPIUsage; @class MTHNetworkTaskSessionConfigAPIUsage; @class MTHNetworkTransaction; @class MTHNetworkRepeatTransactions; @protocol MTHNetworkRecorderDelegate; @interface MTHNetworkRecorder : NSObject /// In general, it only makes sense to have one recorder for the entire application. + (instancetype)defaultRecorder; - (void)addDelegate:(id<MTHNetworkRecorderDelegate>)delegate; - (void)removeDelegate:(id<MTHNetworkRecorderDelegate>)delegate; /// Array of MTHawkeyeNetworkTransaction objects ordered by start time with the newest first. /// You must read transactions from the storage module and set them to this property, before inspection. /// Since it is a weak property, You have to hold a strong reference to the array until you don't need it. //@property (nonatomic, weak) NSArray<MTHNetworkTransaction *> *networkTransactions; ///// 记录 response data 的 MD5 值,用于侦测重复的网络请求 //@property (nonatomic, assign) BOOL shouldCacheResponseDataMD5; @property (nonatomic, copy) NSArray<NSString *> *hostBlacklist; /// 记录重复的网络请求时,在此黑名单内的不计入 //@property (nonatomic, copy) NSArray<NSString *> *repeatTransactionsHostBlackList; // Recording network activity /// Call when app is about to send HTTP request. - (void)recordRequestWillBeSentWithRequestID:(NSString *)requestID request:(NSURLRequest *)request redirectResponse:(nullable NSURLResponse *)redirectResponse; /// Call to collect API Usage before HTTP request completed for Network Inpect. - (void)recordRequestTaskAPIUsageWithRequestID:(NSString *)requestID taskAPIUsage:(MTHNetworkTaskAPIUsage *)taskAPIUsage taskSessionConfigAPIUsage:(MTHNetworkTaskSessionConfigAPIUsage *)taskSessionConfigAPIUsage; /// Call when HTTP response is available. - (void)recordResponseReceivedWithRequestID:(NSString *)requestID response:(NSURLResponse *)response; /// Call when data chunk is received over the network. - (void)recordDataReceivedWithRequestID:(NSString *)requestID dataLength:(int64_t)dataLength; /// Call when HTTP request has finished loading. - (void)recordLoadingFinishedWithRequestID:(NSString *)requestID responseBody:(NSData *)responseBody; /// Call when HTTP request has failed to load. - (void)recordLoadingFailedWithRequestID:(NSString *)requestID error:(NSError *)error; /// 后续统一切换使用 Metrics 来统计,主要调整 redirect request 相关逻辑 - (void)recordMetricsWithRequestID:(NSString *)requestID metrics:(NSURLSessionTaskMetrics *)metrics NS_AVAILABLE_IOS(10_0); /// Call to set the request mechanism anytime after recordRequestWillBeSent... has been called. /// This string can be set to anything useful about the API used to make the request. - (void)recordMechanism:(NSString *)mechanism forRequestID:(NSString *)requestID; @end @protocol MTHNetworkRecorderDelegate <NSObject> @optional - (void)recorderWantCacheTransactionAsUpdated:(MTHNetworkTransaction *)transaction currentState:(MTHNetworkTransactionState)state; - (void)recorderWantCacheNewTransaction:(MTHNetworkTransaction *)transaction; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeyeDemo/MTHawkeyeDemo/MemoryDemo/ANormalViewModel.h<|end_filename|> // // ANormalViewModel.h // MTHawkeyeDemo // // Created by EuanC on 04/08/2017. // Copyright © 2017 Meitu. All rights reserved. // #import <Foundation/Foundation.h> @interface ANormalViewModel : NSObject @property (nonatomic, strong) Class classProperty; /**< Class property, ivar type: #, lead to a crash of object_getIvar() */ @end <|start_filename|>MTHawkeyeDemo/MTHawkeyeDemo/NetworkDemo/MTURLConnectionInjectTestViewController.h<|end_filename|> // // MTURLConnectionInjectTestViewController.h // MTHawkeyeDemo // // Created by EuanC on 28/08/2017. // Copyright © 2017 Meitu. All rights reserved. // #import <UIKit/UIKit.h> @interface MTURLConnectionInjectTestViewController : UITableViewController @end <|start_filename|>MTHawkeye/NetworkPlugins/HawkeyeUI/MTHMultilineTableViewCell.h<|end_filename|> // // Copyright (c) 2014-2016, Flipboard // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2/13/15 // Created by: <NAME> // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN extern NSString *const kMTHawkeyeMultilineTableViewCellIdentifier; @interface MTHMultilineTableViewCell : UITableViewCell + (CGFloat)preferredHeightWithAttributedText:(NSAttributedString *)attributedText inTableViewWidth:(CGFloat)tableViewWidth style:(UITableViewStyle)style showsAccessory:(BOOL)showsAccessory; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/MemoryPlugins/LivingObjectSniffer/HawkeyeUI/MTHLivingObjectsSnifferHawkeyeUI.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/10 // Created by: EuanC // #import <Foundation/Foundation.h> #import "MTHawkeyeUIPlugin.h" NS_ASSUME_NONNULL_BEGIN /* Raise warning by flash label on the Hawkeye floating window only if the number of unexpected living instances of a View class exceeds this value. Default 20. */ extern NSInteger gHawkeyeWarningUnexpectedLivingCellViewCount; /* Raise warning by flash label on the Hawkeye floating window only if the number of unexpected living instances of a View class exceeds this value. Default count is 5. */ extern NSInteger gHawkeyeWarningUnexpectedLivingViewCount; /* The flush duration on the Hawkeye floating window when the warning is triggered. */ extern CGFloat gHawkeyeWarningUnexpectedLivingObjectFlashDuration; /* The duration of the toast when warning unexpected living View Controller */ extern CGFloat gHawkeyeWarningUnexpectedLivingVCObjectToastDuration; @class MTHawkeyeSettingSectionEntity; @interface MTHLivingObjectsSnifferHawkeyeUI : NSObject <MTHawkeyeMainPanelPlugin, MTHawkeyeSettingUIPlugin> @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/UISkeleton/Utils/UIViewController+MTHawkeyeCurrentViewController.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 02/07/2018 // Created by: Huni // #import <UIKit/UIKit.h> @interface UIViewController (MTHawkeyeCurrentViewController) + (UIViewController *)mth_topViewController; @end <|start_filename|>MTHawkeyeDemo/MTHawkeyeDemo/MemoryDemo/LeakingPropertiesSecondTestViewController.h<|end_filename|> // // LeakingPropertiesSecondTestViewController.h // MTHawkeyeDemo // // Created by EuanC on 03/08/2017. // Copyright © 2017 Meitu. All rights reserved. // #import <UIKit/UIKit.h> @class SharedInstanceExample; @interface LeakingPropertiesSecondTestViewController : UIViewController @property (nonatomic, strong) SharedInstanceExample *sampleViewModel; @end <|start_filename|>MTHawkeye/StorageMonitorPlugins/DirectoryWatcher/Core/MTHDirectoryWatcherMonitor.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/11/7 // Created by: Huni // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN typedef void (^__nullable MTHDirectoryWatcherChangeCallback)(NSString *path, NSUInteger folderSize); typedef void (^__nullable MTHDirectoryWatcherTriggerLimitFiredCallback)(NSString *path); @interface MTHDirectoryWatcherMonitor : NSObject /** * Watching paths */ @property (nonatomic, strong, readonly) NSArray<NSString *> *watchPaths; /** * Watching path detect interval */ @property (nonatomic, assign) NSTimeInterval detectInterval; /** * Each watcher change report count archive limit will call this block * You should use removePath: to stop watcher if need */ @property (nonatomic, copy) MTHDirectoryWatcherTriggerLimitFiredCallback watcherTriggerLimitFiredCallback; /** * Each watcher change report event will call this block */ @property (nonatomic, copy) MTHDirectoryWatcherChangeCallback watcherChangeCallback; /** * Monitor watching state */ @property (nonatomic, assign, readonly) BOOL isWatching; + (instancetype)shared; /** * Start monitoring */ - (void)startWatching; /** * Stop monitoring */ - (void)stopWatching; /** * Add a monitoring file path * * @param path Will watch the path after startWatching call * @param triggerLimit Will call watcherTriggerLimitFiredCallback block after triggerLimit archive, 0 never call */ - (void)addMonitorPath:(NSString *)path triggerLimit:(NSUInteger)triggerLimit; /** * Remove a monitoring file path * * @param path Stop watch the path immediately */ - (void)removePath:(NSString *)path; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/Utils/MTHawkeyeLogMacros.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/6/14 // Created by: EuanC // #pragma once #ifndef MTHAWKEYE_LOG_MACROS_H #define MTHAWKEYE_LOG_MACROS_H #import "MTHawkeyeInnerLogger.h" // clang-format off #ifdef DEBUG #if __has_include(<CocoaLumberjack/CocoaLumberjack.h>) #import <CocoaLumberjack/CocoaLumberjack.h> static DDLogLevel ddLogLevel = DDLogLevelVerbose; static DDLog *mthawkeye_ddlog = nil; /** * These are the two macros that all other macros below compile into. * These big multiline macros makes all the other macros easier to read. **/ #define MTH_LOG_MACRO(isAsynchronous, lvl, flg, ctx, atag, frmt, ...) \ [MTHawkeyeInnerLogger log : isAsynchronous \ level : lvl \ flag : flg \ tag : atag \ format : (frmt), ## __VA_ARGS__] #define MTH_LOG_MAYBE(async, lvl, flg, tag, frmt, ...) \ do { if(lvl & flg) MTH_LOG_MACRO(async, lvl, flg, tag, frmt, ##__VA_ARGS__); } while(0) #define MTHLog(fmt, ...) MTH_LOG_MAYBE(LOG_ASYNC_ENABLED, LOG_LEVEL_DEF, DDLogFlagVerbose, 0, nil, fmt, ##__VA_ARGS__) #define MTHLogDebug(fmt, ...) MTH_LOG_MAYBE(LOG_ASYNC_ENABLED, LOG_LEVEL_DEF, DDLogFlagDebug, 0, nil, (@"[Debug] " fmt), ##__VA_ARGS__) #define MTHLogInfo(fmt, ...) MTH_LOG_MAYBE(LOG_ASYNC_ENABLED, LOG_LEVEL_DEF, DDLogFlagInfo, 0, nil, (@"[Info] " fmt), ##__VA_ARGS__) #define MTHLogWarn(fmt, ...) MTH_LOG_MAYBE(LOG_ASYNC_ENABLED, LOG_LEVEL_DEF, DDLogFlagWarning, 0, nil, (@"[Warn] " fmt), ##__VA_ARGS__) #define MTHLogError(fmt, ...) MTH_LOG_MAYBE(LOG_ASYNC_ENABLED, LOG_LEVEL_DEF, DDLogFlagError, 0, nil, (@"[Error] " fmt), ##__VA_ARGS__) #else #define MTHLog(fmt, ...) NSLog((@"%s " fmt), ##__VA_ARGS__) #define MTHLogDebug(fmt, ...) NSLog((@"[Debug] " fmt), ##__VA_ARGS__) #define MTHLogInfo(fmt, ...) NSLog((@"[Info] " fmt), ##__VA_ARGS__) #define MTHLogWarn(fmt, ...) NSLog((@"[Warn] " fmt), ##__VA_ARGS__) #define MTHLogError(fmt, ...) NSLog((@"[Error] " fmt), ##__VA_ARGS__) #endif /* __has_include(<CocoaLumberjack/CocoaLumberjack.h>) */ #else // !DEBUG #if __has_include(<CocoaLumberjack/CocoaLumberjack.h>) #import <CocoaLumberjack/CocoaLumberjack.h> static DDLogLevel ddLogLevel = DDLogLevelVerbose; #define MTH_LOG_MACRO(isAsynchronous, lvl, flg, ctx, atag, frmt, ...) \ [MTHawkeyeInnerLogger log : isAsynchronous \ level : lvl \ flag : flg \ tag : atag \ format : (frmt), ## __VA_ARGS__] #define MTH_LOG_MAYBE(async, lvl, flg, tag, frmt, ...) \ do { if(lvl & flg) MTH_LOG_MACRO(async, lvl, flg, tag, frmt, ##__VA_ARGS__); } while(0) #define MTHLog(fmt, ...) MTH_LOG_MAYBE(LOG_ASYNC_ENABLED, LOG_LEVEL_DEF, DDLogFlagVerbose, 0, nil, fmt, ##__VA_ARGS__) #define MTHLogDebug(fmt, ...) MTH_LOG_MAYBE(LOG_ASYNC_ENABLED, LOG_LEVEL_DEF, DDLogFlagDebug, 0, nil, (@"[Debug] " fmt), ##__VA_ARGS__) #define MTHLogInfo(fmt, ...) MTH_LOG_MAYBE(LOG_ASYNC_ENABLED, LOG_LEVEL_DEF, DDLogFlagInfo, 0, nil, (@"[Info] " fmt), ##__VA_ARGS__) #define MTHLogWarn(fmt, ...) MTH_LOG_MAYBE(LOG_ASYNC_ENABLED, LOG_LEVEL_DEF, DDLogFlagWarning, 0, nil, (@"[Warn] " fmt), ##__VA_ARGS__) #define MTHLogError(fmt, ...) MTH_LOG_MAYBE(LOG_ASYNC_ENABLED, LOG_LEVEL_DEF, DDLogFlagError, 0, nil, (@"[Error] " fmt), ##__VA_ARGS__) #else #define MTHLog(fmt, ...) #define MTHLogDebug(fmt, ...) #define MTHLogInfo(fmt, ...) #define MTHLogWarn(fmt, ...) #define MTHLogError(fmt, ...) #endif /* __has_include(<CocoaLumberjack/CocoaLumberjack.h>) */ #endif // DEBUG // clang-format on #endif // MTHAWKEYE_LOG_MACROS_H <|start_filename|>MTHawkeye/Utils/MTHawkeyeSignPosts.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/28 // Created by: EuanC // #ifndef MTHawkeyeSignPosts_h #define MTHawkeyeSignPosts_h typedef NS_ENUM(uintptr_t, MTHSignpostColor) { MTHSignpostColorBlue, MTHSignpostColorGreen, MTHSignpostColorPurple, MTHSignpostColorOrange, MTHSignpostColorRed, MTHSignpostColorDefault }; // clang-format off #ifndef kCFCoreFoundationVersionNumber_iOS_10_0 #define kCFCoreFoundationVersionNumber_iOS_10_0 1348.00 #endif #define MTH_AT_LEAST_IOS10 (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iOS_10_0) #ifdef MTH_PROFILE #if __has_include(<sys/kdebug_signpost.h>) #define MTH_KDEBUG_ENABLE 1 #else #define MTH_KDEBUG_ENABLE 0 #endif #else #define MTH_KDEBUG_ENABLE 0 #endif #if MTH_KDEBUG_ENABLE #import <sys/kdebug_signpost.h> // These definitions are required to build the backward-compatible kdebug trace // on the iOS 10 SDK. The kdebug_trace function crashes if run on iOS 9 and earlier. // It's valuable to support trace signposts on iOS 9, because A5 devices don't support iOS 10. #ifndef DBG_MACH_CHUD #define DBG_MACH_CHUD 0x0A #define DBG_FUNC_NONE 0 #define DBG_FUNC_START 1 #define DBG_FUNC_END 2 #define DBG_APPS 33 #define SYS_kdebug_trace 180 #define KDBG_CODE(Class, SubClass, code) (((Class & 0xff) << 24) | ((SubClass & 0xff) << 16) | ((code & 0x3fff) << 2)) #define APPSDBG_CODE(SubClass, code) KDBG_CODE(DBG_APPS, SubClass, code) #endif // Currently we'll reserve arg3. #define MTHSignpost(name, identifier, arg2, color) \ MTH_AT_LEAST_IOS10 ? kdebug_signpost(name, (uintptr_t)identifier, (uintptr_t)arg2, 0, color) \ : syscall(SYS_kdebug_trace, APPSDBG_CODE(DBG_MACH_CHUD, name) | DBG_FUNC_NONE, (uintptr_t)identifier, (uintptr_t)arg2, 0, color); #define MTHSignpostStartCustom(name, identifier, arg2) \ MTH_AT_LEAST_IOS10 ? kdebug_signpost_start(name, (uintptr_t)identifier, (uintptr_t)arg2, 0, 0) \ : syscall(SYS_kdebug_trace, APPSDBG_CODE(DBG_MACH_CHUD, name) | DBG_FUNC_START, (uintptr_t)identifier, (uintptr_t)arg2, 0, 0); #define MTHSignpostStart(name) MTHSignpostStartCustom(name, self, 0) #define MTHSignpostEndCustom(name, identifier, arg2, color) \ MTH_AT_LEAST_IOS10 ? kdebug_signpost_end(name, (uintptr_t)identifier, (uintptr_t)arg2, 0, color) \ : syscall(SYS_kdebug_trace, APPSDBG_CODE(DBG_MACH_CHUD, name) | DBG_FUNC_END, (uintptr_t)identifier, (uintptr_t)arg2, 0, color); #define MTHSignpostEnd(name) MTHSignpostEndCustom(name, self, 0, MTHSignpostColorDefault) #else // !MTH_KDEBUG_ENABLE #define MTHSignpost(name, identifier, arg2, color) #define MTHSignpostStartCustom(name, identifier, arg2) #define MTHSignpostStart(name) #define MTHSignpostEndCustom(name, identifier, arg2, color) #define MTHSignpostEnd(name) #endif // MTH_KDEBUG_ENABLE // clang-format on #endif /* MTHawkeyeSignPosts_h */ <|start_filename|>MTHawkeye/MemoryPlugins/Allocations/Core/mtha_allocate_record_reader.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/7/27 // Created by: EuanC // #ifndef mtha_record_reader_h #define mtha_record_reader_h #include <list> #include <mach/mach.h> #include <stdio.h> #include <vector> #include "mtha_allocate_logging.h" namespace MTHAllocation { class AllocateRecords { public: /** Group allocation records by backtrace (stack_id) */ typedef struct { uint32_t size; /**< total size of memory allocate by this backtrace (stack_id) */ uint32_t count; /**< total count of memory pointers allocate by this backtrace (stack_id) */ uint64_t stack_id; /**< backtrace identify, refer to backtrace_uniquing_table */ } InStackId; /** Group allocation records by category */ typedef struct { const char *name; /**< category name */ uint32_t size; /**< total size of memory allocate under this category */ uint32_t count; /**< total count of memory pointers allocate under this category */ std::list<InStackId *> *stacks; /**< all the stacks that allocate memory under this category */ } InCategory; public: AllocateRecords(mtha_splay_tree *rawRecords) : _rawRecords(rawRecords) {} ~AllocateRecords(); /** Read the raw records and group it by Category & StackId */ void parseAndGroupingRawRecords(void); InCategory *firstRecordInCategory(void); InCategory *nextRecordInCategory(void); void resetInCategoryIterator(void); uint64_t recordSize() const; uint32_t allocateRecordCount() const; uint32_t stackRecordCount() const; uint32_t categoryRecordCount() const; private: void freeFormedRecords(void); mtha_splay_tree *_rawRecords = NULL; std::list<InCategory *> *_formedRecords = NULL; uint64_t _recordSize = 0; uint32_t _allocateRecordCount = 0; uint32_t _stackRecordCount = 0; uint32_t _categoryRecordCount = 0; const std::list<InCategory *>::const_iterator kNullIterator; std::list<InCategory *>::const_iterator _recordIterator = kNullIterator; private: AllocateRecords(const AllocateRecords &); AllocateRecords &operator=(const AllocateRecords &); }; } // namespace MTHAllocation #endif /* mtha_record_reader_h */ <|start_filename|>MTHawkeye/UISkeleton/MTHawkeyeMainPanels.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/9 // Created by: EuanC // #import <Foundation/Foundation.h> #import "MTHawkeyeMainPanelSwitchViewController.h" #import "MTHawkeyeMainPanelViewController.h" NS_ASSUME_NONNULL_BEGIN @protocol MTHawkeyeMainPanelPlugin; @protocol MTHawkeyeMainPanelSwitcherDelegate; @interface MTHawkeyeMainPanels : NSObject <MTHawkeyeMainPanelViewControllerDatasource, MTHawkeyeMainPanelSwitcherDelegate> @property (readonly) NSMutableArray<id<MTHawkeyeMainPanelPlugin>> *panels; - (instancetype)initWithMainPanelPlugins:(NSArray<id<MTHawkeyeMainPanelPlugin>> *)plugins; - (void)addMainPanelPlugin:(id<MTHawkeyeMainPanelPlugin>)plugin; - (void)removeMainPanelPlugin:(id<MTHawkeyeMainPanelPlugin>)plugin; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/EnergyPlugins/CPUTrace/HawkeyeUI/MTHCPURecordsViewController.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2017/10/13 // Created by: 潘名扬 // #import <UIKit/UIKit.h> @interface MTHCPURecordsViewController : UIViewController @end <|start_filename|>MTHawkeye/EnergyPlugins/CPUTrace/Core/MTHCPUTrace.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2017/6/29 // Created by: YWH // #import <UIKit/UIKit.h> #include <vector> #import "MTHCPUTraceHighLoadRecord.h" #ifndef MTH_CPUTraceDebugEnable #define MTH_CPUTraceDebugEnable 0 #define MTH_CPUTracePerformanceEnable 0 #endif #if MTH_CPUTraceDebugEnable #define MTHCPUDebugLog(fmt, ...) printf(fmt, ##__VA_ARGS__) #else #define MTHCPUDebugLog(fmt, ...) #endif @protocol MTHCPUTracingDelegate; @interface MTHCPUTrace : NSObject /** When the CPU is under low load, the frequency to check the CPU usage. default 1 second. */ @property (nonatomic, assign) CGFloat checkIntervalIdle; /** When the CPU is under high load, the frequency to check the CPU usage. default 0.3 second. */ @property (nonatomic, assign) CGFloat checkIntervalBusy; /** Only care when the CPU usage exceeding the threshold. default 80% */ @property (nonatomic, assign) CGFloat highLoadThreshold; /** Only dump StackFrame of the thread when it's CPU usage exceeding the threshold while sampling. default 15% */ @property (nonatomic, assign) CGFloat stackFramesDumpThreshold; /** Only generate record when the high load lasting longer than limit. default 60 seconds. */ @property (nonatomic, assign) CGFloat highLoadLastingLimit; + (instancetype)shareInstance; - (void)addDelegate:(id<MTHCPUTracingDelegate>)delegate; - (void)removeDelegate:(id<MTHCPUTracingDelegate>)delegate; - (void)startTracing; - (void)stopTracing; - (BOOL)isTracing; @end /****************************************************************************/ #pragma mark - @protocol MTHCPUTracingDelegate <NSObject> - (void)cpuHighLoadRecordStartAt:(NSTimeInterval)startAt didUpdateStackFrameSample:(MTH_CPUTraceStackFramesNode *)stackframeRootNode averageCPUUsage:(CGFloat)averageCPUUsage lastingTime:(CGFloat)lastingTime; - (void)cpuHighLoadRecordDidEnd; @end <|start_filename|>MTHawkeyeDemo/MTHawkeyeDemo/MemoryDemo/MTImagePicker/MTPhotoDetailViewController.h<|end_filename|> // // MTPhotoDetailViewController.h // MTHawkeyeDemo // // Created by EuanC on 10/07/2017. // Copyright © 2017 Meitu. All rights reserved. // #import <UIKit/UIKit.h> @interface MTPhotoDetailViewController : UIViewController @end <|start_filename|>MTHawkeyeDemo/MTHawkeyeDemo/MemoryDemo/ReusePropertyTestViewController.h<|end_filename|> // // ReusePropertyTestViewController.h // MTHawkeyeDemo // // Created by EuanC on 04/08/2017. // Copyright © 2017 Meitu. All rights reserved. // #import <UIKit/UIKit.h> @class ANormalViewModel; /** vc 持有一个在 vc 创建之前就已经存在的属性,检测到第二次后,应该断定为共享对象 */ @interface ReusePropertyTestViewController : UIViewController @property (nonatomic, strong) ANormalViewModel *viewModel; @property (nonatomic, strong) ANormalViewModel *sharedViewModel; @property (nonatomic, strong) ANormalViewModel *existMainViewModel; @end <|start_filename|>MTHawkeyeDemo/MTHawkeyeDemo/GraphicsDemo/GraphicsDemoViewController.h<|end_filename|> // // GraphicsDemoViewController.h // MTHawkeyeDemo // // Created by EuanC on 2019/3/7. // Copyright © 2019 Meitu. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface GraphicsDemoViewController : UIViewController @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/MemoryPlugins/Allocations/HawkeyeCore/MTHawkeyeUserDefaults+Allocations.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/17 // Created by: EuanC // #import "MTHawkeyeUserDefaults.h" NS_ASSUME_NONNULL_BEGIN @interface MTHawkeyeUserDefaults (Allocations) @property (nonatomic, assign) BOOL allocationsTraceOn; /**< 监控通过内存分配记录及堆栈 */ @property (nonatomic, assign) size_t mallocReportThresholdInBytes; /**< 读取内存分配记录时,输出 malloc 报告的阈值 */ @property (nonatomic, assign) size_t vmAllocateReportThresholdInBytes; /**< 读取内存分配记录时,输出 vmallocation/mmap 报告的阈值 */ @property (nonatomic, assign) uint32_t reportCategoryElementCountThreshold; /**< limit the category summary report, default 0 */ @property (nonatomic, assign) BOOL chunkMallocTraceOn; /**< 单次大块内存分配监控 */ @property (nonatomic, assign) size_t chunkMallocThresholdInBytes; /**< 单次大块内存分配监控阈值 */ @property (nonatomic, assign) BOOL isStackLogNeedSysFrame; /**< 堆栈记录时,是否记录非 App 帧 */ @property (nonatomic, assign) size_t maxStackRecordDepth; /**< 记录堆栈的最深深度,默认 50 */ @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/NetworkPlugins/Inspect/Core/MTHNetworkTaskInspectionBandwidth.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 25/08/2017 // Created by: EuanC // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @class MTHNetworkTaskInspection; extern NSString *kkMTHNetworkTaskAdviceKeyDuplicatedRequestIndexList; /** Bandwidth Inpsection 主要用于侦测带宽相关的优化项 */ @interface MTHNetworkTaskInspectionBandwidth : NSObject /** Detecting if response body is compressed 建议检查 HTTP Request Header 看是否已正确配置 Accept-Encoding 然后检查后端是否配置正常,请求正常的话服务端返回头应包含预期的 Content-Type */ + (MTHNetworkTaskInspection *)responseContentEncodingInspection; /** Detecting duplicate network transactions 建议将一些网络请求直接缓存到本地,减少后续的请求次数; 如果是需要及时刷新的数据,建议使用 HTTP Cache-Control 来减少数据未更新时返回数据包的大小 */ + (MTHNetworkTaskInspection *)duplicateRequestInspection; /** Detecting image size and quality for optimized web requests (not available yet) 建议在不同网络环境下使用不同质量的图片 建议使用压缩比更高的图片格式 (如 webp) */ + (MTHNetworkTaskInspection *)responseImagePayloadInspection; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/NetworkPlugins/Inspect/Core/MTHNetworkTaskInspectResults.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 08/09/2017 // Created by: EuanC // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @class MTHNetworkTaskAdvice; @class MTHNetworkTaskInspectionsGroup; @class MTHNetworkTaskInspectionWithResult; @class MTHNetworkTaskInspection; @interface MTHNetworkTaskInspectResults : NSObject @property (nonatomic, copy, readonly) NSArray<MTHNetworkTaskInspectionsGroup *> *groups; - (void)updateGroupsInfoWithInspections:(NSArray<MTHNetworkTaskInspection *> *)inspections; - (void)updateResultsAsInspection:(MTHNetworkTaskInspection *)inspection inspectedAdvices:(NSArray<MTHNetworkTaskAdvice *> *)advices; - (void)updateInspectedAdvices:(NSArray<MTHNetworkTaskAdvice *> *)advices groupName:(NSString *)groupId typeName:(NSString *)name; @end @interface MTHNetworkTaskInspectionsGroup : NSObject @property (nonatomic, copy) NSString *name; @property (nonatomic, copy, readonly) NSArray<MTHNetworkTaskInspectionWithResult *> *inspections; @end @interface MTHNetworkTaskInspectionWithResult : NSObject @property (nonatomic, copy, readonly) NSString *name; @property (nonatomic, strong, readonly) MTHNetworkTaskInspection *inspection; @property (nonatomic, copy, readonly) NSArray<MTHNetworkTaskAdvice *> *advices; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/NetworkPlugins/HawkeyeUI/MTHNetworkTransactionAdviceDetailViewModel.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2017/9/5 // Created by: 潘名扬 // #import <Foundation/Foundation.h> #import "MTHNetworkWaterfallViewController.h" NS_ASSUME_NONNULL_BEGIN @class MTHNetworkTransaction; @interface MTHNetworkTransactionAdviceDetailViewModel : NSObject <MTHNetworkWaterfallDataSource> // 当前聚焦的网络请求记录下标 @property (nonatomic, assign) NSInteger requestIndexFocusOnCurrently; // 当前显示的关联网络请求记录下标数组,包含聚焦的请求 @property (nonatomic, copy, readonly) NSArray<NSNumber *> *currentOnViewIndexArray; @property (nonatomic, assign) NSTimeInterval timelineStartAt; // 当前关注的 timeline 的起始时间 @property (nonatomic, assign) NSTimeInterval timelineDuration; // 当前关注的 timeline 总时长 - (instancetype)initWithRequestIndex:(NSInteger)index relatedRequestIndexes:(NSIndexSet *)indexes; - (MTHNetworkTransaction *)transactionFromRequestIndex:(NSInteger)requestIndex; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeyeDemo/MTHawkeyeDemo/ViewController.h<|end_filename|> // // ViewController.h // MTHawkeyeDemo // // Created by cqh on 18/05/2017. // Copyright © 2017 Meitu. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UITableViewController @end <|start_filename|>MTHawkeye/UISkeleton/MTHawkeyeSettingViewController.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/14 // Created by: EuanC // #import <UIKit/UIKit.h> #import "MTHawkeyeSettingTableEntity.h" NS_ASSUME_NONNULL_BEGIN @protocol MTHawkeyeSettingViewControllerDelegate; @interface MTHawkeyeSettingViewController : UITableViewController //- (instancetype)initWithDelegate:(id<MTHawkeyeSettingViewControllerDelegate>)delegate; - (instancetype)initWithTitle:(NSString *)title viewModelEntity:(MTHawkeyeSettingTableEntity *)entity; @end @protocol MTHawkeyeSettingViewControllerDelegate <NSObject> - (NSInteger)numberOfSettingPlugins; - (MTHawkeyeSettingSectionEntity *)settingPluginAtSectionIndex:(NSInteger)index; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/Core/MTHawkeyeClient.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/4 // Created by: EuanC // #import <Foundation/Foundation.h> #import "MTHawkeyePlugin.h" #import "MTHawkeyeUserDefaults.h" NS_ASSUME_NONNULL_BEGIN typedef void (^MTHawkeyeClientPluginsSetupHandler)(NSMutableArray<id<MTHawkeyePlugin>> *pluginsToAdd); typedef void (^MTHawkeyeClientPluginsCleanHandler)(NSMutableArray<id<MTHawkeyePlugin>> *pluginsAdded); @interface MTHawkeyeClient : NSObject + (instancetype)shared; /** plugins setup and cleaner @param pluginsSetupHandler pluginsSetupHandler will be called while `startServer` invoked. the initial plugin array is empty, after the block, the added plugins will be used to setup client, you can add your own plugins into the array here. @param pluginsCleanHandler pluginsCleanHandler will be called while `stopServer` invoked. the plugin array item will be remove internal after stop, you can do cleanup if you've retain the plugins external. */ - (void)setPluginsSetupHandler:(MTHawkeyeClientPluginsSetupHandler)pluginsSetupHandler pluginsCleanHandler:(MTHawkeyeClientPluginsCleanHandler)pluginsCleanHandler; /** start hawkeye client server, and trigger `hawkeyeClientDidStart` in all plugins. */ - (void)startServer; - (void)stopServer; /** manual call `addPlugin` after startServer will not invoke `hawkeyeClientDidStart` */ - (void)addPlugin:(id<MTHawkeyePlugin>)plugin; - (void)removePlugin:(id<MTHawkeyePlugin>)plugin; - (nullable id<MTHawkeyePlugin>)pluginFromID:(NSString *)pluginID; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/NetworkPlugins/Inspect/Core/MTHNetworkTaskInspector.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 24/08/2017 // Created by: EuanC // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @class MTHNetworkTaskInspection; @class MTHNetworkTaskInspectorContext; @class MTHNetworkTaskInspectResults; @class MTHNetworkTransaction; @class MTHNetworkRecorder; @class MTHNetworkTaskAdvice; @protocol MTHNetworkInspectInfoDelegate <NSObject> - (void)requestCacheNetworkInspectResult:(NSDictionary *)inspectResultDic withKey:(NSString *)key; - (NSDictionary *)existNetworkInspectResultsCache; @end @interface MTHNetworkTaskInspector : NSObject /** 网络任务侦测项列表,需要关闭内置的侦测项时,可遍历找到对应项,将 enabled 置为 NO. */ @property (nonatomic, copy, readonly) NSArray<MTHNetworkTaskInspection *> *inspections; // IMPROVE: context 不应该由外部去更新,由内部处理 @property (nonatomic, strong, readonly) MTHNetworkTaskInspectorContext *context; @property (nonatomic, strong, readonly) MTHNetworkTaskInspectResults *inspectResults; @property (nonatomic, weak) id<MTHNetworkInspectInfoDelegate> storageDelegate; /** 可设置此域名黑名单,来过滤一些第三方 sdk 的网络请求侦测 host 匹配规则为后半段部分匹配: [transaction.request.URL.host hasSuffix:host] */ @property (nonatomic, copy) NSArray<NSString *> *hostBlackList; + (instancetype)shared; + (void)setEnabled:(BOOL)enabled; + (BOOL)isEnabled; /** 上层可调用此方法增加自己的策略,策略的实现可查看 `MTHNetworkTaskInspectionScheduling` 等类; 需要关闭某一侦测项时,现在暂不提供显示的方法。上层可遍历本类的 `inspections` 属性,找到对应的侦测项 将 enabled 置为 NO,即可关闭对应的侦测。 */ - (void)addInspection:(MTHNetworkTaskInspection *)inspection; /** 侦测传入的网络请求是否存在问题 使用已加入的 inspections 作为侦测器 */ - (void)inspectTransactions:(NSArray<MTHNetworkTransaction *> *)transactions completionHandler:(void (^)(NSDictionary<NSString *, NSArray<MTHNetworkTaskAdvice *> *> *))completionHandler; - (void)releaseNetworkTaskInspectorElement; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/Utils/MTHawkeyeDyldImagesUtils.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/10/30 // Created by: EuanC // #import <Foundation/Foundation.h> #include <mach/vm_types.h> #include <stdbool.h> NS_ASSUME_NONNULL_BEGIN #ifdef __cplusplus extern "C" { #endif /** cache dyld images info to filepath. */ void mtha_setup_dyld_images_dumper_with_path(NSString *filepath); /** detect if the given frame address is a system libraries method. */ boolean_t mtha_addr_is_in_sys_libraries(vm_address_t address); /** check if the given symbol address is within the interval of all dyld images. */ boolean_t mtha_symbol_addr_check_basic(vm_address_t address); /****************************************************************************/ #pragma mark - boolean_t mtha_start_dyld_restore(NSString *cachedDyldImages); uint64_t mtha_dyld_restore_address(uint64_t org_address); void mtha_end_dyld_restore(void); NS_ASSUME_NONNULL_END #ifdef __cplusplus } #endif <|start_filename|>MTHawkeyeDemo/MTHawkeyeDemo/MemoryDemo/SharedInstanceExample.h<|end_filename|> // // SharedInstanceExample.h // MTHawkeyeDemo // // Created by EuanC on 03/08/2017. // Copyright © 2017 Meitu. All rights reserved. // #import <Foundation/Foundation.h> @interface SharedInstanceExample : NSObject + (instancetype)shared; + (void)staticFuncWithParam:(id)obj; @end <|start_filename|>MTHawkeye/UISkeleton/Toast/MTHToastView.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 07/06/2018 // Created by: Huni // #import <UIKit/UIKit.h> #import "MTHToastViewMaker.h" #import "UIButton+MTHBlocks.h" typedef void (^MTHToastViewBlock)(void); @interface MTHToastView : UIView @property (copy, nonatomic) MTHToastViewBlock hiddenBlock; @property (copy, nonatomic) MTHToastViewBlock clickedBlock; + (instancetype)toastViewFrom:(void (^)(MTHToastViewMaker *make))block; - (void)showToastView; - (void)hideToastView; - (void)setupLeftButtonWithTitle:(NSString *)title andEvent:(MTHToastButtonActionBlock)event; - (void)setupRightButtonWithTitle:(NSString *)title andEvent:(MTHToastButtonActionBlock)event; - (void)pauseTimer; - (void)startTimer; @end <|start_filename|>MTHawkeye/MemoryPlugins/Allocations/HawkeyeUI/MTHAllocationsSettingEntity.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/18 // Created by: EuanC // #import <Foundation/Foundation.h> #import "MTHawkeyeSettingTableEntity.h" NS_ASSUME_NONNULL_BEGIN @interface MTHAllocationsSettingEntity : NSObject + (MTHawkeyeSettingSwitcherCellEntity *)loggerSwitcherCell; + (MTHawkeyeSettingSwitcherCellEntity *)includeSystemFrameSwitcherCell; + (MTHawkeyeSettingEditorCellEntity *)mallocReportThresholdEditorCell; + (MTHawkeyeSettingEditorCellEntity *)vmReportThresholdEditorCell; + (MTHawkeyeSettingEditorCellEntity *)reportCategoryElementCountThresholdEditorCell; + (MTHawkeyeSettingSwitcherCellEntity *)singleChunkMallocSwitcherCell; + (MTHawkeyeSettingEditorCellEntity *)chunkMallocThresholdEditorCell; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeyeDemo/MTHawkeyeDemo/MemoryDemo/FacebookProjects/FacebookProjectViewController.h<|end_filename|> // // FacebookProjectViewController.h // MTHawkeyeDemo // // Created by cqh on 29/06/2017. // Copyright © 2017 meitu. All rights reserved. // #import <UIKit/UIKit.h> @interface FacebookProjectViewController : UIViewController - (instancetype)initWithName:(NSString *)name URL:(NSURL *)url; @end <|start_filename|>MTHawkeye/GraphicsPlugins/OpenGLTrace/HawkeyeCore/MTHawkeyeUserDefaults+OpenGLTrace.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/22 // Created by: EuanC // #import "MTHawkeyeUserDefaults.h" NS_ASSUME_NONNULL_BEGIN @interface MTHawkeyeUserDefaults (OpenGLTrace) /** GLTrace Switch. If YES, Hook GLFunctions, otherwise do nothing. */ @property (nonatomic, assign) BOOL openGLTraceOn; /** Default NO. Only dectect and calculate GL Resources(Texture, Framebuffer, Buffer...) Size. If YES, OpenGLTrace will do analyse GLFunction invoked (Check current context exist, GLGetError, Four-Type-Wrong-Using...) [opengl-debugger.md see more] */ @property (nonatomic, assign) BOOL openGLTraceAnalysisOn; /** Default NO, when openGLTraceAnalysisOn is set on, change to YES default. If some error occur, OpenGLTrace will throw exception in Hawkeye. Otherwise you should implement MTHOpenGLTraceDelegate protocal to process GL error. */ @property (nonatomic, assign) BOOL openGLTraceRaiseExceptionOn; /** Default state depends on openGLTraceOn. */ @property (nonatomic, assign) BOOL openGLTraceShowGPUMemoryOn; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/NetworkPlugins/Inspect/Core/MTHNetworkTaskInspectionLatency.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 25/08/2017 // Created by: EuanC // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @class MTHNetworkTaskInspection; /** Latency Inspection 主要用于首包时间优化相关项 - 启动 20s 之后的网络请求,包含 dns 时长占比超过 1/3 的请求 (域名收编) - 重定向请求最后一阶段外的时间 t 占总时长 1/2 以上 - 重定向请求第一阶段之后包含了 dns/conn 时间 - http keep-alive 关闭 - 并发的网络请求,包含多个 host,且出现并发的 tcp 握手 (0.5d) - 包含 tcp 握手的连接,往前十秒内有可复用的同类 host (0.5d) - 总的请求使用的域名数超过5个,建议收敛域名 */ @interface MTHNetworkTaskInspectionLatency : NSObject /** Detecting DNS connection time 策略: 总体时长 > 300ms & dns 时间占比 > 1/3 建议: 使用 MTFastDNS 或类似方案减少 DNS 耗时 如果是链路复用问题,建议收敛域名 如果未使用 HTTP 2.0,建议升级到 HTTP 2.0 提升连接复用率 */ + (MTHNetworkTaskInspection *)dnsCostInspection; /** Detecting HTTP too much extra time cost cause of redirects 策略1: 总体时长 > 300ms & 重定向时间最后一段之外的时间占时长 > 1/2 策略2: 总体时长 > 300ms & 重定向第一段之后包含了 dns/tcp connection 耗时 建议: 如果重定向包含了不同的域名,建议收敛为同一域名,减少可能发生的 dns, tcp connection 耗时 尽量减少不必要的 HTTP 重定向,移动网络环境下 HTTP 重定向会大幅提高请求延时。 */ + (MTHNetworkTaskInspection *)redirectRequestInspection; /** Detecting HTTP keep-alive not used 建议无特殊原因,不要关闭 keep-alive */ + (MTHNetworkTaskInspection *)httpKeepAliveInspection; /** Detecting use too many second-level domains 策略: 主域名下使用了过多的二级域名 > 3 建议: 使用的域名数过多,建议收敛域名。以减少可能的 dns, tcp connection 耗时 如果未使用 HTTP 2.0,建议升级到 HTTP 2.0 提升连接复用率 */ + (MTHNetworkTaskInspection *)tooManyHostInspection; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/StorageMonitorPlugins/DirectoryWatcher/HawkeyeCore/MTHDirectoryTree.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/121/14 // Created by: David.Dai // #import <Foundation/Foundation.h> #define MTHDirectoryTreeDocument @"Documents" #define MTHDirectoryTreeCaches @"Library/Caches" #define MTHDirectoryTreePreferences @"Library/Preferences" #define MTHDirectoryTreeTmp @"tmp" NS_ASSUME_NONNULL_BEGIN @interface MTHDirectoryTree : NSObject @property (nonatomic, copy, readonly) NSString *relativePath; @property (nonatomic, copy, readonly) NSString *absolutePath; @property (nonatomic, copy, readonly) NSString *name; @property (nonatomic, copy, readonly) NSArray<MTHDirectoryTree *> *childTree; - (instancetype)initWithRelativePath:(NSString *)path; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/NetworkPlugins/HawkeyeUI/MTHNetworkTaskInspectAdvicesViewController.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 09/09/2017 // Created by: EuanC // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @class MTHNetworkTaskInspectionWithResult; @class MTHNetworkTaskAdvice; @interface MTHNetworkTaskInspectAdvicesViewController : UITableViewController - (instancetype)initWithTaskInspectionResult:(MTHNetworkTaskInspectionWithResult *)inspectionResult advicesForTransactions:(NSDictionary<NSString *, NSArray<MTHNetworkTaskAdvice *> *> *)advicesDict; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/MemoryPlugins/Allocations/Core/mtha_allocate_record_output.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/10/17 // Created by: EuanC // #ifndef mtha_report_output_h #define mtha_report_output_h #include <stdio.h> #include "mtha_allocate_record_reader.h" #import <Foundation/Foundation.h> namespace MTHAllocation { class RecordOutput { public: RecordOutput(AllocateRecords &allocateRecords, mtha_backtrace_uniquing_table *stackRecords, uint32_t categoryElementCountThreshold = 0) : _stackRecords(stackRecords) , _categoryElementCountThreshold(categoryElementCountThreshold) { _allocationRecords = &allocateRecords; }; ~RecordOutput(); void flushReportToConsoleFormatInLine(uint32_t thresholdInBytes); void flushReportToFileFormatInLine(uint32_t thresholdInBytes, NSString *filePath); /** @param dyldImagesInfoFile Only need for history session report. */ void flushReportToFileFormatInJson(uint32_t thresholdInBytes, NSString *reportFilePath, NSString *dyldImagesInfoFile); private: AllocateRecords *_allocationRecords = NULL; mtha_backtrace_uniquing_table *_stackRecords = NULL; uint32_t _categoryElementCountThreshold = 0; /**< only when the category element count exceed the limit, output to report */ private: RecordOutput(const RecordOutput &); RecordOutput &operator=(const RecordOutput &); }; } #endif /* mtha_report_output_h */ <|start_filename|>MTHawkeye/MemoryPlugins/Allocations/Core/mtha_locking.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/7/19 // Created by: EuanC // #ifndef mtha_locking_h #define mtha_locking_h #include <libkern/OSAtomic.h> #include <os/lock.h> #include <pthread/pthread.h> #if 0 // only available in the furture typedef os_unfair_lock _malloc_lock_s; #define _MALLOC_LOCK_INIT OS_UNFAIR_LOCK_INIT __attribute__((always_inline)) static inline void _malloc_lock_init(_malloc_lock_s *lock) { *lock = OS_UNFAIR_LOCK_INIT; } __attribute__((always_inline)) static inline void _malloc_lock_lock(_malloc_lock_s *lock) { return os_unfair_lock_lock(lock); } __attribute__((always_inline)) static inline bool _malloc_lock_trylock(_malloc_lock_s *lock) { return os_unfair_lock_trylock(lock); } __attribute__((always_inline)) static inline void _malloc_lock_unlock(_malloc_lock_s *lock) { return os_unfair_lock_unlock(lock); } // use pthread_mutex_ under iOS 10.0 #else typedef pthread_mutex_t _malloc_lock_s; #define _MALLOC_LOCK_INIT PTHREAD_MUTEX_INITIALIZER __attribute__((always_inline)) static inline void _malloc_lock_init(_malloc_lock_s *lock) { _malloc_lock_s _os_lock_handoff_init; pthread_mutex_init(&_os_lock_handoff_init, NULL); *lock = _os_lock_handoff_init; } __attribute__((always_inline)) static inline int _malloc_lock_lock(_malloc_lock_s *lock) { return pthread_mutex_lock(lock); } __attribute__((always_inline)) static inline int _malloc_lock_trylock(_malloc_lock_s *lock) { return pthread_mutex_trylock(lock); } __attribute__((always_inline)) static inline int _malloc_lock_unlock(_malloc_lock_s *lock) { return pthread_mutex_unlock(lock); } #endif // //////////////////////////////////////// /// MARK: - #if defined(__i386__) || defined(__x86_64__) #if defined(__has_attribute) #if __has_attribute(address_space) #define OS_GS_RELATIVE __attribute__((address_space(256))) #endif #endif #ifdef OS_GS_RELATIVE #define _os_tsd_get_base() ((void *OS_GS_RELATIVE *)0) #else __attribute__((always_inline)) __inline__ void * _os_tsd_get_direct(unsigned long slot) { void *ret; __asm__("mov %%gs:%1, %0" : "=r"(ret) : "m"(*(void **)(slot * sizeof(void *)))); return ret; } __attribute__((always_inline)) __inline__ int _os_tsd_set_direct(unsigned long slot, void *val) { #if defined(__i386__) && defined(__PIC__) __asm__("movl %1, %%gs:%0" : "=m"(*(void **)(slot * sizeof(void *))) : "rn"(val)); #elif defined(__i386__) && !defined(__PIC__) __asm__("movl %1, %%gs:%0" : "=m"(*(void **)(slot * sizeof(void *))) : "ri"(val)); #else __asm__("movq %1, %%gs:%0" : "=m"(*(void **)(slot * sizeof(void *))) : "rn"(val)); #endif return 0; } #endif #elif defined(__arm__) || defined(__arm64__) __attribute__((always_inline, pure)) static __inline__ void ** _os_tsd_get_base(void) { #if defined(__arm__) && defined(_ARM_ARCH_6) uintptr_t tsd; __asm__("mrc p15, 0, %0, c13, c0, 3" : "=r"(tsd)); tsd &= ~0x3ul; /* lower 2-bits contain CPU number */ #elif defined(__arm__) && defined(_ARM_ARCH_5) register uintptr_t tsd asm("r9"); #elif defined(__arm64__) uint64_t tsd; __asm__("mrs %0, TPIDRRO_EL0" : "=r"(tsd)); tsd &= ~0x7ull; #endif return (void **)(uintptr_t)tsd; } #define _os_tsd_get_base() _os_tsd_get_base() #else #error _os_tsd_get_base not implemented on this architecture #endif #ifdef _os_tsd_get_base __attribute__((always_inline)) __inline__ void * _os_tsd_get_direct(unsigned long slot) { return _os_tsd_get_base()[slot]; } __attribute__((always_inline)) __inline__ int _os_tsd_set_direct(unsigned long slot, void *val) { _os_tsd_get_base()[slot] = val; return 0; } #endif #endif /* mtha_locking_h */ <|start_filename|>MTHawkeye/NetworkPlugins/Inspect/Core/MTHNetworkTaskInspectionAPIUsage.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 25/08/2017 // Created by: EuanC // #import "MTHNetworkTaskInspection.h" NS_ASSUME_NONNULL_BEGIN @class MTHNetworkTaskInspection; /** API Usage Inspection 主要用于侦测 API 使用上的一些建议 */ @interface MTHNetworkTaskInspectionAPIUsage : NSObject /** Detecting URL creation result is nil eg: NSURL *url = [NSURL URLWithString:@" http://www.host.com"]; NSURL *url = [NSURL URLWithString:@"http://www.host.com?中文"]; 会返回 nil,直接拿这个去请求网络会失败。 Hook NSURL 的 Designed 创建方法,用于记录可能的 URL 失败错误。默认开启 */ + (MTHNetworkTaskInspection *)nilNSURLInspection; /** Detecting URL exceptions for the request 侦测 url 异常的情况(bad, unsupport) 的请求.(后续需要增加记录原始 urlstring,方便排查) */ + (MTHNetworkTaskInspection *)unexpectedURLRequestInspection; /** Detecting the use of deprecated NSURLConnection API NSURLSession 通过共享 session 来复用可用的 tcp 连接,减少了网络请求连接延时时间。 同时,NSURLSession 开始支持了 HTTP 2.0 协议,而启用 HTTP 2.0 更有利于做后续的网络优化操作。 */ + (MTHNetworkTaskInspection *)deprecatedURLConnectionInspection; /** Detecting has not yet use HTTP/2 HTTP 2.0 优势 - HTTP/2 同一 host 下有多个请求并发时,只创建了一个 tcp 连接。同场景下相比 HTTP/1.1 减少了多路 tcp 连接的耗时。 - HTTP/2 采用二进制协议,为流量控制、优先级、server push 提供了基础 - HTTP/2 支持多路复用,HTTP/1.0 中一个连接只能有一个请求,HTTP/1.1 中一个连接同时可以有多个请求,但一次只能有一个响应,会造成 Head-of-line Blocking 问题,HTTP/2 则可以多路复用,解决 Head-of-line Blocking 的问题。 - HTTP/2 使用 HPACK 格式压缩头部,减少了传输包的大小 - HTTP/2 可以设置请求的优先级,HTTP/1.1 只能按照进入的先后顺序 - HTTP/2 支持服务器 push 操作,可以减少一些场景下的来回路程耗时 ref: https://github.com/creeperyang/blog/issues/23 HTTP2 简介及基于 HTTP2 的 Web 前端优化 */ + (MTHNetworkTaskInspection *)preferHTTP2Inspection; /** Detecting the use of default timeout - 不同网络状况下,建议使用不同的 timeoutIntervalForRequest 超时策略(默认 60s) (poor: 30s, moderate: 15s, good: 8s, excellent: 5s) - 不同包大小&网络状况下,考虑使用不同的 timeoutIntervalForResource 超时策略(默认一周) 建议: timeoutIntervalForRequest 为两个数据包之间的最大时间间隔,在正常情况下,我们可以设置一个相对合理的超时时间来更快侦测到网络不可用的状态。 因为不同网络连接质量下,情况不同,建议最高设置为 30s,即连续 30s 没有收到下一个包则置为请求超时。 如果有侦测网络质量,建议做区分 (unknown/poor: 30s, moderate: 15s, good: 8s, excellent: 5s) 具体分档见 MTHNetworkStat.h 注意: NSURLRequest & NSURLSessionConfiguration 同时设置的情况下将会取更激进的策略 (存疑,待确认) timeoutIntervalForResource 为整个任务(上传/下载)的最长完成时间,默认值为1周。因跟包大小和排队时间相关,目前没有具体建议值。 */ + (MTHNetworkTaskInspection *)timeoutConfigInspection; /** Detecting improper use of NSURLSessionTask 侦测多个同一类型的 task 没有使用同一 Session 管理 同一 host 下,尽量使用同一 session 来管理所有请求 task,以复用网络连接 */ + (MTHNetworkTaskInspection *)urlSessionTaskManageInspection; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/Core/MTHawkeyePlugin.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/3 // Created by: EuanC // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN /** The protocol of a Hawkeye client plugin. Once you have a new or exist module and wanna add it as Hawkeye client plugin, you should implement a adaptor that following MTHawkeyePlugin. you can see class `MTHNetworkMonitorHawkeyeAdaptor` as an example. */ @protocol MTHawkeyePlugin <NSObject> @required /** Plugin Identity, should be different with other plugins. */ + (NSString *)pluginID; /** will triggered when Hawkeye client did start. */ - (void)hawkeyeClientDidStart; /** will triggered when Hawkeye client did stop. */ - (void)hawkeyeClientDidStop; @optional /** will triggered when Hawkeye client status flush timer fired. */ - (void)receivedFlushStatusCommand; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/StorageMonitorPlugins/DirectoryWatcher/HawkeyeUI/MTHDirectoryWatcherSelctionTableViewCell.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/121/18 // Created by: David.Dai // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface MTHDirectoryWatcherSelctionTableViewCell : UITableViewCell @property (nonatomic, assign) BOOL isWatching; @property (nonatomic, strong) NSString *path; @property (nonatomic, assign) BOOL haveChild; @property (nonatomic, copy) dispatch_block_t switchBlock; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/MemoryPlugins/LivingObjectSniffer/Core/MTHLivingObjectInfo.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/10 // Created by: EuanC // #import <Foundation/Foundation.h> #import "MTHLivingObjectShadow.h" NS_ASSUME_NONNULL_BEGIN /** living instance info. when instance released, the property instance will be nil. */ @interface MTHLivingObjectInfo : NSObject @property (nonatomic, readonly, weak, nullable) id instance; @property (nonatomic, readonly) NSString *preHolderName; @property (nonatomic, readonly) NSTimeInterval recordTime; @property (nonatomic, readonly) BOOL theHodlerIsNotOwner; @property (nonatomic, readonly) BOOL isSingleton; @end /** Group living instance by class. (for assemble and storage). */ @interface MTHLivingObjectGroupInClass : NSObject @property (nonatomic, copy, readonly) NSString *className; @property (nonatomic, readonly) NSArray<MTHLivingObjectInfo *> *aliveInstances; @property (nonatomic, assign) NSInteger detectedCount; @property (nonatomic, assign) NSInteger aliveInstanceCount; - (void)addMayLeakedInstance:(MTHLivingObjectShadow *)objShadow completion:(void (^)(MTHLivingObjectInfo *theAliveInstance))completion; @end /** Group living instance by shadow cast action. (for viewing) */ @interface MTHLivingObjectGroupInTrigger : NSObject @property (nonatomic, strong) MTHLivingObjectShadowTrigger *trigger; @property (nonatomic, copy) NSArray<MTHLivingObjectInfo *> *detectedInstances; @property (nonatomic, assign) NSInteger aliveInstanceCount; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/MemoryPlugins/Allocations/Core/MTHAHistoryRecordReader.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/11/13 // Created by: EuanC // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface MTHAHistoryRecordReader : NSObject @property (nonatomic, copy, class, readonly) NSString *mallocReportFileName; @property (nonatomic, copy, class, readonly) NSString *vmReportFileName; - (instancetype)initWithRecordDir:(NSString *)rootDir; /** Read record from persistance files, then generate report and save to files. while generate malloc report, only record size exceed `mallocReportThresholdInBytes` will be counted. whild generate vm report, only record size exceed `vmReportThresholdInBytes` will be counted. ( ./malloc_records + ./stacks ) => ./malloc_report ( ./vm_records + ./stacks ) => ./vm_report */ - (void)generateReportWithMallocThresholdInBytes:(NSInteger)mallocReportThresholdInBytes vmThresholdInBytes:(NSInteger)vmReportThresholdInBytes; - (NSString *)mallocReportContent; - (NSString *)vmReportContent; - (NSString *)dyldImagesContent; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/MemoryPlugins/Allocations/Core/mtha_backtrace_uniquing_table.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/7/27 // Created by: EuanC // #ifndef mtha_backtrace_uniquing_table_h #define mtha_backtrace_uniquing_table_h #include <mach/mach.h> #include <stdbool.h> #include <stdio.h> #define MTH_ALLOCATIONS_DEBUG 0 #ifdef __cplusplus extern "C" { #endif // The expansion factor controls the shifting up of table size. A factor of 1 will double the size upon expanding, // 2 will quadruple the size, etc. Maintaining a 66% fill in an ideal table requires the collision allowance to // increase by 3 for every quadrupling of the table size (although this the constant applied to insertion // performance O(c*n)) #define MTHA_VM_EXPAND_FACTOR 1 #define MTHA_VM_COLLISION_GROWTH_RATE 3 // For a uniquing table, the useful node size is slots := floor(table_byte_size / (2 * sizeof(vm_address_t))) // Some useful numbers for the initial max collision value (desiring 66% fill): // 16K-23K slots -> 16 collisions // 24K-31K slots -> 17 collisions // 32K-47K slots -> 18 collisions // 48K-79K slots -> 19 collisions // 80K-96K slots -> 20 collisions #define MTHA_VM_INITIAL_MAX_COLLIDE 20 #define MTHA_VM_DEFAULT_UNIQUING_PAGE_SIZE_WITH_SYS 1024 // memory cost: pages * vm_page_size(16386); default: 16MB #define MTHA_VM_DEFAULT_UNIQUING_PAGE_SIZE_WITHOUT_SYS 256 // memory cost: pages * vm_page_size(16386); default: 4MB const uint64_t mtha_vm_invalid_stack_id = (uint64_t)(-1ll); // backtrace uniquing table chunks used in client-side stack log reading code, // in case we can't read the whole table in one mach_vm_read() call. typedef struct _mtha_table_chunk_header { uint64_t num_nodes_in_chunk; uint64_t table_chunk_size; vm_address_t *table_chunk; struct _mtha_table_chunk_header *next_table_chunk_header; } mtha_table_chunk_header_t; #pragma pack(push, 4) typedef struct _mtha_backtrace_uniquing_table { FILE *mmap_fp; // mmap file descriptor uint32_t fileSize; // mmap file size uint32_t numPages; // number of pages of the table uint32_t numNodes; uint32_t tableSize; uint32_t untouchableNodes; vm_address_t table_address; int32_t max_collide; // 'table_address' is just an always 64-bit version of the pointer-sized 'table' field to remotely read; // it's important that the offset of 'table_address' in the struct does not change between 32 and 64-bit. #if MTH_ALLOCATIONS_DEBUG uint64_t nodesFull; uint64_t backtracesContained; #endif uint64_t max_table_size; bool in_client_process : 1; union { vm_address_t *table; // in "target" process; allocated using vm_allocate() mtha_table_chunk_header_t *first_table_chunk_hdr; // in analysis process } u; } mtha_backtrace_uniquing_table; #pragma pack(pop) typedef vm_address_t mtha_slot_address; typedef uint32_t mtha_slot_parent; typedef uint32_t mtha_table_slot_index; #pragma pack(push, 4) typedef struct { union { struct { uint32_t slot0; uint32_t slot1; } slots; struct { uint64_t address : 36; uint32_t parent : 28; } normal_slot; }; } mtha_table_slot_t; #pragma pack(pop) _Static_assert(sizeof(mtha_table_slot_t) == 8, "table_slot_t must be 64 bits"); const mtha_slot_parent mtha_slot_no_parent_normal = 0xFFFFFFF; // 28 bits mtha_backtrace_uniquing_table *mtha_create_uniquing_table(const char *filepath, size_t default_page_size); mtha_backtrace_uniquing_table *mtha_read_uniquing_table_from(const char *filepath); void mtha_destroy_uniquing_table(mtha_backtrace_uniquing_table *table); mtha_backtrace_uniquing_table *mtha_expand_uniquing_table(mtha_backtrace_uniquing_table *old_uniquing_table); int mtha_enter_frames_in_table(mtha_backtrace_uniquing_table *uniquing_table, uint64_t *foundIndex, vm_address_t *frames, int32_t count); void mtha_add_new_slot(mtha_table_slot_t *table_slot, vm_address_t address, mtha_table_slot_index parent); void mtha_unwind_stack_from_table_index(mtha_backtrace_uniquing_table *uniquing_table, uint64_t index_pos, vm_address_t *out_frames_buffer, uint32_t *out_frames_count, uint32_t max_frames); #ifdef __cplusplus } #endif #endif /* mtha_backtrace_uniquing_table_h */ <|start_filename|>MTHawkeye/TimeConsumingPlugins/ObjcCallTrace/Core/MTHCallTrace.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 01/11/2017 // Created by: EuanC // #import <Foundation/Foundation.h> extern NSString *const kHawkeyeCalltraceAutoLaunchKey; /**< standardUserDefaults key, 启动时是否在 load 自动开启 CallTrace */ @class MTHCallTraceTimeCostModel; /** 用于 Hook objc_msgSend 方法,如果方法的耗时大于某一阈值,记录到内存里 因目前 hook objc_msgSend 的方式会修改调用堆栈,不建议在需要保留崩溃堆栈的环境中开启 设置下次启动自动开启后,内部的 + load 方法会做开启操作,但因不同类的 load 方法调用顺序依赖于 文件编译顺序、静态库链接顺序,如果要监测所有 App 内的 load 方法耗时,建议新建一个 framework 里面只实现一个 load 方法,调用 [MTHCallTrace startAtOnce] 然后把这个 Framework 放到所有链接库的最前面,保证他的 load 方法会被最早执行 ``` // 以美颜工程为例,在主工程 Target 下新建一个 Framework `Pangu`, 确保在 MYXJ target 的 target dependencies 里有添加了 Pangu 并放在首位 // 然后在 Pangu 里实现任一个类,里面只实现 load 方法,如下 + (void)load { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-performSelector-leaks" // 通过动态库注入版本,配置读取 setting bundle 里的配置信息 Class theClass = NSClassFromString(@"MTHSettingBundlePreference"); if (theClass) { [theClass performSelector:NSSelectorFromString(@"load")]; } // 直接引用的版本, 配置直接使用上一次运行时的配置(保存在 NSUserDefault 里) Class calltraceClass = NSClassFromString(@"MTHCallTrace"); if (calltraceClass) { [calltraceClass performSelector:NSSelectorFromString(@"load")]; } #pragma clang diagnostic pop } ``` */ @interface MTHCallTrace : NSObject /** 设置启动 App 时是否自动开启 CallTrace,重新启动后生效 因目前 CallTrace 会影响断点/崩溃时的调用堆栈可读性,故不建议总是开启 此类目前不提供运行中开启、关闭的方法 */ + (void)setAutoStartAtLaunchEnabled:(BOOL)enabled; + (BOOL)autoStartAtLaunchEnabled; /** 如果要开启 CallTrace,一般建议尽可能早的开始,以便监测包括 load 方法在内的 ObjC 方法耗时 如果上层 App 没有做任何额外的操作,load 方法的加载顺序不可预期,有些 load 方法的耗时监测可能会漏过 上层 App 可添加一个静态链接库(如 MTTheVeryFirst),置顶到所有 framework 之前 在这个库里实现 load 方法,调用本方法 */ + (void)startAtOnce; + (void)disable; + (void)enable; + (BOOL)isRunning; + (void)configureTraceAll; + (void)configureTraceByThreshold; + (void)configureTraceMaxDepth:(NSInteger)depth; // 配置方法调用记录的最大层级 + (void)configureTraceTimeThreshold:(double)timeInMS; // 配置方法调用记录的耗时阈值 + (int)currentTraceMaxDepth; + (double)currentTraceTimeThreshold; // in ms + (NSArray<MTHCallTraceTimeCostModel *> *)records; // 原始排列的数据 + (NSArray<MTHCallTraceTimeCostModel *> *)prettyRecords; // 原始排列的数据,将子节点移为树枝 + (NSArray<MTHCallTraceTimeCostModel *> *)recordsFromIndex:(NSInteger)index; // 原始的排列数据,从偏移位置开始到结尾 @end <|start_filename|>MTHawkeye/UISkeleton/Utils/UITableView+MTHEmptyTips.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/9/11 // Created by: EuanC // #import <UIKit/UIKit.h> @interface UITableView (MTHEmptyTips) - (void)mthawkeye_removeEmptyTipsFooterView; - (void)mthawkeye_setFooterViewWithEmptyTips:(NSString *)tips; - (void)mthawkeye_setFooterViewWithEmptyTips:(NSString *)tips tipsTop:(CGFloat)top; - (void)mthawkeye_setFooterViewWithEmptyTips:(NSString *)tips tipsTop:(CGFloat)tipsTop button:(NSString *)title btnTarget:(id)target btnAction:(SEL)action; @end <|start_filename|>MTHawkeye/NetworkPlugins/HawkeyeUI/MTHNetworkWaterfallViewCellModel.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 18/07/2017 // Created by: EuanC // #import <Foundation/Foundation.h> #import "MTHNetworkTransaction.h" NS_ASSUME_NONNULL_BEGIN @interface MTHNetworkWaterfallViewCellModel : NSObject @property (nonatomic, assign) NSTimeInterval timelineStartAt; // timeline 起始时间 @property (nonatomic, assign) NSTimeInterval timelineDuration; // timeline 总的时间区间 @property (nonatomic, strong) MTHNetworkTransaction *transaction; // 当前 cell 要展示的请求记录 @property (nonatomic, strong) MTHNetworkTransaction *focusedTransaction; // 当前 timeline 选中的请求记录,可能有交叉 @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/UISkeleton/MTHawkeyeFloatingWidgets.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/4 // Created by: EuanC // #import <Foundation/Foundation.h> #import "MTHawkeyeUIPlugin.h" NS_ASSUME_NONNULL_BEGIN @class MTHMonitorViewCell; @protocol MTHawkeyeFloatingWidgetsDataDelegate; @interface MTHawkeyeFloatingWidgets : NSObject @property (nonatomic, weak) id<MTHawkeyeFloatingWidgetsDataDelegate> delegate; @property (readonly) NSMutableArray<id<MTHawkeyeFloatingWidgetPlugin>> *plugins; - (instancetype)initWithWidgets:(NSArray<id<MTHawkeyeFloatingWidgetPlugin>> *)widgets; - (void)addWidget:(id<MTHawkeyeFloatingWidgetPlugin>)widget; - (void)removeWidget:(id<MTHawkeyeFloatingWidgetPlugin>)widget; - (nullable id<MTHawkeyeFloatingWidgetPlugin>)widgetFromID:(NSString *)widgetID; - (void)rebuildDatasource; - (void)receivedFlushStatusCommand; - (NSInteger)floatingWidgetCellCount; - (MTHMonitorViewCell *)floatingWidgetCellAtIndex:(NSUInteger)index; @end @protocol MTHawkeyeFloatingWidgetsDataDelegate <NSObject> - (void)floatingWidgetsUpdated; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/TimeConsumingPlugins/UITimeProfiler/HawkeyeUI/MTHUITimeProfilerResultCallTraceCell.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 07/11/2017 // Created by: EuanC // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @class MTHCallTraceTimeCostModel; @interface MTHUITimeProfilerResultCallTraceCell : UITableViewCell @property (nonatomic, strong) UILabel *timeCostLabel; @property (nonatomic, strong) UILabel *callInfoLabel; @property (nonatomic, strong, nullable) UILabel *subCallInfoLabel; - (void)configureWithCallTraceTimeCostModel:(MTHCallTraceTimeCostModel *)model expanded:(BOOL)expanded; + (CGFloat)heightForCallTraceTimeCostModel:(MTHCallTraceTimeCostModel *)model expanded:(BOOL)expanded; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/MemoryPlugins/Allocations/Core/MTHAllocations.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/11/2 // Created by: EuanC // #import <Foundation/Foundation.h> #import <mach/vm_types.h> NS_ASSUME_NONNULL_BEGIN typedef void (^MTHVMChunkMallocBlock)(size_t bytes, vm_address_t *stack_frames, size_t frames_count); @interface MTHAllocations : NSObject @property (nonatomic, assign) NSInteger mallocReportThresholdInBytes; /**< malloc report generating threshold in bytes */ @property (nonatomic, assign) NSInteger vmReportThresholdInBytes; /**< vmallocte/mmap report generating threshold in bytes */ /** when the category's allocation size within the limit, use this to limit the category output. or all the category summary will output to the report. default 0. */ @property (nonatomic, assign) NSInteger reportCategoryElementCountThreshold; @property (nonatomic, assign, readonly) NSInteger assistantHeapMemoryUsage; /**< extra heap memory used by Allocations */ @property (nonatomic, assign, readonly) NSInteger assistantMmapMemoryUsed; /**< extra mmap memory used by Allocations */ + (instancetype)shared; /** setup root directory path for record files. You should call this method before you start the logger. You should set unique persistance directories for each session. */ - (BOOL)setupPersistanceDirectory:(NSString *)rootDir; - (void)setIsStackLogNeedSysFrame:(BOOL)isStackLogNeedSysFrame; /**< record system libraries frames when record backtrace, default false */ - (void)setMaxStackRecordDepth:(NSInteger)maxStackRecordDepth; /**< stack record max depth, default 50 */ - (BOOL)isLoggingOn; - (BOOL)existLoggingRecords; - (BOOL)startMallocLogging:(BOOL)mallocLogOn vmLogging:(BOOL)vmLogOn; - (BOOL)stopMallocLogging:(BOOL)mallocLogOff vmLogging:(BOOL)vmLogOff; - (void)startSingleChunkMallocDetector:(size_t)thresholdInBytes callback:(MTHVMChunkMallocBlock)callback; - (void)configSingleChunkMallocThresholdInBytes:(size_t)thresholdInBytes; - (void)stopSingleChunkMallocDetector; /** Read record from memory, then generate report and flush to file. while generate malloc report, only record size exceed `mallocReportThresholdInBytes` will be counted. whild generate vm report, only record size exceed `vmReportThresholdInBytes` will be counted. you can change `mallocReportThresholdInBytes`, `vmReportThresholdInBytes` before generate report. */ - (void)generateReportAndSaveToFile; /** In Json Style. */ - (void)generateReportAndSaveToFileInJSON; /** read the report file content generate by `generateReportAndSaveToFile` function. */ - (NSString *)mallocReportFileContent; - (NSString *)vmReportFileContent; - (NSString *)dyldImagesContent; /** Read record from memory, then generate report and flush to console. while generate malloc report, only record size exceed `mallocReportThresholdInBytes` will be counted. whild generate vm report, only record size exceed `vmReportThresholdInBytes` will be counted. you can change `mallocReportThresholdInBytes`, `vmReportThresholdInBytes` before generate report. */ - (void)generateReportAndFlushToConsole; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/UISkeleton/MTHawkeyeMainPanelSwitchViewController.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/9 // Created by: EuanC // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @protocol MTHawkeyeMainPanelSwitcherDelegate; @interface MTHawkeyeMainPanelSwitchViewController : UIViewController @property (nonatomic, weak, readonly) id<MTHawkeyeMainPanelSwitcherDelegate> delegate; - (instancetype)initWithSelectedIndexPath:(NSIndexPath *)selectedIndexPath delegate:(id<MTHawkeyeMainPanelSwitcherDelegate>)delegate; - (CGFloat)fullContentHeight; @end @protocol MTHawkeyeMainPanelSwitcherDelegate <NSObject> @required - (NSInteger)numberOfSwitcherOptionsSection; - (NSInteger)numberOfSwitcherOptionsRowAtSection:(NSInteger)section; - (NSString *)switcherOptionsSectionTitleAtIndex:(NSInteger)index; - (NSString *)switcherOptionsTitleAtIndexPath:(NSIndexPath *)indexPath; @optional - (BOOL)shouldChangeSelectStatusToNew:(NSIndexPath *)newSelectIndexPath fromOld:(NSIndexPath *)oldSelectIndexPath; - (void)panelSwitcherDidSelectAtIndexPath:(NSIndexPath *)indexPath; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/TimeConsumingPlugins/ObjcCallTrace/Core/MTHCallTraceCore.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 01/11/2017 // Created by: EuanC // #ifndef MTHCallTraceCore_h #define MTHCallTraceCore_h #include <objc/objc.h> #include <stdint.h> #include <stdio.h> #define MTHawkeyeCallTracePerformanceTestEnabled 0 #ifdef MTHawkeyeCallTracePerformanceTestEnabled #define _InternalMTCallTracePerformanceTestEnabled MTHawkeyeCallTracePerformanceTestEnabled #else #define _InternalMTCallTracePerformanceTestEnabled NO #endif typedef struct { __unsafe_unretained Class cls; SEL sel; uint32_t cost; // us (1/1000 ms), max 4290s. uint32_t depth; double event_time; // unix time } mth_call_record; extern void mth_calltraceStart(void); extern void mth_calltraceStop(void); extern bool mth_calltraceRunning(void); extern void mth_calltraceConfigTimeThreshold(uint32_t us); // default 15 * 1000 extern void mth_calltraceConfigMaxDepth(int depth); // default 5 extern void mth_calltraceTraceAll(void); extern void mth_calltraceTraceByThreshold(void); extern uint32_t mth_calltraceTimeThreshold(void); // in us, max 4290 * 1e6 us. extern int mth_calltraceMaxDepth(void); extern mth_call_record *mth_getCallRecords(int *num); extern void mth_clearCallRecords(void); #endif /* MTHCallTraceCore_h */ <|start_filename|>MTHawkeye/NetworkPlugins/Inspect/Core/MTHNetworkTaskInspection.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 24/08/2017 // Created by: EuanC // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @class MTHNetworkTaskAdvice; @class MTHNetworkTransaction; @class MTHNetworkTaskInspectorContext; typedef NSArray<MTHNetworkTaskAdvice *> *_Nullable (^MTHNetworkTaskInspectHandler)(MTHNetworkTransaction *transactionToInspect, MTHNetworkTaskInspectorContext *context); typedef NS_ENUM(NSInteger, MTHNetworkTaskInspectionParamValueType) { MTHNetworkTaskInspectionParamValueTypeNone = 0, MTHNetworkTaskInspectionParamValueTypeInteger = 1, MTHNetworkTaskInspectionParamValueTypeFloat = 2, MTHNetworkTaskInspectionParamValueTypeBoolean = 3, }; @class MTHNetworkTaskInspectionParamEntity; /** 网络请求任务侦测项 */ @interface MTHNetworkTaskInspection : NSObject @property (nonatomic, copy) NSString *group; // 分组名称 (APIUsage, Bandwidth, Lantency, Scheduling ...). @property (nonatomic, copy) NSString *name; // 命名 @property (nonatomic, copy) NSString *displayName; // 显示名称 @property (nonatomic, copy, nullable) NSString *guide; // 侦测说明,可用于开关界面上的说明 @property (nonatomic, assign) BOOL enabled; // 是否开启 @property (nonatomic, copy) MTHNetworkTaskInspectHandler inspectHandler; /** 用于传入非默认的侦测参数,详见内置 inspect 的使用 */ @property (nonatomic, copy) NSDictionary<NSString *, MTHNetworkTaskInspectionParamEntity *> *inspectCustomParams; @end /** 侦测项单个配置参数 */ @interface MTHNetworkTaskInspectionParamEntity : NSObject @property (nonatomic, copy) NSString *displayName; // 配置参数的显示名称 @property (nonatomic, strong) id value; // 配置参数的值 @property (nonatomic, assign) MTHNetworkTaskInspectionParamValueType valueType; // 配置参数的数值类型 @property (nonatomic, copy, nullable) NSString *valueUnits; // 配置参数的显示单位 @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeyeDemo/MTHawkeyeDemo/MemoryDemo/AlertRetainedViewController.h<|end_filename|> // // AlertRetainedViewController.h // MTHawkeyeDemo // // Created by EuanC on 11/08/2017. // Copyright © 2017 Meitu. All rights reserved. // #import <UIKit/UIKit.h> @interface AlertRetainedViewController : UIViewController @end <|start_filename|>MTHawkeye/UISkeleton/MTHawkeyeUIClient.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/4 // Created by: EuanC // #import <Foundation/Foundation.h> #import "MTHawkeyeUIPlugin.h" NS_ASSUME_NONNULL_BEGIN typedef void (^MTHawkeyeUIClientPluginsSetupHandler)( NSMutableArray<id<MTHawkeyeMainPanelPlugin>> *mainPanelPluginsToAdd, NSMutableArray<id<MTHawkeyeFloatingWidgetPlugin>> *floatingWidgetPluginsToAdd, NSMutableArray<id<MTHawkeyeSettingUIPlugin>> *settingUIPluginsIntoToAdd); typedef void (^MTHawkeyeUIClientPluginsCleanHandler)( NSMutableArray<id<MTHawkeyeMainPanelPlugin>> *mainPanelPluginsAdded, NSMutableArray<id<MTHawkeyeFloatingWidgetPlugin>> *floatingWidgetPluginsAdded, NSMutableArray<id<MTHawkeyeSettingUIPlugin>> *settingUIPluginsIntoAdded); @interface MTHawkeyeUIClient : NSObject @property (readonly) MTHawkeyeUIClientPluginsSetupHandler pluginsSetupHandler; @property (readonly) MTHawkeyeUIClientPluginsCleanHandler pluginsCleanHandler; + (instancetype)shared; /** plugins setup and cleaner, should call before `startServer`. @param pluginsSetupHandler pluginsSetupHandler will be called while `startServer` invoked. the initial plugin array is empty, after the block, the added plugins will be used to setup client, you can add your own plugins into the array here. @param pluginsCleanHandler pluginsCleanHandler will be called while `stopServer` invoked. the plugin array item will be remove internal after stop, you can do cleanup if you've retain the plugins external. */ - (void)setPluginsSetupHandler:(MTHawkeyeUIClientPluginsSetupHandler)pluginsSetupHandler pluginsCleanHandler:(MTHawkeyeUIClientPluginsCleanHandler)pluginsCleanHandler; /** setup ui plugins and start server, then show floating monitor window if need. after the server start, a gesture recognizer will be placed on the keyWindow to show/hide the floating monitor window. */ - (void)startServer; /** hide window and stop server, then call the pluginsCleaner do clean stuff. the gesture recognizer will remain, if you want to remove the recognizer, go to Hawkeye Setting UI, turn off show/hide window gesture recognizer manual. */ - (void)stopServer; /** show floating monitor window, you can also show the window by 3 fingers long press for 3 seconds gesture. */ - (void)showWindow; /** hide floating monitor window. you can also hide the window by 3 fingers long press for 3 seconds gesture. */ - (void)hideWindow; /** Open the main panel with id mainPanelId, which related to `mainPanelIdentity` in `MTHawkeyeMainPanelPlugin`. when the mainPanelId is nil, will open previous viewed panel. @param mainPanelId the panel you want to open, related to `mainPanelIdentity` in `MTHawkeyeMainPanelPlugin` */ - (void)showMainPanelWithSelectedID:(nullable NSString *)mainPanelId; /** Find specific floating widget plugin with floatingWidgetID and raise an warning on it. You can configure the warning action by passing a params. params eg.: raise warning on `mem` floating widget for 5 seconds, and when tap the floating widget during the warning, it will jump to "memory-records" panel. { // flashing the warning for 5 seconds. kMTHFloatingWidgetRaiseWarningParamsKeepDurationKey : @(5.f), // search `mainPanelIdentity` in `MTHawkeyeMainPanelPlugin`. kMTHFloatingWidgetRaiseWarningParamsPanelIDKey : @"memory-records", } @param floatingWidgetID where warning raise on, related to `widgetIdentity` in `MTHawkeyeFloatingWidgetPlugin` @param params key: kMTHFloatingWidgetRaiseWarningParamsKeepDurationKey, see above kMTHFloatingWidgetRaiseWarningParamsPanelIDKey, see above */ - (void)raiseWarningOnFloatingWidget:(NSString *)floatingWidgetID withParams:(nullable NSDictionary *)params; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/MemoryPlugins/Allocations/Core/mtha_file_utils.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/10/25 // Created by: EuanC // #ifndef mtha_file_utils_h #define mtha_file_utils_h #import <stdbool.h> #include <stdio.h> #ifdef __cplusplus extern "C" { #endif bool mtha_is_file_exist(const char *filepath); bool mtha_create_file(const char *filepath); size_t mtha_get_file_size(int fd); #ifdef __cplusplus } #endif #endif /* mtha_file_utils_h */ <|start_filename|>MTHawkeyeDemo/MTHawkeyeDemo/NetworkDemo/MTNetworkTaskDemoViewController.h<|end_filename|> // // MTNetworkTaskDemoViewController.h // MTHawkeyeDemo // // Created by EuanC on 17/07/2017. // Copyright © 2017 Meitu. All rights reserved. // #import <UIKit/UIKit.h> @interface MTNetworkTaskDemoViewController : UIViewController @end <|start_filename|>MTHawkeye/UISkeleton/MTHawkeyeMainPanelViewController.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/9 // Created by: EuanC // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @protocol MTHawkeyeMainPanelViewControllerDatasource; @protocol MTHawkeyeMainPanelSwitcherDelegate; @interface MTHawkeyeMainPanelViewController : UIViewController @property (nonatomic, weak) id<MTHawkeyeMainPanelViewControllerDatasource> datasource; @property (nonatomic, weak) id<MTHawkeyeMainPanelSwitcherDelegate> delegate; - (instancetype)initWithSelectedIndexPath:(NSIndexPath *)indexPath datasource:(id<MTHawkeyeMainPanelViewControllerDatasource>)datasource delegate:(id<MTHawkeyeMainPanelSwitcherDelegate>)delegate; - (instancetype)initWithSelectedPanelID:(NSString *)panelID datasource:(id<MTHawkeyeMainPanelViewControllerDatasource>)datasource delegate:(id<MTHawkeyeMainPanelSwitcherDelegate>)delegate; @end @protocol MTHawkeyeMainPanelViewControllerDatasource <NSObject> @optional - (NSIndexPath *)indexPathForPanelID:(NSString *)panelID; - (NSString *)panelViewControllerTitleForSwitcherOptionAtIndexPath:(NSIndexPath *)indexPath; - (UIViewController *)panelViewControllerForSwitcherOptionAtIndexPath:(NSIndexPath *)indexPath; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/MemoryPlugins/LivingObjectSniffer/HawkeyeCore/MTHLivingObjectsSnifferHawkeyeAdaptor.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/10 // Created by: EuanC // #import <Foundation/Foundation.h> #import "MTHLivingObjectInfo.h" #import "MTHawkeyePlugin.h" NS_ASSUME_NONNULL_BEGIN @protocol MTHLivingObjectsWarningProtocol; @interface MTHLivingObjectsSnifferHawkeyeAdaptor : NSObject <MTHawkeyePlugin> @property (nonatomic, weak, nullable) id<MTHLivingObjectsWarningProtocol> delegate; @end @protocol MTHLivingObjectsWarningProtocol <NSObject> - (void)sniffOutUnexpectLivingObject:(MTHLivingObjectInfo *)objInfo extraInfo:(MTHLivingObjectGroupInClass *)group; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeyeDemo/MTHawkeyeDemo/MemoryDemo/ALeakingViewModel.h<|end_filename|> // // ALeakingViewModel.h // MTHawkeyeDemo // // Created by EuanC on 10/07/2017. // Copyright © 2017 Meitu. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @protocol ANormalProtocolWithNSObject; @protocol ANormalProtocolWithoutNSObject; @interface ALeakingViewModel : NSObject @end @interface AViewModelWithLeakingProperty : NSObject @property (nonatomic, strong) ALeakingViewModel *viewModelWillLeak; @end @protocol ANormalProtocolWithoutNSObjectA; @protocol ANormalProtocolWithoutNSObject @property (nonatomic, strong, nullable) id<ANormalProtocolWithoutNSObjectA> aaaaaa; @end @protocol ANormalProtocolWithoutNSObjectA @property (nonatomic, readonly) NSInteger index; @end @interface MBCCameraCapturingConfiguration : NSObject <ANormalProtocolWithoutNSObject> @property (nonatomic, assign, readonly) BOOL fullScreenRatio; /** 实现 ANormalProtocolWithoutNSObject 的属性,如果未显示定义,不能直接通过 keyForValue 获取 如果使用 KeyForValue 来遍历,需在 mt_memoryDebuggerIsPropertyNeedObserve 内判断 isValue 来过滤 */ //@property (nonatomic, strong, nullable) id<ANormalProtocolWithoutNSObjectA> aaaaaa; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/Utils/mth_thread_utils.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/11/2 // Created by: EuanC // #ifndef mth_thread_utils_h #define mth_thread_utils_h #include <stdbool.h> #include <stdio.h> #ifdef __cplusplus extern "C" { #endif // __cplusplus bool mth_suspend_all_child_threads(void); bool mth_resume_all_child_threads(void); #ifdef __cplusplus } #endif // __cplusplus #endif /* mth_thread_utils_h */ <|start_filename|>MTHawkeye/TimeConsumingPlugins/UITimeProfiler/HawkeyeUI/MTHUITimeProfilerResultViewModel.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 09/11/2017 // Created by: EuanC // #import <UIKit/UIKit.h> @class MTHCallTraceTimeCostModel; @class MTHTimeIntervalCustomEventRecord; @class MTHViewControllerAppearRecord; @interface MTHTimeProfilerResultViewSection : NSObject @property (nonatomic, strong) NSString *title; @property (nonatomic, assign) NSTimeInterval timeCostInMS; @property (nonatomic, strong) MTHViewControllerAppearRecord *vcRecord; @property (nonatomic, copy) NSArray *cellModels; /**< could be MTHCallTraceTimeCostModel or MTHTimeIntervalCustomEventRecord */ @end @interface MTHUITimeProfilerResultViewModel : NSObject - (instancetype)initWithVCAppearRecords:(NSArray<MTHViewControllerAppearRecord *> *)vcAppearRecords detailCostRecords:(NSArray<MTHCallTraceTimeCostModel *> *)detailCostRecords customEventRecords:(NSArray<MTHTimeIntervalCustomEventRecord *> *)customEventRecords; - (NSInteger)numberOfSection; - (NSString *)titleForSection:(NSInteger)section; - (NSTimeInterval)timeCostInMSForSection:(NSInteger)section; - (MTHTimeProfilerResultViewSection *)sectionAtIndex:(NSInteger)index; - (MTHViewControllerAppearRecord *)vcRecordForSection:(NSInteger)section; - (NSInteger)numberOfCellForSection:(NSInteger)section; - (id)cellModelAtIndexPath:(NSIndexPath *)indexPath; - (NSArray *)cellModelsForSection:(NSUInteger)section; - (NSArray *)cellModelsFor:(MTHViewControllerAppearRecord *)vcAppearRecord atSection:(NSUInteger)section; - (NSArray *)extraRecordsStartFrom:(NSTimeInterval)startTime endBefore:(NSTimeInterval)endTime lowerSectionIndex:(NSUInteger)section; - (void)updateCell:(NSIndexPath *)indexPath expanded:(bool)expanded; - (BOOL)cellExpandedForIndexPath:(NSIndexPath *)indexPath; @end <|start_filename|>MTHawkeye/NetworkPlugins/HawkeyeUI/MTHNetworkMonitorViewModel.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 17/07/2017 // Created by: EuanC // #import <Foundation/Foundation.h> #import "MTHNetworkTransaction.h" #import "MTHNetworkWaterfallViewController.h" NS_ASSUME_NONNULL_BEGIN typedef NS_ENUM(NSInteger, MTHNetworkRecordsDisplayMode) { MTHNetworkRecordsDisplayModeFull = 0, // 展示完整的网络请求记录列表 MTHNetworkRecordsDisplayModeParallel, // 展示选中时刻同时执行中的网络请求记录列表 MTHNetworkRecordsDisplayModeRepeatTransactions, // 分组展示重复的网络记录请求 MTHNetworkRecordsDisplayModeDomainFilter, // 展示根据域名过滤的网络请求记录列表 MTHNetworkRecordsDisplayModeRspCodeFilter, // 展示根据 http code 过滤的网络请求记录列表 MTHNetworkRecordsDisplayModeTimeoutFilter, // 展示网络超时可能不合理的网络请求记录列表 }; @class MTHNetworkTaskAdvice; @class MTHNetworkTransactionsURLFilter; @class MTHNetworkTaskInspectionWithResult; @interface MTHNetworkMonitorViewModel : NSObject <MTHNetworkWaterfallDataSource> @property (nonatomic, assign) MTHNetworkRecordsDisplayMode displayMode; @property (nonatomic, assign) BOOL isPresentingSearch; // 当前显示的网络请求记录列表 @property (nonatomic, readonly) NSArray<MTHNetworkTransaction *> *networkTransactions; // 过滤的网络请求记录列表 @property (nonatomic, readonly) NSArray<MTHNetworkTransaction *> *filteredNetworkTransactions; // - (nullable NSArray<MTHNetworkTaskAdvice *> *)advicesForTransaction:(MTHNetworkTransaction *)transaction; // 当当前聚焦的请求 r1 未完成时,之后展示的请求数不依赖于 r1 的结束时间,此属性用于限制展示的数量 @property (nonatomic, assign) NSInteger maxFollowingWhenFocusNotResponse; // 当前聚焦的网络请求记录下标, 调用 focusOnTransactionWithIndex: 时会更新 @property (nonatomic, assign, readonly) NSInteger requestIndexFocusOnCurrently; // 当前显示的关联网络请求记录下标数组,包含聚焦的请求,调用 focusOnTransactionWithIndex: 时会更新 @property (nonatomic, copy, readonly) NSArray<NSNumber *> *currentOnViewIndexArray; @property (nonatomic, assign) NSTimeInterval timelineStartAt; // 当前关注的 timeline 的起始时间 @property (nonatomic, assign) NSTimeInterval timelineDuration; // 当前关注的 timeline 总时常 // 搜索过滤相关 @property (nonatomic, copy) NSString *currentSearchText; @property (nonatomic, strong) MTHNetworkTransactionsURLFilter *filter; @property (nonatomic, copy) NSSet<NSString *> *warningAdviceTypeIDs; /**< Cell 上不显示特定 inspection 的警告 */ - (void)focusOnTransactionWithRequestIndex:(NSInteger)requestIndex; - (NSInteger)viewIndexFromRequestIndex:(NSInteger)requestIndex; - (MTHNetworkTransaction *)transactionFromRequestIndex:(NSInteger)requestIndex; - (void)updateSearchResultsWithText:(NSString *)searchText completion:(void (^)(void))completion; // transactions update - (void)loadTransactionsWithInspectComoletion:(void (^)(void))inspectCompetion; - (void)incomeNewTransactions:(NSArray<MTHNetworkTransaction *> *)transactions inspectCompletion:(void (^)(void))inspectCompetion; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeyeDemo/MTHawkeyeDemo/MemoryDemo/EnormousViewModel.h<|end_filename|> // // EnormousViewModel.h // MTHawkeyeDemo // // Created by EuanC on 16/08/2017. // Copyright © 2017 Meitu. All rights reserved. // #import <Foundation/Foundation.h> #import "ANormalViewModel.h" @interface EnormousViewModel : NSObject @property (nonatomic, strong) NSMutableArray<EnormousViewModel *> *subModels; - (void)createSubModelsWithCount:(NSInteger)count depth:(NSInteger)depth; @end <|start_filename|>MTHawkeye/TimeConsumingPlugins/UITimeProfiler/HawkeyeUI/MTHUITImeProfilerResultEventCell.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/9 // Created by: EuanC // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @class MTHTimeIntervalCustomEventRecord; @interface MTHUITImeProfilerResultEventCell : UITableViewCell - (void)configureWithEventRecord:(MTHTimeIntervalCustomEventRecord *)eventRecord expanded:(BOOL)expanded; + (CGFloat)heightForEventRecord:(MTHTimeIntervalCustomEventRecord *)eventRecord expanded:(BOOL)expanded; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/TimeConsumingPlugins/UITimeProfiler/HawkeyeUI/MTHTimeIntervalStepsViewController.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/6/20 // Created by: 潘名扬 // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @class MTHViewControllerAppearRecord; @class MTHCallTraceTimeCostModel; @class MTHAppLaunchRecord; @interface MTHTimeIntervalStepsViewController : UIViewController /** extraRecords element could be MTHCallTraceTimeCostModel or MTHTimeIntervalCustomEventRecord */ - (void)setupWithAppLaunchRecord:(MTHAppLaunchRecord *)launchRecord firstVCRecord:(nullable MTHViewControllerAppearRecord *)vcRecord extraRecords:(nullable NSArray *)extraRecords; /** extraRecords element could be MTHCallTraceTimeCostModel or MTHTimeIntervalCustomEventRecord */ - (void)setupWithVCRecord:(MTHViewControllerAppearRecord *)vcRecord extraRecords:(nullable NSArray *)extraRecords; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/GraphicsPlugins/OpenGLTrace/HawkeyeUI/MTHOpenGLTraceHawkeyeUI.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/22 // Created by: EuanC // #import <Foundation/Foundation.h> #import <MTHawkeye/MTHawkeyeUIPlugin.h> NS_ASSUME_NONNULL_BEGIN @class MTHawkeyeSettingSectionEntity; @interface MTHOpenGLTraceHawkeyeUI : NSObject <MTHawkeyeSettingUIPlugin, MTHawkeyeMainPanelPlugin, MTHawkeyeFloatingWidgetPlugin> @property (nonatomic, assign) BOOL widgetHidden; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/MemoryPlugins/LivingObjectSniffer/HawkeyeUI/MTHLivingObjectViewController.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 03/07/2017 // Created by: EuanC // #import <UIKit/UIKit.h> @class MTHLivingObjectGroupInClass; @class MTHLivingObjectGroupInTrigger; @interface MTHLivingObjectViewController : UIViewController - (instancetype)initWithLivingInstancesGroupInClass:(MTHLivingObjectGroupInClass *)groupInClass groupsInTrigger:(NSArray<MTHLivingObjectGroupInTrigger *> *)groups; @end <|start_filename|>MTHawkeye/NetworkPlugins/HawkeyeUI/MTHNetworkTransactionDetailTableViewController.h<|end_filename|> // // Copyright (c) 2014-2016, Flipboard // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2/10/15 // Created by: <NAME> // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @class MTHNetworkTransaction; @class MTHNetworkTaskAdvice; @interface MTHNetworkTransactionDetailTableViewController : UITableViewController @property (nonatomic, strong) MTHNetworkTransaction *transaction; @property (nonatomic, strong, nullable) NSArray<MTHNetworkTaskAdvice *> *advices; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/MemoryPlugins/LivingObjectSniffer/Core/UIDevice+MTHLivingObjectSniffer.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 29/06/2017 // Created by: EuanC // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface UIDevice (MTHLivingObjectSniffer) /// Used memory by app in byte. @property (nonatomic, readonly) int64_t memoryAppUsed; /* The real physical memory used by app. - https://stackoverflow.com/questions/9660763/whats-the-right-statistic-for-ios-memory-footprint-live-bytes-real-memory-ot - https://developer.apple.com/library/archive/technotes/tn2434/_index.html */ @property (nonatomic, readonly) int64_t memoryFootprint; /// Total physical memory in byte. (-1 when error occurs) @property (nonatomic, readonly) int64_t memoryTotal; /// Used (active + inactive + wired) memory in byte. (-1 when error occurs) @property (nonatomic, readonly) int64_t memoryUsed; /// Free memory in byte. (-1 when error occurs) @property (nonatomic, readonly) int64_t memoryFree; /// Acvite memory in byte. (-1 when error occurs) @property (nonatomic, readonly) int64_t memoryActive; /// Inactive memory in byte. (-1 when error occurs) @property (nonatomic, readonly) int64_t memoryInactive; /// Wired memory in byte. (-1 when error occurs) @property (nonatomic, readonly) int64_t memoryWired; /// Purgable memory in byte. (-1 when error occurs) @property (nonatomic, readonly) int64_t memoryPurgable; @end <|start_filename|>MTHawkeyeDemo/MTHawkeyeDemo/MemoryDemo/LeakingPropertiesTestViewController.h<|end_filename|> // // LeakingPropertiesTestViewController.h // MTHawkeyeDemo // // Created by EuanC on 03/08/2017. // Copyright © 2017 Meitu. All rights reserved. // #import <UIKit/UIKit.h> @interface LeakingPropertiesTestViewController : UIViewController @end <|start_filename|>MTHawkeye/TimeConsumingPlugins/UITimeProfiler/HawkeyeUI/MTHUITimeProfilerResultSectionHeaderView.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/6/19 // Created by: 潘名扬 // #import <UIKit/UIKit.h> typedef void (^MTHCallTraceShowDetailBlock)(void); @interface MTHUITimeProfilerResultSectionHeaderView : UITableViewHeaderFooterView @property (nonatomic, strong) UILabel *topLabel; @property (nonatomic, strong) UILabel *bottomLabel; @property (nonatomic, strong) MTHCallTraceShowDetailBlock showDetailBlock; - (void)setupWithTopText:(NSString *)topText bottomText:(NSString *)bottomText showDetailBlock:(MTHCallTraceShowDetailBlock)block; @end <|start_filename|>MTHawkeye/StackBacktrace/MTHStackFrameSymbolicsRemote.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/22 // Created by: EuanC // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface MTHStackFrameSymbolicsRemote : NSObject /* MTHStackFrameSymbolicsRemoteProtocol As a symbolics service, you should accept a POST request with a JSON format string HTTP body. eg: ```json { "dyld_images_info": { "arch": "arm64 v8", "model": "16B92", "os_version": "12.1", "name": "Meipai", "dyld_images": [ { "addr":"0x1002034", # require "addr_slide":"0x002132", # optional "uuid":"23024352u5982752", # require "name":"" # optional }, ... ] }, "stack_frames": [ "0x18ee92708", "0x18ee92722", "0x18ee92333", "0x18ee92221", "0x18ee92998" ] } ``` and response symbolicated stack frames in JSON format string. eg: ```json { "stack_frames":[ { "addr": "0x1002034", # require "fname": "Meipai", # require, path name of shared object. "fbase": "0x1001000", # optional, base address of shared object. "sname": "[AClass method1]", # require, name of nearest symbol. "sbase": "0x1002034", # optional, address of nearest symbol. }, ... ], "error":{ # optional "msg": "" } } ``` */ + (NSString *)symbolicsServerURL; + (void)configureSymbolicsServerURL:(NSString *)serverURL; + (void)configureSymbolicsTaskTimeout:(NSTimeInterval)timeoutInSeconds; /* @param framePointers stack frames that needs to be symbolized, in hexadecimal string array format. eg. @[@"0x100000", @"0x10000230"] @param dyldImagesInfo associated dyld images information. eg. @{ "arch": "arm64 v8", "model": "16B92", "os_version": "12.1", "name": "ProjectName", "dyld_images": [ { "addr": "0x1000240", "addr_slide": "0x0240", "uuid": "xxxxxxxxxxxxxxx", "name": "xyx" # optional }, { "addr": "0x1000240", "addr_slide": "0x0240", "uuid": "xxxxxxxxxxxxxxx" } ] } @param completionHandler get the symbolized frames from completionHandler eg. @[ { "addr": "0x1000240", "fname": "xyx", "fbase": "0x1000100", "sname": "[AClass method1]", "sbase": "0x1000240" }, ... ] */ + (void)symbolizeStackFrames:(NSArray<NSString *> *)framePointers withDyldImagesInfos:(NSDictionary *)dyldImagesInfo completionHandler:(void (^)(NSArray<NSDictionary<NSString *, NSString *> *> *symbolizedFrames, NSError *error))completionHandler; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/UISkeleton/Toast/UIButton+MTHBlocks.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 11/06/2018 // Created by: Huni // #import <UIKit/UIKit.h> typedef void (^MTHToastButtonActionBlock)(void); @interface UIButton (MTHBlocks) - (void)mth_handleControlEvent:(UIControlEvents)controlEvent withBlock:(MTHToastButtonActionBlock)action; @end <|start_filename|>MTHawkeye/StorageMonitorPlugins/DirectoryWatcher/HawkeyeCore/MTHawkeyeUserDefaults+DirectorWatcher.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/21 // Created by: EuanC // #import "MTHawkeyeUserDefaults.h" typedef NS_OPTIONS(NSUInteger, MTHDirectoryWatcherDetect) { kMTHDirectoryWatcherDetectTimingEnterForeground = 1 << 0, kMTHDirectoryWatcherDetectTimingEnterBackground = 1 << 1, }; NS_ASSUME_NONNULL_BEGIN @interface MTHawkeyeUserDefaults (DirectorWatcher) @property (nonatomic, assign) BOOL directoryWatcherOn; @property (nonatomic, assign) NSTimeInterval directoryWatcherStartDelay; @property (nonatomic, assign) MTHDirectoryWatcherDetect directoryWatcherDetectOptions; @property (nonatomic, assign) NSUInteger directoryWatcherStopAfterTimes; @property (nonatomic, assign) NSTimeInterval directoryWatcherReportMinInterval; @property (atomic, strong) NSArray<NSString *> *directoryWatcherFoldersPath; // NSHomeDirectory() relative path @property (atomic, strong) NSDictionary<NSString *, NSNumber *> *directoryWatcherFoldersLimitInMB; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/MemoryPlugins/LivingObjectSniffer/Core/MTHLivingObjectSniffService.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/6 // Created by: EuanC // #import <Foundation/Foundation.h> #import "MTHLivingObjectSniffer.h" NS_ASSUME_NONNULL_BEGIN @interface MTHLivingObjectSniffService : NSObject @property (nonatomic, readonly) MTHLivingObjectSniffer *sniffer; @property (nonatomic, assign) NSTimeInterval delaySniffInSeconds; // default 3.f + (instancetype)shared; - (void)start; - (void)stop; - (BOOL)isRunning; - (void)addIgnoreList:(NSArray<NSString *> *)ignoreList; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/StorageMonitorPlugins/DirectoryWatcher/HawkeyeUI/MTHDirectoryWatcherViewController.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/121/15 // Created by: David.Dai // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface MTHDirectoryWatcherViewController : UIViewController @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeyeDemo/MTHawkeyeDemo/MemoryDemo/MemoryPerformanceTestViewController.h<|end_filename|> // // MemoryPerformanceTestViewController.h // MTHawkeyeDemo // // Created by EuanC on 16/08/2017. // Copyright © 2017 Meitu. All rights reserved. // #import <UIKit/UIKit.h> @interface MemoryPerformanceTestViewController : UIViewController @end <|start_filename|>MTHawkeye/GraphicsPlugins/OpenGLTrace/HawkeyeCore/MTHOpenGLTraceHawkeyeAdaptor.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/20 // Created by: EuanC // #import <Foundation/Foundation.h> #import "MTHawkeyePlugin.h" NS_ASSUME_NONNULL_BEGIN @protocol MTHOpenGLTraceDelegate; @interface MTHOpenGLTraceHawkeyeAdaptor : NSObject <MTHawkeyePlugin> @property (readonly) NSArray *alivingMemoryGLObjects; // Current gl objects in memory @property (class, readonly) size_t openGLESResourceMemorySize; - (void)addDelegate:(id<MTHOpenGLTraceDelegate>)delegate; - (void)removeDelegate:(id<MTHOpenGLTraceDelegate>)delegate; @end @protocol MTHOpenGLTraceDelegate <NSObject> @optional - (void)glTracer:(MTHOpenGLTraceHawkeyeAdaptor *)gltracer didUpdateMemoryUsed:(size_t)memorySizeInByte; - (void)glTracerDidUpdateAliveGLObjects:(MTHOpenGLTraceHawkeyeAdaptor *)gltracer; - (void)glTracer:(MTHOpenGLTraceHawkeyeAdaptor *)gltracer didReceivedErrorMsg:(NSString *)errorMessage; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/NetworkPlugins/HawkeyeUI/MTHWebTableViewCell.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 20/08/2018 // Created by: Huni // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN extern NSString *const kMTHawkeyeWebTableViewCellIdentifier; @interface MTHWebTableViewCell : UITableViewCell - (void)webViewLoadString:(NSString *)string; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/NetworkPlugins/Inspect/Core/MTHNetworkTaskInspectorContext.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 25/08/2017 // Created by: EuanC // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @class MTHNetworkTransaction; // MARK: - MTHTopLevelDomain /** 顶级域名类 利用 NSString 去重 */ @interface MTHTopLevelDomain : NSObject @property (nonatomic, copy) NSString *domainString; @property (nonatomic, strong) NSMutableSet<NSString *> *secondLevelDomains; - (instancetype)initWithString:(NSString *)domainString; @end // MARK: - MTHNetworkTaskInspectorContext @interface MTHNetworkTaskInspectorContext : NSObject @property (nonatomic, readonly) NSArray<MTHNetworkTransaction *> *transactions; /** 使用网络请求记录列表,初始化 InspectorContext 环境 */ - (void)updateContextWithTransactions:(NSArray<MTHNetworkTransaction *> *)transactions; // MARK: - For NSURLSessionTask Manager /** 记录创建了同一 Host 的 URLSessionTask 所在的 NSURLSession 个数 正常应该为 1,不合理使用时会有多个 NSURLSession 创建同一类型的 task key: host value: NSCountedSet<urlSessionTask.NSURLSession.pointerString(count)> */ @property (nonatomic, strong, nullable) NSMutableDictionary *taskSessionsGroupbyHost; /** 记录所有网络请求涉及到的一级和二级域名 */ @property (nonatomic, strong, nullable) NSMutableSet<MTHTopLevelDomain *> *topLevelDomains; /** 记录每个独立的 NSURLSession 所创建的 Task 总数 element: urlSessionTask.NSURLSession.pointerString(count) */ @property (nonatomic, copy, nullable) NSCountedSet *countedTaskSessions; // MARK: - For duplicated transactions @property (nonatomic, strong, nullable) NSMutableOrderedSet *hashKeySet; @property (nonatomic, strong, nullable) NSMutableArray *duplicatedGroups; @property (nonatomic, assign) int64_t duplicatedPayloadCost; // 记录重复的网络请求多消耗的网络流量 - (NSString *)hashKeyForTransaction:(MTHNetworkTransaction *)transaction; // MARK: - For Parallel transactions - (NSArray<MTHNetworkTransaction *> *)parallelTransactionsBefore:(MTHNetworkTransaction *)transaction; @property (nonatomic, strong, nullable) NSMutableArray *containDNSCostRequestIndexesOnStartup; @property (nonatomic, strong, nullable) NSMutableArray *containTCPConnCostRequestIndexesOnStartup; @property (nonatomic, assign) NSTimeInterval dnsCostTotalOnStartup; @property (nonatomic, assign) NSTimeInterval tcpConnCostTotalOnStartup; - (NSArray<MTHNetworkTransaction *> *)transactionsForRequestIndexes:(NSIndexSet *)indexes; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/UISkeleton/Toast/MTHToast.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 13/06/2018 // Created by: Huni // #import <Foundation/Foundation.h> #import "MTHToastBtnHandler.h" typedef NS_ENUM(NSInteger, MTHToastStyle) { MTHToastStyleSimple = 0, MTHToastStyleDetail }; @interface MTHToast : NSObject + (instancetype)shared; /** 显示短消息的弹框 @param message 信息 @param handler 点击弹框时间,默认为收起弹框 */ - (void)showToastWithMessage:(NSString *)message handler:(void (^)(void))handler; /** 显示 Toast 弹框 @param style 弹框类型 @param title 弹框标题 @param content 弹框内容 @param detailContent 弹框展开后内容 @param duration 弹框持续时间 @param handler 点击弹框事件 @param buttonHandlers 弹框展开后添加的按钮 @param hidden 弹框被遮挡后是否要被忽略 */ - (void)showToastWithStyle:(MTHToastStyle)style title:(NSString *)title content:(NSString *)content detailContent:(NSString *)detailContent duration:(NSTimeInterval)duration handler:(void (^)(void))handler buttonHandlers:(NSArray<MTHToastBtnHandler *> *)buttonHandlers autoHiddenBeOccluded:(BOOL)hidden; @end <|start_filename|>MTHawkeye/UISkeleton/MTHawkeyeSettingTableEntity.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/14 // Created by: EuanC // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @class MTHawkeyeSettingSectionEntity; @class MTHawkeyeSettingCellEntity; @interface MTHawkeyeSettingTableEntity : NSObject @property (nonatomic, copy) NSArray<MTHawkeyeSettingSectionEntity *> *sections; @end @interface MTHawkeyeSettingSectionEntity : NSObject @property (nonatomic, copy, nullable) NSString *headerText; @property (nonatomic, copy, nullable) NSString *footerText; @property (nonatomic, copy) NSArray<MTHawkeyeSettingCellEntity *> *cells; @property (nonatomic, copy, nullable) NSString *tag; - (void)addCell:(MTHawkeyeSettingCellEntity *)cell; - (void)insertCell:(MTHawkeyeSettingCellEntity *)cell atIndex:(NSUInteger)index; - (void)removeCellByTag:(NSString *)cellTag; @end /****************************************************************************/ #pragma mark - Setting Cell @protocol MTHawkeyeSettingCellEntityDelegate; @interface MTHawkeyeSettingCellEntity : NSObject @property (nonatomic, copy) NSString *title; @property (nonatomic, copy, nullable) NSString *tag; @property (nonatomic, assign) BOOL frozen; @property (nonatomic, weak, nullable) id<MTHawkeyeSettingCellEntityDelegate> delegate; @end @protocol MTHawkeyeSettingCellEntityDelegate <NSObject> - (void)hawkeyeSettingEntityValueDidChanged:(MTHawkeyeSettingCellEntity *)entity; @end // MARK: - @interface MTHawkeyeSettingFoldedCellEntity : MTHawkeyeSettingCellEntity @property (nonatomic, copy) NSString *foldedTitle; @property (nonatomic, copy) NSArray<MTHawkeyeSettingSectionEntity *> *foldedSections; - (void)addSection:(MTHawkeyeSettingSectionEntity *)section; - (void)insertSection:(MTHawkeyeSettingSectionEntity *)section atIndex:(NSUInteger)insertTo; - (void)insertCell:(MTHawkeyeSettingCellEntity *)cell atIndexPath:(NSIndexPath *)insertTo; @end @interface MTHawkeyeSettingEditorCellEntity : MTHawkeyeSettingCellEntity @property (nonatomic, assign) UIKeyboardType editorKeyboardType; @property (nonatomic, copy, nullable) NSString *valueUnits; @property (nonatomic, copy, nullable) NSString *inputTips; @property (nonatomic, copy) NSString * (^setupValueHandler)(void); @property (nonatomic, copy) BOOL (^valueChangedHandler)(NSString *newValue); @end @interface MTHawkeyeSettingSwitcherCellEntity : MTHawkeyeSettingCellEntity @property (nonatomic, copy) BOOL (^setupValueHandler)(void); @property (nonatomic, copy) BOOL (^valueChangedHandler)(BOOL newValue); @end @interface MTHawkeyeSettingSelectorCellEntity : MTHawkeyeSettingCellEntity @property (nonatomic, copy) NSArray<NSString *> *options; @property (nonatomic, copy) NSUInteger (^setupSelectedIndexHandler)(void); @property (nonatomic, copy) BOOL (^selectIndexChangedHandler)(NSUInteger newIndex); @end @interface MTHawkeyeSettingActionCellEntity : MTHawkeyeSettingCellEntity @property (nonatomic, copy) void (^didTappedHandler)(void); @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/NetworkPlugins/Monitor/Core/Utils/MTHNetworkCurlLogger.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 07/27/16 // Created by: Ji // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface MTHNetworkCurlLogger : NSObject /** * Generates a cURL command equivalent to the given request. * * @param request The request to be translated */ + (NSString *)curlCommandString:(NSURLRequest *)request; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/TimeConsumingPlugins/ObjcCallTrace/Core/MTHCallTraceTimeCostModel.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 01/11/2017 // Created by: EuanC // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface MTHCallTraceTimeCostModel : NSObject @property (nonatomic, copy) NSString *className; /**< ObjC class name */ @property (nonatomic, copy) NSString *methodName; /**< Objc method name */ @property (nonatomic, assign) BOOL isClassMethod; @property (nonatomic, assign) NSTimeInterval timeCostInMS; /**< cost in millisecond */ @property (nonatomic, assign) NSTimeInterval eventTime; /**< happen at */ @property (nonatomic, assign) NSUInteger callDepth; /**< depth from top */ @property (nonatomic, copy, nullable) NSArray<MTHCallTraceTimeCostModel *> *subCosts; // 子调用 @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/TimeConsumingPlugins/UITimeProfiler/Core/MTHAppLaunchStepTracer.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/121/25 // Created by: EuanC // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface MTHAppLaunchStepTracer : NSObject + (void)traceSteps; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/EnergyPlugins/CPUTrace/HawkeyeCore/MTHawkeyeUserDefaults+CPUTrace.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/21 // Created by: EuanC // #import "MTHawkeyeUserDefaults.h" NS_ASSUME_NONNULL_BEGIN @interface MTHawkeyeUserDefaults (CPUMonitor) @property (nonatomic, assign) BOOL cpuTraceOn; /** When the CPU is under low load, the frequency to check the CPU usage. default 1 second. */ @property (nonatomic, assign) CGFloat cpuTraceCheckIntervalIdle; /** When the CPU is under high load, the frequency to check the CPU usage. default 0.3 second. */ @property (nonatomic, assign) CGFloat cpuTraceCheckIntervalBusy; /** Only care when the CPU usage exceeding the threshold. default 80% */ @property (nonatomic, assign) CGFloat cpuTraceHighLoadThreshold; /** Only dump StackFrame of the thread when it's CPU usage exceeding the threshold while sampling. default 15% */ @property (nonatomic, assign) CGFloat cpuTraceStackFramesDumpThreshold; /** Only generate record when the high load lasting longer than limit. default 60 seconds. */ @property (nonatomic, assign) CGFloat cpuTraceHighLoadLastingLimit; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/UISkeleton/MTHawkeyeInputAlert.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/18 // Created by: EuanC // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface MTHawkeyeInputAlert : NSObject + (void)showInputAlertWithTitle:(nullable NSString *)title messgage:(nullable NSString *)message from:(UIViewController *)fromVC textFieldSetupHandler:(void (^)(UITextField *textField))setupHandler confirmHandler:(void (^)(UITextField *textField))confirmHandler cancelHandler:(nullable void (^)(UITextField *textField))cancelHandler; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/StorageMonitorPlugins/DirectoryWatcher/Core/MTHDirectoryWatcher.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/11/6 // Created by: Huni // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @class MTHDirectoryWatcher; @protocol MTHDirectoryWatcherDelegate <NSObject> @required - (void)directoryDidChange:(MTHDirectoryWatcher *)directoryWatcher; @end @interface MTHDirectoryWatcher : NSObject @property (nonatomic, assign, readonly) CGFloat folderSize; @property (nonatomic, copy, readonly) NSString *watchPath; @property (nonatomic, assign) NSUInteger reportCount; @property (nonatomic, assign) NSTimeInterval changeReportInterval; + (MTHDirectoryWatcher *)directoryWatcherWithPath:(NSString *)watchPath changeReportInterval:(NSTimeInterval)changeReportInterval delegate:(id<MTHDirectoryWatcherDelegate>)watchDelegate; + (unsigned long long)fileSizeAtPath:(NSString *)path; - (void)invalidate; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/MemoryPlugins/Allocations/Core/mtha_splay_tree.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/7/10 // Created by: Huni // #ifndef mtha_splay_tree_h #define mtha_splay_tree_h #import <assert.h> #import <mach/mach.h> #import <malloc/malloc.h> #import <stdbool.h> #import <stdio.h> #import <stdlib.h> #ifdef __cplusplus extern "C" { #endif // MARK: - Macros #define MTH_ALLOCATIONS_FLAGS_SHIFT 56 #define MTH_ALLOCATIONS_USER_TAG_SHIFT 24 #define MTH_ALLOCATIONS_FLAGS(longlongvar) (uint32_t)((uint64_t)(longlongvar) >> MTH_ALLOCATIONS_FLAGS_SHIFT) #define MTH_ALLOCATIONS_VM_USER_TAG(flags) (((flags)&VM_FLAGS_ALIAS_MASK) >> MTH_ALLOCATIONS_USER_TAG_SHIFT) #define MTH_ALLOCATIONS_FLAGS_AND_USER_TAG(longlongvar) \ (uint32_t)(MTH_ALLOCATIONS_FLAGS(longlongvar) | (((uint64_t)(longlongvar)&0x00FF000000000000ull) >> MTH_ALLOCATIONS_USER_TAG_SHIFT)) #define MTH_ALLOCATIONS_OFFSET_MASK 0x0000FFFFFFFFFFFFull #define MTH_ALLOCATIONS_OFFSET(longlongvar) ((longlongvar)&MTH_ALLOCATIONS_OFFSET_MASK) #define MTH_ALLOCATIONS_OFFSET_AND_FLAGS(longlongvar, type_flags) \ (((uint64_t)(longlongvar)&MTH_ALLOCATIONS_OFFSET_MASK) | ((uint64_t)(type_flags) << MTH_ALLOCATIONS_FLAGS_SHIFT) | (((uint64_t)(type_flags)&0xFF000000ull) << MTH_ALLOCATIONS_USER_TAG_SHIFT)) #define MTH_ALLOCATIONS_SIZE_SHIFT 36 // 移动环境下内存分配较小,可用 30bit 来保存单一对象的分配内存大小 #define MTH_ALLOCATIONS_SIZE(longlongvar) (uint32_t)((uint64_t)(longlongvar) >> MTH_ALLOCATIONS_SIZE_SHIFT) #define MTH_ALLOCATIONS_CATEGORY_MASK 0x0000FFFFFFFFFull #define MTH_ALLOCATIONS_CATEGORY(longlongvar) ((longlongvar)&MTH_ALLOCATIONS_CATEGORY_MASK) #define MTH_ALLOCATIONS_CATEGORY_AND_SIZE(longlongvar, size) \ (((uint64_t)(longlongvar)&MTH_ALLOCATIONS_CATEGORY_MASK) | ((uint64_t)(size) << MTH_ALLOCATIONS_SIZE_SHIFT)) /* Macro used to disguise addresses so that leak finding can work */ #define MTH_ALLOCATIONS_DISGUISE(address) ((address) ^ 0x00005555) /* nicely idempotent */ typedef struct _mtha_splay_tree_node { struct { uint32_t parent : 21; // max for 2097152 pointer. uint32_t left : 21; // uint32_t right : 21; uint32_t extra : 1; // for other use } index; struct { uint64_t addr : 36; uint32_t cnt : 28; } addr_cnt; uint64_t category_and_size; // top 30 bits are the size. uint64_t stackid_and_flags; // top 8 bits are actually the flags! } mtha_splay_tree_node; typedef struct _mtha_splay_tree { uint32_t root_index; uint32_t node_index; uint32_t max_index; FILE *mmap_fp; size_t mmap_size; uint32_t nextInsertIndex; mtha_splay_tree_node *node; } mtha_splay_tree; mtha_splay_tree *mtha_splay_tree_read_from_mmapfile(const char *path); mtha_splay_tree *mtha_splay_tree_create_on_mmapfile(size_t entry_count, const char *path); mtha_splay_tree *mtha_expand_splay_tree(mtha_splay_tree *tree); mtha_splay_tree *mtha_splay_tree_create(size_t entry_count); bool mtha_splay_tree_insert(mtha_splay_tree *tree, uint64_t addr, uint64_t stackid_and_flags, uint64_t category_and_size); uint32_t mtha_splay_tree_search(mtha_splay_tree *tree, vm_address_t addr, bool splay); mtha_splay_tree_node mtha_splay_tree_delete(mtha_splay_tree *tree, vm_address_t addr); void mtha_splay_tree_close(mtha_splay_tree *tree); #ifdef __cplusplus } #endif #endif /* mtha_splay_tree_h */ <|start_filename|>MTHawkeye/DefaultPlugins/MTRunHawkeyeInOneLine.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/14 // Created by: EuanC // #import <Foundation/Foundation.h> #import "MTHawkeyeDefaultPlugins.h" NS_ASSUME_NONNULL_BEGIN /** Run Hawkeye shortly and simply. If you need custom plugins, see how `start` work, make your own start. */ @interface MTRunHawkeyeInOneLine : NSObject /** If you wanna start with custom plugins, implement your own start method. */ + (void)start; + (void)stop; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/NetworkPlugins/HawkeyeUI/MTHNetworkWaterfallViewController.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 17/07/2017 // Created by: EuanC // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @class MTHNetworkTransaction; @protocol MTHNetworkWaterfallDataSource - (NSTimeInterval)timelineStartAt; - (NSTimeInterval)timelineDuration; - (nullable NSArray<MTHNetworkTransaction *> *)networkTransactions; - (NSInteger)requestIndexFocusOnCurrently; - (nullable NSArray<NSNumber *> *)currentOnViewIndexArray; - (nullable MTHNetworkTransaction *)transactionFromRequestIndex:(NSInteger)requestIndex; @end @interface MTHNetworkWaterfallViewController : UIViewController @property (nonatomic, strong) id<MTHNetworkWaterfallDataSource> dataSource; - (instancetype)initWithViewModel:(id<MTHNetworkWaterfallDataSource>)dataSource; - (void)reloadData; - (void)updateContentInset; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/TimeConsumingPlugins/UITimeProfiler/HawkeyeCore/MTHUITimeProfilerHawkeyeAdaptor.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/20 // Created by: EuanC // #import <Foundation/Foundation.h> #import <MTHawkeye/MTHawkeyePlugin.h> NS_ASSUME_NONNULL_BEGIN extern NSNotificationName kMTHawkeyeNotificationNameFirstVCDidAppeared; extern BOOL mthawkeye_VCTraceIgnoreSystemVC; // default yes. @class MTHViewControllerAppearRecord; @class MTHTimeIntervalCustomEventRecord; @interface MTHUITimeProfilerHawkeyeAdaptor : NSObject <MTHawkeyePlugin> + (NSArray<MTHViewControllerAppearRecord *> *)readViewControllerAppearedRecords; + (NSArray<MTHTimeIntervalCustomEventRecord *> *)readCustomEventRecords; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/NetworkPlugins/HawkeyeUI/MTHNetworkHistoryViewCell.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 17/07/2017 // Created by: EuanC // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN extern NSString *const MTNetworkHistoryViewCellIdentifier; typedef NS_ENUM(NSInteger, MTHNetworkHistoryViewCellStatus) { MTHNetworkHistoryViewCellStatusDefault = 0, // 普通状态 MTHNetworkHistoryViewCellStatusOnFocus = 1, // 当前焦点所在请求记录cell MTHNetworkHistoryViewCellStatusOnWaterfall = 2, // 当前在 waterfall 视图可见的请求对应的请求记录 cell }; @class MTHNetworkTransaction; @class MTHNetworkTaskAdvice; @protocol MTHNetworkHistoryViewCellDelegate; @interface MTHNetworkHistoryViewCell : UITableViewCell @property (nonatomic, strong) MTHNetworkTransaction *transaction; @property (nonatomic, strong, nullable) NSArray<MTHNetworkTaskAdvice *> *advices; @property (nonatomic, weak, nullable) id<MTHNetworkHistoryViewCellDelegate> delegate; @property (nonatomic, assign) MTHNetworkHistoryViewCellStatus status; @property (nonatomic, copy, nullable) NSSet<NSString *> *warningAdviceTypeIDs; + (CGFloat)preferredCellHeight; @end @protocol MTHNetworkHistoryViewCellDelegate <NSObject> - (void)mt_networkHistoryViewCellDidTappedDetail:(MTHNetworkHistoryViewCell *)cell; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/MemoryPlugins/LivingObjectSniffer/Core/MTHLivingObjectSniffer.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/12/6 // Created by: EuanC // #import <Foundation/Foundation.h> #import "MTHLivingObjectInfo.h" #import "MTHLivingObjectShadow.h" NS_ASSUME_NONNULL_BEGIN @interface MTHLivingObjectShadowPackageInspectResultItem : NSObject @property (nonatomic, strong) MTHLivingObjectGroupInClass *theGroupInClass; @property (nonatomic, copy) NSArray<MTHLivingObjectInfo *> *livingObjectsNew; @end @interface MTHLivingObjectShadowPackageInspectResult : NSObject @property (nonatomic, copy) NSArray<MTHLivingObjectShadowPackageInspectResultItem *> *items; @property (nonatomic, strong) MTHLivingObjectShadowTrigger *trigger; @end /****************************************************************************/ #pragma mark - @protocol MTHLivingObjectSnifferDelegate; @interface MTHLivingObjectSniffer : NSObject @property (nonatomic, readonly, nullable) NSArray<MTHLivingObjectGroupInClass *> *livingObjectGroupsInClass; @property (nonatomic, strong) NSMutableArray<NSString *> *ignoreList; - (instancetype)init; - (void)addDelegate:(id<MTHLivingObjectSnifferDelegate>)delegate; - (void)removeDelegate:(id<MTHLivingObjectSnifferDelegate>)delegate; /** All the shadows in shadowPackage are expected to all released after `delayInSeconds`. */ - (void)sniffWillReleasedLivingObjectShadowPackage:(MTHLivingObjectShadowPackage *)shadowPackage expectReleasedIn:(NSTimeInterval)delayInSeconds triggerInfo:(MTHLivingObjectShadowTrigger *)trigger; - (void)sniffLivingViewShadow:(MTHLivingObjectShadow *)shadow; @end @protocol MTHLivingObjectSnifferDelegate <NSObject> @required - (void)livingObjectSniffer:(MTHLivingObjectSniffer *)sniffer didSniffOutResult:(MTHLivingObjectShadowPackageInspectResult *)result; @end NS_ASSUME_NONNULL_END <|start_filename|>MTHawkeye/MemoryPlugins/Allocations/Core/mtha_allocate_logging.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/7/25 // Created by: EuanC // #ifndef mtha_memory_allocate_logging_h #define mtha_memory_allocate_logging_h #include <mach/mach.h> #include <stdbool.h> #include <stdio.h> #include <sys/syslimits.h> #include "mtha_backtrace_uniquing_table.h" #include "mtha_splay_tree.h" #define MTH_ALLOCATIONS_MAX_STACK_SIZE 200 #define mth_allocations_type_free 0 #define mth_allocations_type_generic 1 /* anything that is not allocation/deallocation */ #define mth_allocations_type_alloc 2 /* malloc, realloc, etc... */ #define mth_allocations_type_dealloc 4 /* free, realloc, etc... */ #define mth_allocations_type_vm_allocate 16 /* vm_allocate or mmap */ #define mth_allocations_type_vm_deallocate 32 /* vm_deallocate or munmap */ #define mth_allocations_type_mapped_file_or_shared_mem 128 // The valid flags include those from VM_FLAGS_ALIAS_MASK, which give the user_tag of allocated VM regions. #define mth_allocations_valid_type_flags ( \ mth_allocations_type_generic | mth_allocations_type_alloc | mth_allocations_type_dealloc | mth_allocations_type_vm_allocate | mth_allocations_type_vm_deallocate | mth_allocations_type_mapped_file_or_shared_mem | VM_FLAGS_ALIAS_MASK); // Following flags are absorbed by stack_logging_log_stack() #define mth_allocations_flag_zone 8 /* NSZoneMalloc, etc... */ #define mth_allocations_flag_cleared 64 /* for NewEmptyHandle */ #ifdef __cplusplus extern "C" { #endif // MARK: - Record files info extern char mtha_records_cache_dir[PATH_MAX]; /**< the directory to cache all the records, should be set before start. */ extern const char *mtha_malloc_records_filename; /**< the heap records filename */ extern const char *mtha_vm_records_filename; /**< the vm records filename */ extern const char *mtha_stacks_records_filename; /**< the backtrace records filename */ // MARK: - Allocations Logging extern boolean_t mtha_memory_allocate_logging_enabled; /* when clear, no logging takes place */ extern boolean_t mth_allocations_need_sys_frame; /**< record system libraries frames when record backtrace, default false*/ extern uint32_t mth_allocations_stack_record_max_depth; /**< stack record max depth, default 50 */ // for storing/looking up allocations that haven't yet be written to disk; consistent size across 32/64-bit processes. // It's important that these fields don't change alignment due to the architecture because they may be accessed from an // analyzing process with a different arch - hence the pragmas. #pragma pack(push, 4) typedef struct { mtha_splay_tree *malloc_records = NULL; /**< store Heap memory allocations info, each item contains ptr,size,stackid */ mtha_splay_tree *vm_records = NULL; /**< store other vm memory allocations info, each item contains ptr,size,stackid */ mtha_backtrace_uniquing_table *backtrace_records = NULL; /**< store the stacks when allocate memory */ } mth_allocations_record_raw; #pragma pack(pop) extern mth_allocations_record_raw *mtha_recording; /**< single-thread access variables */ boolean_t mtha_prepare_memory_allocate_logging(void); /**< prepare logging before start */ /* when operating `mtha_recording`, you should make sure it's thread safe. use locking method below to keep it safe. */ void mtha_memory_allocate_logging_lock(void); void mtha_memory_allocate_logging_unlock(void); typedef void(mtha_malloc_logger_t)(uint32_t type_flags, uintptr_t zone_ptr, uintptr_t arg2, uintptr_t arg3, uintptr_t return_val, uint32_t num_hot_to_skip); extern mtha_malloc_logger_t *malloc_logger; extern mtha_malloc_logger_t *__syscall_logger; void mtha_allocate_logging(uint32_t type_flags, uintptr_t zone_ptr, uintptr_t size, uintptr_t ptr_arg, uintptr_t return_val, uint32_t num_hot_to_skip); // MARK: - Single chunk malloc detect typedef void (^mtha_chunk_malloc_block)(size_t bytes, vm_address_t *stack_frames, size_t frames_count); void mtha_start_single_chunk_malloc_detector(size_t threshold_in_bytes, mtha_chunk_malloc_block callback); void mtha_config_single_chunk_malloc_threshold(size_t threshold_in_bytes); void mtha_stop_single_chunk_malloc_detector(void); #ifdef __cplusplus } #endif #endif /* mtha_memory_allocate_logging_h */ <|start_filename|>MTHawkeye/EnergyPlugins/CPUTrace/Core/MTHCPUTraceHighLoadRecord.h<|end_filename|> // // Copyright (c) 2008-present, Meitu, Inc. // All rights reserved. // // This source code is licensed under the license found in the LICENSE file in // the root directory of this source tree. // // Created on: 2018/121/18 // Created by: Zed // #import <Foundation/Foundation.h> #import <mach/mach.h> #import <vector> NS_ASSUME_NONNULL_BEGIN struct MTH_CPUTraceThreadIdAndUsage { thread_t traceThread; double cpuUsage; }; class MTH_CPUTraceStackFramesNode { public: uintptr_t stackframeAddr = 0; uint32_t calledCount = 0; std::vector<MTH_CPUTraceStackFramesNode *> children; public: MTH_CPUTraceStackFramesNode(){}; ~MTH_CPUTraceStackFramesNode(){}; void resetSubCalls(); inline bool isEquralToStackFrameNode(MTH_CPUTraceStackFramesNode *node) { return this->stackframeAddr == node->stackframeAddr; }; MTH_CPUTraceStackFramesNode *addSubCallNode(MTH_CPUTraceStackFramesNode *node); NSArray<NSDictionary *> *json(); NSString *jsonString(); }; @interface MTHCPUTraceHighLoadRecord : NSObject @property (nonatomic, assign) CFAbsoluteTime startAt; /**< The cpu high load record start at. */ @property (nonatomic, assign) CFAbsoluteTime lasting; /**< How long the cpu high load lasting */ @property (nonatomic, assign) float averageCPUUsage; /**< The average cpu usage during the high load */ @end NS_ASSUME_NONNULL_END
JonyFang/MTHawkeye
<|start_filename|>framework/src/main/java/com/github/ma1co/openmemories/framework/ImageInfo.java<|end_filename|> package com.github.ma1co.openmemories.framework; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Context; import android.database.Cursor; import android.media.ExifInterface; import android.net.Uri; import android.provider.MediaStore; import com.sony.scalar.graphics.AvindexGraphics; import com.sony.scalar.media.AvindexContentInfo; import com.sony.scalar.provider.AvindexStore; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Holds information about an image. * This is the abstract base class. * Create an instance using {@link MediaManager#getImageInfo}. */ public abstract class ImageInfo { /** * ImageInfo implementation used on Sony cameras. * Instantiate using {@link MediaManager#getImageInfo}. */ public static class CameraImageInfo extends ImageInfo { private final AvindexContentInfo info; private CameraImageInfo(ContentResolver resolver, Uri uri, long id) { super(resolver, uri, id); info = readInfo(); } private AvindexContentInfo readInfo() { return AvindexStore.Images.Media.getImageInfo(getData()); } private String getData() { return cursor.getString(cursor.getColumnIndexOrThrow(AvindexStore.Images.Media.DATA)); } @Override public String getFilename() { return info.getAttribute(AvindexContentInfo.TAG_DCF_TBL_FILE_NAME); } @Override public String getFolder() { return info.getAttribute(AvindexContentInfo.TAG_DCF_TBL_DIR_NAME); } @Override public Date getDate() { try { return new SimpleDateFormat("yyyy:MM:dd HH:mm:ss").parse(info.getAttribute(AvindexContentInfo.TAG_DATETIME)); } catch (ParseException e) { return null; } } @Override public int getWidth() { return info.getAttributeInt(AvindexContentInfo.TAG_IMAGE_WIDTH, 0); } @Override public int getHeight() { return info.getAttributeInt(AvindexContentInfo.TAG_IMAGE_LENGTH, 0); } @Override public double getAperture() { return info.getAttributeDouble(AvindexContentInfo.TAG_APERTURE, 0); } @Override public double getExposureTime() { return info.getAttributeDouble(AvindexContentInfo.TAG_EXPOSURE_TIME, 0); } @Override public double getFocalLength() { return info.getAttributeDouble(AvindexContentInfo.TAG_FOCAL_LENGTH, 0); } @Override public int getIso() { return info.getAttributeInt(AvindexContentInfo.TAG_ISO, 0); } @Override public int getOrientation() { return info.getAttributeInt(AvindexContentInfo.TAG_ORIENTATION, 0); } @Override public InputStream getThumbnail() { return new ByteArrayInputStream(info.getThumbnail()); } @Override public InputStream getPreviewImage() { return new ByteArrayInputStream(AvindexGraphics.getScreenNail(getData())); } @Override public InputStream getFullImage() { return AvindexStore.Images.Media.getJpegImageInputStream(resolver, uri, id); } } /** * ImageInfo implementation used on non-Sony devices. * Instantiate using {@link MediaManager#getImageInfo}. */ public static class AndroidImageInfo extends ImageInfo { private final ExifInterface exif; private AndroidImageInfo(ContentResolver resolver, Uri uri, long id) { super(resolver, uri, id); exif = readExif(); } private ExifInterface readExif() { try { return new ExifInterface(getData()); } catch (IOException e) { return null; } } private String getData() { return cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)); } @Override public String getFilename() { return cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME)); } @Override public String getFolder() { return cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME)); } @Override public Date getDate() { return new Date(cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_TAKEN))); } @Override public int getWidth() { return cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.WIDTH)); } @Override public int getHeight() { return cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.HEIGHT)); } @Override public double getAperture() { return exif != null ? exif.getAttributeDouble(ExifInterface.TAG_APERTURE, 0) : 0; } @Override public double getExposureTime() { return exif != null ? exif.getAttributeDouble(ExifInterface.TAG_EXPOSURE_TIME, 0) : 0; } @Override public double getFocalLength() { return exif != null ? exif.getAttributeDouble(ExifInterface.TAG_FOCAL_LENGTH, 0) : 0; } @Override public int getIso() { return exif != null ? exif.getAttributeInt(ExifInterface.TAG_ISO, 0) : 0; } @Override public int getOrientation() { return exif != null ? exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0) : 0; } @Override public InputStream getThumbnail() { Cursor cursor = MediaStore.Images.Thumbnails.queryMiniThumbnail(resolver, id, MediaStore.Images.Thumbnails.MINI_KIND, null); if (cursor != null && cursor.moveToFirst()) { long thumbId = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID)); Uri thumbUri = ContentUris.withAppendedId(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, thumbId); try { return resolver.openInputStream(thumbUri); } catch (IOException e) { } } byte[] exifThumbnail = exif.getThumbnail(); if (exifThumbnail != null) return new ByteArrayInputStream(exifThumbnail); return null; } @Override public InputStream getPreviewImage() { return getFullImage(); } @Override public InputStream getFullImage() { try { return resolver.openInputStream(imageUri); } catch (IOException e) { return null; } } } /** * Creates a new MediaManager instance. * You probably want to use {@link MediaManager#getImageInfo} instead. */ public static ImageInfo create(Context context, Uri uri, long id) { ContentResolver resolver = context.getApplicationContext().getContentResolver(); return DeviceInfo.getInstance().isCamera() ? new CameraImageInfo(resolver, uri, id) : new AndroidImageInfo(resolver, uri, id); } protected final ContentResolver resolver; protected final Uri uri; protected final long id; protected final Uri imageUri; protected final Cursor cursor; private ImageInfo(ContentResolver resolver, Uri uri, long id) { this.resolver = resolver; this.uri = uri; this.id = id; imageUri = ContentUris.withAppendedId(uri, id); cursor = resolver.query(imageUri, null, null, null, null); if (!cursor.moveToFirst()) throw new IllegalArgumentException("Image not found"); } /** * Returns the unique id of the image */ public long getImageId() { return id; } /** * Returns the image's filename, e.g. DSC00001.JPG */ public abstract String getFilename(); /** * Returns the name of the folder containing the image, e.g. 100MSDCF */ public abstract String getFolder(); /** * Returns the date the picture was taken */ public abstract Date getDate(); /** * Returns the image's width */ public abstract int getWidth(); /** * Returns the image's height */ public abstract int getHeight(); /** * Returns the aperture, e.g. 8.0 (or 0 if unknown) */ public abstract double getAperture(); /** * Returns the exposure time in seconds, e.g. 0.008 (or 0 if unknown) */ public abstract double getExposureTime(); /** * Returns the focal length in mm, e.g. 50 (or 0 if unknown) */ public abstract double getFocalLength(); /** * Returns the ISO value, e.g. 100 (or 0 if unknown) */ public abstract int getIso(); /** * Returns the exif orientation of the image */ public abstract int getOrientation(); /** * Returns a thumbnail image, typically 160x120px. Might be null. */ public abstract InputStream getThumbnail(); /** * Returns a preview image, typically 1616x1080px. Might be null. */ public abstract InputStream getPreviewImage(); /** * Returns the full image. Returns null for RAW images. */ public abstract InputStream getFullImage(); } <|start_filename|>framework/src/main/java/com/github/ma1co/openmemories/framework/MediaManager.java<|end_filename|> package com.github.ma1co.openmemories.framework; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.provider.MediaStore; import com.sony.scalar.provider.AvindexStore; /** * Query the images on the memory card. * This is the abstract base class. * Create an instance using {@link #create}. */ public abstract class MediaManager { /** * MediaManager implementation used on Sony cameras. * Instantiate using {@link MediaManager#create}. */ public static class CameraMediaManager extends MediaManager { private CameraMediaManager(Context context) { super(context, AvindexStore.Images.Media.EXTERNAL_CONTENT_URI, AvindexStore.Images.Media._ID, AvindexStore.Images.Media.CONTENT_CREATED_UTC_DATE_TIME); } } /** * MediaManager implementation used on non-Sony devices. * Instantiate using {@link MediaManager#create}. */ public static class AndroidMediaManager extends MediaManager { private AndroidMediaManager(Context context) { super(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, MediaStore.Images.Media._ID, MediaStore.Images.Media.DATE_TAKEN); } } /** * Creates a new MediaManager instance */ public static MediaManager create(Context context) { if (DeviceInfo.getInstance().isCamera()) return new CameraMediaManager(context.getApplicationContext()); else return new AndroidMediaManager(context.getApplicationContext()); } private final Context context; private final Uri uri; private final String idField; private final String dateField; private MediaManager(Context context, Uri uri, String idField, String dateField) { this.context = context; this.uri = uri; this.idField = idField; this.dateField = dateField; } /** * Returns the Uri for the image ContentProvider */ public Uri getImageContentUri() { return uri; } private Cursor queryImages(String sortOrder) { return context.getContentResolver().query(uri, new String[] { idField }, null, null, sortOrder); } /** * Returns a cursor over all images, default sort order. Use {@link #getImageInfo(Cursor)} to get more information * about the images. */ public Cursor queryImages() { return queryImages(null); } /** * Returns a cursor over all images, newest images coming first. Use {@link #getImageInfo(Cursor)} to get more * information about the images. */ public Cursor queryNewestImages() { return queryImages(dateField + " DESC"); } /** * Returns a cursor over all images, oldest images coming first. Use {@link #getImageInfo(Cursor)} to get more * information about the images. */ public Cursor queryOldestImages() { return queryImages(dateField + " ASC"); } /** * Returns the unique id of the image pointed to by the cursor */ public long getImageId(Cursor cursor) { return cursor.getLong(cursor.getColumnIndexOrThrow(idField)); } /** * Creates a new {@link ImageInfo} instance for the given image id */ public ImageInfo getImageInfo(long id) { return ImageInfo.create(context, uri, id); } /** * Creates a new {@link ImageInfo} instance for the image pointed to by the cursor */ public ImageInfo getImageInfo(Cursor cursor) { return getImageInfo(getImageId(cursor)); } } <|start_filename|>framework/src/main/java/com/github/ma1co/openmemories/framework/DisplayManager.java<|end_filename|> package com.github.ma1co.openmemories.framework; import android.content.Context; import android.graphics.Point; import android.util.DisplayMetrics; import android.view.WindowManager; import com.github.ma1co.openmemories.util.BiMap; import com.sony.scalar.sysutil.didep.Gpelibrary; import java.util.ArrayList; import java.util.List; /** * Access information about the device's displays. * This is the implementation used on non-Sony devices. * Create an instance using {@link #create}. * All instances have to be released before the app pauses (see {@link #release()}). */ public class DisplayManager { /** * DisplayManager implementation used on Sony cameras. * Instantiate using {@link DisplayManager#create}. */ public static class CameraDisplayManager extends DisplayManager { private com.sony.scalar.hardware.avio.DisplayManager manager; private final BiMap<Gpelibrary.GS_FRAMEBUFFER_TYPE, ColorDepth> colorDepthMap; private final BiMap<String, Display> displayMap; private final BiMap<Integer, Point> aspectRatioMap; private CameraDisplayManager(Context context) { this(context, new com.sony.scalar.hardware.avio.DisplayManager()); } private CameraDisplayManager(Context context, com.sony.scalar.hardware.avio.DisplayManager manager) { super(context); this.manager = manager; manager.setDisplayStatusListener(new com.sony.scalar.hardware.avio.DisplayManager.DisplayEventListener() { @Override public void onDeviceStatusChanged(int event) { handleStatusChange(event); } }); colorDepthMap = new BiMap<Gpelibrary.GS_FRAMEBUFFER_TYPE, ColorDepth>(); colorDepthMap.put(Gpelibrary.GS_FRAMEBUFFER_TYPE.ABGR8888, ColorDepth.HIGH); colorDepthMap.put(Gpelibrary.GS_FRAMEBUFFER_TYPE.RGBA4444, ColorDepth.LOW); displayMap = new BiMap<String, Display>(); displayMap.put(com.sony.scalar.hardware.avio.DisplayManager.DEVICE_ID_PANEL, Display.SCREEN); displayMap.put(com.sony.scalar.hardware.avio.DisplayManager.DEVICE_ID_FINDER, Display.FINDER); displayMap.put(com.sony.scalar.hardware.avio.DisplayManager.DEVICE_ID_HDMI, Display.HDMI); displayMap.put(com.sony.scalar.hardware.avio.DisplayManager.DEVICE_ID_NONE, Display.NONE); aspectRatioMap = new BiMap<Integer, Point>(); aspectRatioMap.put(com.sony.scalar.hardware.avio.DisplayManager.ASPECT_RATIO_3_2, new Point(3, 2)); aspectRatioMap.put(com.sony.scalar.hardware.avio.DisplayManager.ASPECT_RATIO_4_3, new Point(4, 3)); aspectRatioMap.put(com.sony.scalar.hardware.avio.DisplayManager.ASPECT_RATIO_5_3, new Point(5, 3)); aspectRatioMap.put(com.sony.scalar.hardware.avio.DisplayManager.ASPECT_RATIO_11_9, new Point(11, 9)); aspectRatioMap.put(com.sony.scalar.hardware.avio.DisplayManager.ASPECT_RATIO_16_9, new Point(16, 9)); } private void handleStatusChange(int event) { switch (event) { case com.sony.scalar.hardware.avio.DisplayManager.EVENT_SWITCH_DEVICE: Display display = getActiveDisplay(); for (Listener listener : listeners) listener.displayChanged(display); break; } } @Override public void setColorDepth(ColorDepth colorDepth) { Gpelibrary.changeFrameBufferPixel(colorDepthMap.getBackward(colorDepth, Gpelibrary.GS_FRAMEBUFFER_TYPE.RGBA4444)); } @Override public DisplayInfo getDisplayInfo(Display display) { String d = displayMap.getBackward(display, com.sony.scalar.hardware.avio.DisplayManager.DEVICE_ID_NONE); com.sony.scalar.hardware.avio.DisplayManager.DeviceInfo info = manager.getDeviceInfo(d); Point aspect = aspectRatioMap.getForward(info.aspect, new Point(0, 1)); return new DisplayInfo(info.res_w, info.res_h, 1f * aspect.x / aspect.y); } @Override public Display getActiveDisplay() { return displayMap.getForward(manager.getActiveDevice(), Display.NONE); } @Override public void setActiveDisplay(Display display) { String d = displayMap.getBackward(display, com.sony.scalar.hardware.avio.DisplayManager.DEVICE_ID_NONE); manager.switchDisplayOutputTo(d); } @Override public void release() { manager.releaseDisplayStatusListener(); manager.finish(); manager = null; } } /** * Color depth enum (corresponds to ARGB_8888 and ARGB_4444) */ public enum ColorDepth { HIGH, LOW; } /** * Enumerates all display types */ public enum Display { SCREEN, FINDER, HDMI, NONE; } /** * This class holds information about a display's dimensions */ public class DisplayInfo { /** * The display's width, in pixels */ public final int width; /** * The display's height, in pixels */ public final int height; /** * The display's physical aspect ratio (width / height). * Divide by the frame buffer's aspect ratio to get the pixel aspect ratio. */ public final float aspectRatio; public DisplayInfo(int width, int height, float aspectRatio) { this.width = width; this.height = height; this.aspectRatio = aspectRatio; } } /** * Listener interface to listen to DisplayManager events */ public interface Listener { /** * This method is called when the active display changes */ void displayChanged(Display display); } /** * Creates a new DisplayManager instance. * All instances have to be released before the app pauses (see {@link #release()}). */ public static DisplayManager create(Context context) { if (DeviceInfo.getInstance().isCamera()) return new CameraDisplayManager(context); else return new DisplayManager(context); } private android.view.Display display; protected final List<Listener> listeners = new ArrayList<Listener>(); private DisplayManager(Context context) { display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); } /** * Register a new event listener */ public void addListener(Listener listener) { listeners.add(listener); } /** * Unregister an event listener */ public void removeListener(Listener listener) { listeners.remove(listener); } /** * Set the color depth of the frame buffer */ public void setColorDepth(ColorDepth colorDepth) { } /** * Get the dimensions of the specified display */ public DisplayInfo getDisplayInfo(Display display) { DisplayMetrics metrics = new DisplayMetrics(); this.display.getMetrics(metrics); return new DisplayInfo(metrics.widthPixels, metrics.heightPixels, (metrics.widthPixels / metrics.xdpi) / (metrics.heightPixels / metrics.ydpi)); } /** * Get the type of the active display */ public Display getActiveDisplay() { return Display.SCREEN; } /** * Switch to the specified display */ public void setActiveDisplay(Display display) { } /** * Get the dimensions of the active display */ public DisplayInfo getActiveDisplayInfo() { return getDisplayInfo(getActiveDisplay()); } /** * Get the dimensions of the frame buffer */ public DisplayInfo getFrameBufferInfo() { DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); return new DisplayInfo(metrics.widthPixels, metrics.heightPixels, 1f * metrics.widthPixels / metrics.heightPixels); } /** * Release this instance. * All instances have to be released before the app pauses. */ public void release() { display = null; } } <|start_filename|>framework/src/main/java/com/github/ma1co/openmemories/framework/DeviceInfo.java<|end_filename|> package com.github.ma1co.openmemories.framework; import android.os.Build; import com.github.ma1co.openmemories.util.BiMap; import com.sony.scalar.sysutil.ScalarProperties; /** * Access the device's non-changing properties (e.g. model name, serial number, firmware version). * This is the implementation used on non-Sony devices. * Retrieve the appropriate instance using {@link #getInstance()}. */ public class DeviceInfo { /** * DeviceInfo implementation used on Sony cameras. * The properties are read from the ScalarProperties API. * Instantiate using {@link DeviceInfo#getInstance()}. */ public static class CameraDeviceInfo extends DeviceInfo { private final BiMap<Integer, Category> categoryMap; private CameraDeviceInfo() { categoryMap = new BiMap<Integer, Category>(); categoryMap.put(ScalarProperties.INTVAL_CATEGORY_ILDC_A, Category.A_MOUNT_CAMERA); categoryMap.put(ScalarProperties.INTVAL_CATEGORY_ILDC_E, Category.E_MOUNT_CAMERA); categoryMap.put(ScalarProperties.INTVAL_CATEGORY_DSC, Category.STILL_CAMERA); categoryMap.put(ScalarProperties.INTVAL_CATEGORY_CAM, Category.ACTION_CAMERA); } private int getInt(String key) { return ScalarProperties.getInt(key); } private String getString(String key) { return ScalarProperties.getString(key); } private String[] getPlatform() { String[] platform = getString(ScalarProperties.PROP_VERSION_PLATFORM).split("\\."); if (platform.length != 2) throw new RuntimeException("Platform property has wrong format"); return platform; } @Override public String getModel() { return getString(ScalarProperties.PROP_MODEL_NAME); } @Override public Category getCategory() { return categoryMap.getForward(getInt(ScalarProperties.PROP_MODEL_CATEGORY), Category.OTHER); } @Override public String getProductCode() { return getString(ScalarProperties.PROP_MODEL_CODE); } @Override public String getSerialNumber() { return getString(ScalarProperties.PROP_MODEL_SERIAL_CODE); } @Override public String getFirmwareVersion() { return ScalarProperties.getFirmwareVersion(); } @Override public int getHardwareVersion() { return Integer.parseInt(getPlatform()[0]); } @Override public int getApiVersion() { return Integer.parseInt(getPlatform()[1]); } } /** * Camera category enum */ public enum Category { A_MOUNT_CAMERA, E_MOUNT_CAMERA, STILL_CAMERA, ACTION_CAMERA, OTHER; } private static final String CAMERA_BRAND = "sony"; private static final String CAMERA_MODEL = "ScalarA"; private static final String CAMERA_DEVICE = "dslr-diadem"; private static final Boolean isCamera = CAMERA_BRAND.equals(Build.BRAND) && CAMERA_MODEL.equals(Build.MODEL) && CAMERA_DEVICE.equals(Build.DEVICE); private static final DeviceInfo instance = isCamera ? new CameraDeviceInfo() : new DeviceInfo(); /** * Returns the DeviceInfo instance corresponding to the current device */ public static DeviceInfo getInstance() { return instance; } private DeviceInfo() { } /** * Returns true if the device was detected as a Sony camera */ public boolean isCamera() { return isCamera; } /** * Returns the device's brand (usually "sony") */ public String getBrand() { return Build.BRAND; } /** * Returns the device's model name (e.g. "ILCE-7RM2") */ public String getModel() { return Build.MODEL; } /** * Returns the device's category */ public Category getCategory() { return Category.OTHER; } /** * Returns the device's non-unique product code (usually numeric and zero-padded on the left) */ public String getProductCode() { return Build.DEVICE; } /** * Returns the device's unique serial number (usually numeric and zero-padded on the left) */ public String getSerialNumber() { return Build.SERIAL; } /** * Returns the device's firmware version (e.g. "1.00") */ public String getFirmwareVersion() { return Build.DISPLAY; } /** * Returns the device's hardware revision (1 or 2; 0 if the device isn't a Sony camera) */ public int getHardwareVersion() { return 0; } /** * Returns the revision of proprietary Sony APIs present on the device (0 if not present) */ public int getApiVersion() { return 0; } /** * Returns the Android version (usually "2.3.7" for Gingerbread or "4.1.2" for Jelly Bean) */ public String getAndroidVersion() { return Build.VERSION.RELEASE; } /** * Returns the Android SDK revision (usually 10 for Gingerbread or 16 for Jelly Bean) */ public int getAndroidSdkVersion() { return Build.VERSION.SDK_INT; } /** * Returns the internally used detailed Android build number (usually numeric) */ public String getAndroidIncrementalVersion() { return Build.VERSION.INCREMENTAL; } } <|start_filename|>framework/src/main/java/com/github/ma1co/openmemories/util/BiMap.java<|end_filename|> package com.github.ma1co.openmemories.util; import java.util.HashMap; import java.util.Map; /** * A map with quick reverse lookup. * Internally uses two HashMaps. * @param <K> key type * @param <V> value type */ public class BiMap<K, V> { private final Map<K, V> forward = new HashMap<K, V>(); private final Map<V, K> backward = new HashMap<V, K>(); /** * Stores a new entry in the BiMap * @param k key * @param v value */ public void put(K k, V v) { forward.put(k, v); backward.put(v, k); } /** * Finds the value for the specified key * @param k key * @return the value associated to the key or null if not found */ public V getForward(K k) { return forward.get(k); } /** * Finds the value for the specified key * @param k key * @param defaultV default value * @return the value associated to the key or the default if not found */ public V getForward(K k, V defaultV) { V v = getForward(k); return v != null ? v : defaultV; } /** * Finds the key for the specified value * @param v value * @return the key associated to the value or null if not found */ public K getBackward(V v) { return backward.get(v); } /** * Finds the key for the specified value * @param v value * @param defaultK default key * @return the key associated to the value or the default if not found */ public K getBackward(V v, K defaultK) { K k = getBackward(v); return k != null ? k : defaultK; } } <|start_filename|>framework/src/main/java/com/github/ma1co/openmemories/framework/DateTime.java<|end_filename|> package com.github.ma1co.openmemories.framework; import com.sony.scalar.sysutil.PlainCalendar; import com.sony.scalar.sysutil.PlainTimeZone; import com.sony.scalar.sysutil.TimeUtil; import java.util.*; /** * Query the current date and time. * This is the default Android implementation. * Retrieve the appropriate instance using {@link #getInstance()}. */ public class DateTime { /** * DateTime implementation using Sony's proprietary TimeUtil API. * The system time cannot be used, as it is not set correctly. * Instantiate using {@link DateTime#getInstance()}. */ public static class CameraDateTime extends DateTime { private CameraDateTime() { } @Override public Calendar getCurrentTime() { PlainCalendar cal = TimeUtil.getCurrentCalendar(); PlainTimeZone tz = TimeUtil.getCurrentTimeZone(); int offsetMinutes = tz.gmtDiff + tz.summerTimeDiff; TimeZone timeZone = new SimpleTimeZone(offsetMinutes * 60 * 1000, ""); Calendar calendar = new GregorianCalendar(timeZone); calendar.set(cal.year, cal.month - 1, cal.day, cal.hour, cal.minute, cal.second); calendar.add(Calendar.MINUTE, offsetMinutes); return calendar; } } private static final DateTime instance = DeviceInfo.getInstance().isCamera() ? new CameraDateTime() : new DateTime(); /** * Returns the DateTime instance corresponding to the current device */ public static DateTime getInstance() { return instance; } private DateTime() { } /** * Returns a Calendar instance containing the current time and time zone */ public Calendar getCurrentTime() { return new GregorianCalendar(); } }
ma1co/OpenMemories-Framework
<|start_filename|>util/strings_test.go<|end_filename|> package util import "testing" func TestSanitizeURI(t *testing.T) { cases := [][]string{ []string{"mongodb://example.com/", "mongodb://example.com/"}, []string{"mongodb://example.com/?appName=foo:@bar", "mongodb://example.com/?appName=foo:@bar"}, []string{"mongodb://example.com?appName=foo:@bar", "mongodb://example.com?appName=foo:@bar"}, []string{"mongodb://@example.com/", "mongodb://[**REDACTED**]@example.com/"}, []string{"mongodb://:@example.com/", "mongodb://[**REDACTED**]@example.com/"}, []string{"mongodb://user@example.com/", "mongodb://[**REDACTED**]@example.com/"}, []string{"mongodb://user:@example.com/", "mongodb://[**REDACTED**]@example.com/"}, []string{"mongodb://:pass@example.com/", "mongodb://[**REDACTED**]@example.com/"}, []string{"mongodb://user:pass@example.com/", "mongodb://[**REDACTED**]@example.com/"}, []string{"mongodb+srv://example.com/", "mongodb+srv://example.com/"}, []string{"mongodb+srv://@example.com/", "mongodb+srv://[**REDACTED**]@example.com/"}, []string{"mongodb+srv://:@example.com/", "mongodb+srv://[**REDACTED**]@example.com/"}, []string{"mongodb+srv://user@example.com/", "mongodb+srv://[**REDACTED**]@example.com/"}, []string{"mongodb+srv://user:@example.com/", "mongodb+srv://[**REDACTED**]@example.com/"}, []string{"mongodb+srv://:pass@example.com/", "mongodb+srv://[**REDACTED**]@example.com/"}, []string{"mongodb+srv://user:pass@example.com/", "mongodb+srv://[**REDACTED**]@example.com/"}, } for _, c := range cases { got := SanitizeURI(c[0]) if got != c[1] { t.Errorf("For %s: got: %s; wanted: %s", c[0], got, c[1]) } } }
sphanse99/mongo-tools-common
<|start_filename|>lib/MoveToParentMergingPlugin.js<|end_filename|> function MoveToParentMergingPlugin(chunkCount) { this.chunkCount = chunkCount || 2; } module.exports = MoveToParentMergingPlugin; MoveToParentMergingPlugin.prototype.constructor = MoveToParentMergingPlugin; function getFirstCommonParent (chunks) { var parents = []; var counts = []; for (var n = 0, chunk; chunk = chunks[n++];) { for (var m = 0, parentChunk; parentChunk = chunk.parents[m++];) { var i = parents.indexOf(parentChunk); if (i < 0) { parents.push(parentChunk); counts.push(0); i = parents.length - 1; } counts[i]++; if (counts[i] === chunks.length) { return parentChunk; } } } return null; } MoveToParentMergingPlugin.prototype.apply = function (compiler) { var chunkCount = this.chunkCount; compiler.plugin("compilation", function (compilation) { compilation.plugin("optimize-chunks", function (chunks) { var nonEntryChunks = chunks.filter(function (chunk) { return !chunk.entry; }); var modules = {}; nonEntryChunks.forEach(function (chunk) { chunk.modules.slice(0).forEach(function (module) { var request = module.request; var handle = modules[request] = modules[request] || { module: module, chunks: [] }; handle.chunks.push(chunk); }); }); for (var key in modules) { var handle = modules[key]; if (handle.chunks.length >= chunkCount) { var parent = getFirstCommonParent(handle.chunks); var module = handle.module; if (parent) { handle.chunks.forEach(function (chunk) { chunk.removeModule(module); }); if (!handle.moved) { parent.addModule(module); module.addChunk(parent); } } } } }); }); }; <|start_filename|>example/child-b.js<|end_filename|> var common = require("./common"); module.exports = "B, with " + common; <|start_filename|>example/common.js<|end_filename|> module.exports = "a common module"; <|start_filename|>example/index.js<|end_filename|> // Introduce split points for two child chunks. // Each child chunk contains a 'common' module. // That common child module will be lifted to the parent chunk (this chunk). require.ensure([], function (require) { require("./child-a"); }); require.ensure([], function (require) { require("./child-b"); }); <|start_filename|>example/output/1.bundle.js<|end_filename|> webpackJsonp([1],[ /* 0 */, /* 1 */ /***/ function(module, exports, __webpack_require__) { var common = __webpack_require__(3); module.exports = "A, with " + common; /***/ }, /* 2 */, /* 3 */ /***/ function(module, exports, __webpack_require__) { module.exports = "a common module"; /***/ } ]); <|start_filename|>example/child-a.js<|end_filename|> var common = require("./common"); module.exports = "A, with " + common; <|start_filename|>example/webpack.config.js<|end_filename|> var MoveToParentMergingPlugin = require("../"); module.exports = { entry: "./index.js", output: { path: "output", filename: "bundle.js" }, plugins: [ new MoveToParentMergingPlugin() ] };
soundcloud/move-to-parent-merging-webpack-plugin
<|start_filename|>roles/openpitrix/files/openpitrix/config/gen_helper.go<|end_filename|> // Copyright 2018 The OpenPitrix Authors. All rights reserved. // Use of this source code is governed by a Apache license // that can be found in the LICENSE file. // +build ingore package main import ( "fmt" "io/ioutil" ) const Tmpl = ` // Copyright 2018 The OpenPitrix Authors. All rights reserved. // Use of this source code is governed by a Apache license // that can be found in the LICENSE file. package config const InitialGlobalConfig = %s ` func main() { yamlContent, err := ioutil.ReadFile("./global_config.init.yaml") if err != nil { panic(err) } data := fmt.Sprintf(Tmpl, "`"+string(yamlContent)+"`") err = ioutil.WriteFile("../../pkg/config/init_global_config.go", []byte(data), 0666) if err != nil { panic(err) } }
pengcong06/ks-installer
<|start_filename|>Elastic.Console/ElasticVersion.cs<|end_filename|> // A simple version implementation based on // https://github.com/maxhauser/semver/blob/master/src/Semver/SemVersion.cs // MIT License // Copyright (c) 2013 <NAME> // // 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. using System; using System.Globalization; using System.Runtime.Serialization; using System.Security.Permissions; using System.Text.RegularExpressions; namespace Elastic { /// <summary> /// An Elastic product version /// </summary> public sealed class ElasticVersion : IEquatable<ElasticVersion>, IComparable<ElasticVersion>, IComparable { private static Regex VersionRegex = new Regex( @"^(?<major>\d+)(\.(?<minor>\d+))?(\.(?<patch>\d+))?(\-(?<pre>[0-9A-Za-z]+))?$", RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture); public ElasticVersion(object version) : this(version.ToString()) { } public ElasticVersion(string version) { var match = VersionRegex.Match(version); if (!match.Success) throw new ArgumentException(string.Format("Invalid version '{0}'", version), "version"); var major = int.Parse(match.Groups["major"].Value, CultureInfo.InvariantCulture); var minorMatch = match.Groups["minor"]; int minor = 0; if (minorMatch.Success) minor = int.Parse(minorMatch.Value, CultureInfo.InvariantCulture); var patchMatch = match.Groups["patch"]; int patch = 0; if (patchMatch.Success) patch = int.Parse(patchMatch.Value, CultureInfo.InvariantCulture); var prerelease = match.Groups["pre"].Value; this.Major = major; this.Minor = minor; this.Patch = patch; this.Prerelease = prerelease; } public ElasticVersion(int major, int minor, int patch, string prerelease) { this.Major = major; this.Minor = minor; this.Patch = patch; this.Prerelease = prerelease; } public static bool TryParse(string version, out ElasticVersion ElasticVersion) { try { ElasticVersion = new ElasticVersion(version); return true; } catch (Exception) { ElasticVersion = null; return false; } } public static bool Equals(ElasticVersion versionA, ElasticVersion versionB) { if (ReferenceEquals(versionA, null)) return ReferenceEquals(versionB, null); return versionA.Equals(versionB); } public static int Compare(ElasticVersion versionA, ElasticVersion versionB) { if (ReferenceEquals(versionA, null)) return ReferenceEquals(versionB, null) ? 0 : -1; return versionA.CompareTo(versionB); } public ElasticVersion Change(int? major = null, int? minor = null, int? patch = null, string prerelease = null) { return new ElasticVersion( major ?? this.Major, minor ?? this.Minor, patch ?? this.Patch, prerelease ?? this.Prerelease); } public int Major { get; private set; } public int Minor { get; private set; } public int Patch { get; private set; } public string Prerelease { get; private set; } public override string ToString() { var version = "" + Major + "." + Minor + "." + Patch; if (!String.IsNullOrEmpty(Prerelease)) version += "-" + Prerelease; return version; } public int CompareTo(object obj) { return CompareTo((ElasticVersion)obj); } public int CompareTo(ElasticVersion other) { if (ReferenceEquals(other, null)) return 1; var r = this.CompareByPrecedence(other); return r; } public bool PrecedenceMatches(ElasticVersion other) { return CompareByPrecedence(other) == 0; } public int CompareByPrecedence(ElasticVersion other) { if (ReferenceEquals(other, null)) return 1; var r = this.Major.CompareTo(other.Major); if (r != 0) return r; r = this.Minor.CompareTo(other.Minor); if (r != 0) return r; r = this.Patch.CompareTo(other.Patch); if (r != 0) return r; r = CompareComponent(this.Prerelease, other.Prerelease, true); return r; } static int CompareComponent(string a, string b, bool lower = false) { var aEmpty = String.IsNullOrEmpty(a); var bEmpty = String.IsNullOrEmpty(b); if (aEmpty && bEmpty) return 0; if (aEmpty) return lower ? 1 : -1; if (bEmpty) return lower ? -1 : 1; var aComps = a.Split('.'); var bComps = b.Split('.'); var minLen = Math.Min(aComps.Length, bComps.Length); for (int i = 0; i < minLen; i++) { var ac = aComps[i]; var bc = bComps[i]; int anum, bnum; var isanum = Int32.TryParse(ac, out anum); var isbnum = Int32.TryParse(bc, out bnum); int r; if (isanum && isbnum) { r = anum.CompareTo(bnum); if (r != 0) return anum.CompareTo(bnum); } else { if (isanum) return -1; if (isbnum) return 1; r = String.CompareOrdinal(ac, bc); if (r != 0) return r; } } return aComps.Length.CompareTo(bComps.Length); } public override bool Equals(object obj) { if (ReferenceEquals(obj, null)) return false; if (ReferenceEquals(this, obj)) return true; var other = (ElasticVersion)obj; return Equals(other); } public bool Equals(ElasticVersion other) { if (other == null) return false; return this.Major == other.Major && this.Minor == other.Minor && this.Patch == other.Patch && string.Equals(this.Prerelease, other.Prerelease, StringComparison.Ordinal); } public override int GetHashCode() { unchecked { int result = this.Major.GetHashCode(); result = result * 31 + this.Minor.GetHashCode(); result = result * 31 + this.Patch.GetHashCode(); result = result * 31 + this.Prerelease.GetHashCode(); return result; } } public static bool operator ==(ElasticVersion left, ElasticVersion right) { return ElasticVersion.Equals(left, right); } public static bool operator !=(ElasticVersion left, ElasticVersion right) { return !ElasticVersion.Equals(left, right); } public static bool operator >(ElasticVersion left, ElasticVersion right) { return ElasticVersion.Compare(left, right) > 0; } public static bool operator >=(ElasticVersion left, ElasticVersion right) { return left == right || left > right; } public static bool operator <(ElasticVersion left, ElasticVersion right) { return ElasticVersion.Compare(left, right) < 0; } public static bool operator <=(ElasticVersion left, ElasticVersion right) { return left == right || left < right; } } } <|start_filename|>Elastic.Console/ServerCertificateValidation.cs<|end_filename|> using System.Net.Security; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; namespace Elastic { /// <summary> /// Handlers for certificate validation /// </summary> public class ServerCertificateValidation { /// <summary> /// Skip certificate validation /// </summary> public static RemoteCertificateValidationCallback AllowAll() { return new RemoteCertificateValidationCallback(delegate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) { return true; }); } } } <|start_filename|>Elastic.Console/ElasticsearchRequestBody.cs<|end_filename|> using System; using System.Collections; namespace Elastic { /// <summary> /// An Elasticsearch API request body represented as a /// Hashtable or string /// </summary> /// <remarks> /// Allows $Body in Invoke-Elasticsearch to *not* bind to ElasticsearchRequest /// </remarks> public class ElasticsearchRequestBody { public ElasticsearchRequestBody(Hashtable input) { this.Input = input; } public ElasticsearchRequestBody(string input) { this.Input = input; } public object Input { get; private set; } } }
isabella232/powershell
<|start_filename|>src/test/java/net/bitnine/agensgraph/test/util/AgTokenizerTest.java<|end_filename|> /* * Copyright (c) 2014-2018, Bitnine Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.bitnine.agensgraph.test.util; import junit.framework.TestCase; import net.bitnine.agensgraph.util.AgTokenizer; import org.junit.Test; import java.sql.SQLException; import java.util.ArrayList; public class AgTokenizerTest extends TestCase { @Test public void testParseString() throws SQLException { String s1 = "vertex[3.1]{\"vid\": 1}"; String s2 = "edge[4.1][3.1,3.2]{\"rid\": 1}"; String s3 = "vertex[3.2]{\"vid\": 2}"; String string = "[" + s1 + "," + s2 + "," + s3 + "]"; ArrayList<String> t = AgTokenizer.tokenize(string); assertEquals(s1, t.get(0)); assertEquals(s2, t.get(1)); assertEquals(s3, t.get(2)); } @Test public void testNull() throws SQLException { String string = "[NULL,,NULL]"; ArrayList<String> t = AgTokenizer.tokenize(string); assertNull(t.get(0)); assertNull(t.get(1)); assertNull(t.get(2)); } @Test public void testEmpty() throws SQLException { String string = "[]"; ArrayList<String> t = AgTokenizer.tokenize(string); assertEquals(1, t.size()); } } <|start_filename|>src/test/java/net/bitnine/agensgraph/test/util/JsonbUtilTest.java<|end_filename|> /* * Copyright (c) 2014-2018, Bitnine Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.bitnine.agensgraph.test.util; import junit.framework.TestCase; import net.bitnine.agensgraph.util.Jsonb; import net.bitnine.agensgraph.util.JsonbUtil; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class JsonbUtilTest extends TestCase { @Test public void testArrayBuilder() { Jsonb j = JsonbUtil.createArrayBuilder() .add("") .add(0) .add(0.0) .add(false) .add(true) .addNull() .add(JsonbUtil.createArrayBuilder() .add(0)) .add(JsonbUtil.createObjectBuilder() .add("i", 0)) .build(); assertEquals("[\"\",0,0.0,false,true,null,[0],{\"i\":0}]", j.toString()); } @Test public void testObjectBuilder() { Jsonb j = JsonbUtil.createObjectBuilder() .add("s", "") .add("l", 0) .add("d", 0.0) .add("f", false) .add("t", true) .addNull("z") .add("a", JsonbUtil.createArrayBuilder() .add(0)) .add("o", JsonbUtil.createObjectBuilder() .add("i", 0)) .build(); assertNotNull(j.toString()); assertTrue(j.containsKey("z")); assertTrue(j.isNull("z")); assertFalse(j.containsKey("x")); assertTrue(j.isNull("x")); } @Test public void testCreateScalar() { Jsonb j = JsonbUtil.create("s"); assertEquals("s", j.getString()); j = JsonbUtil.create(Integer.MAX_VALUE); assertEquals(Integer.MAX_VALUE, j.getInt()); j = JsonbUtil.create(Long.MAX_VALUE); assertEquals(Long.MAX_VALUE, j.getLong()); j = JsonbUtil.create(Math.PI); assertEquals(Math.PI, j.getDouble()); j = JsonbUtil.create(false); assertFalse(j.getBoolean()); j = JsonbUtil.create(true); assertTrue(j.getBoolean()); j = JsonbUtil.createNull(); assertTrue(j.isNull()); } @Test public void testCreateArray() { Jsonb j = JsonbUtil.createArray(); assertEquals(0, j.size()); assertEquals("[]", j.toString()); j = JsonbUtil.createArray("0", "1", "2"); assertEquals(3, j.size()); assertEquals("[\"0\",\"1\",\"2\"]", j.toString()); j = JsonbUtil.createArray(0, 1, 2); assertEquals(3, j.size()); assertEquals("[0,1,2]", j.toString()); j = JsonbUtil.createArray(0L, 1L, 2L); assertEquals(3, j.size()); assertEquals("[0,1,2]", j.toString()); j = JsonbUtil.createArray(0.0, 1.0, 2.0); assertEquals("[0.0,1.0,2.0]", j.toString()); j = JsonbUtil.createArray(false, true); assertEquals(2, j.size()); assertEquals("[false,true]", j.toString()); j = JsonbUtil.createArray( JsonbUtil.create(""), JsonbUtil.create(0), JsonbUtil.create(0.0), JsonbUtil.create(false), JsonbUtil.createNull(), JsonbUtil.createArray(), JsonbUtil.createObject(), new JSONArray(), new JSONObject()); assertEquals(9, j.size()); assertEquals("[\"\",0,0.0,false,null,[],{},[],{}]", j.toString()); List<Object> a = new ArrayList<>(); a.add(""); a.add(0); a.add(0.0); a.add(false); a.add(null); a.add(JsonbUtil.createArray()); a.add(JsonbUtil.createObject()); a.add(new JSONArray()); a.add(new JSONObject()); j = JsonbUtil.createArray(a); assertEquals(9, j.size()); assertEquals("[\"\",0,0.0,false,null,[],{},[],{}]", j.toString()); } @Test public void testCreateObject() { Jsonb j = JsonbUtil.createObject(); assertEquals(0, j.size()); assertEquals("{}", j.toString()); Map<String, Object> m = new HashMap<>(); m.put("i", 0); m.put("a", new JSONArray()); m.put("o", new JSONObject()); j = JsonbUtil.createObject(m); assertEquals(3, j.size()); assertEquals("{\"a\":[],\"i\":0,\"o\":{}}", j.toString()); } @Test public void testConvertStringToNumber() { Jsonb j = JsonbUtil.create(Integer.toString(Integer.MAX_VALUE) + " "); assertEquals(Integer.MAX_VALUE, j.getInt()); j = JsonbUtil.create(Long.toString(Long.MAX_VALUE) + " "); assertEquals(Long.MAX_VALUE, j.getLong()); j = JsonbUtil.create(Double.toString(Double.MAX_VALUE) + " "); assertEquals(Double.MAX_VALUE, j.getDouble()); } } <|start_filename|>src/test/java/net/bitnine/agensgraph/test/jdbc/AgResultSetTest.java<|end_filename|> /* * Copyright (c) 2014-2018, Bitnine Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.bitnine.agensgraph.test.jdbc; import junit.framework.TestCase; import net.bitnine.agensgraph.test.TestUtil; import org.junit.Test; import org.postgresql.util.PSQLState; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class AgResultSetTest extends TestCase { private Connection conn; @Override public void setUp() throws Exception { conn = TestUtil.openDB(); } @Override public void tearDown() throws SQLException { TestUtil.closeDB(conn); } @Test public void testGetString() throws SQLException { Statement stmt = conn.createStatement(); // string ResultSet rs = stmt.executeQuery("RETURN 'Agens\\\\Graph' AS s"); assertTrue(rs.next()); assertEquals("Agens\\Graph", rs.getString(1)); assertEquals("Agens\\Graph", rs.getString("s")); assertTrue(!rs.next()); rs.close(); // SQL NULL rs = stmt.executeQuery("RETURN null AS z"); assertTrue(rs.next()); assertNull(rs.getString(1)); assertTrue(rs.wasNull()); assertNull(rs.getString("z")); assertTrue(rs.wasNull()); assertTrue(!rs.next()); rs.close(); // jsonb null rs = stmt.executeQuery("SELECT 'null'::jsonb AS z"); assertTrue(rs.next()); assertNull(rs.getString(1)); assertNull(rs.getString("z")); assertTrue(!rs.next()); rs.close(); // SQL boolean rs = stmt.executeQuery("RETURN false AS f, true AS t"); assertTrue(rs.next()); assertEquals("f", rs.getString(1)); assertEquals("f", rs.getString("f")); assertEquals("t", rs.getString(2)); assertEquals("t", rs.getString("t")); assertTrue(!rs.next()); rs.close(); // jsonb boolean rs = stmt.executeQuery("SELECT false::jsonb AS f, true::jsonb AS t"); assertTrue(rs.next()); assertEquals("false", rs.getString(1)); assertEquals("false", rs.getString("f")); assertEquals("true", rs.getString(2)); assertEquals("true", rs.getString("t")); assertTrue(!rs.next()); rs.close(); // other types rs = stmt.executeQuery("RETURN " + Long.MAX_VALUE + " AS l, " + Math.PI + " AS d, [0, 1] AS a, {k: 'v'} AS o"); assertTrue(rs.next()); assertEquals(Long.toString(Long.MAX_VALUE), rs.getString(1)); assertEquals(Long.toString(Long.MAX_VALUE), rs.getString("l")); assertEquals(Double.toString(Math.PI), rs.getString(2)); assertEquals(Double.toString(Math.PI), rs.getString("d")); assertEquals("[0, 1]", rs.getString(3)); assertEquals("[0, 1]", rs.getString("a")); assertEquals("{\"k\": \"v\"}", rs.getString(4)); assertEquals("{\"k\": \"v\"}", rs.getString("o")); assertTrue(!rs.next()); rs.close(); stmt.close(); } @Test public void testGetBoolean() throws SQLException { Statement stmt = conn.createStatement(); // SQL boolean ResultSet rs = stmt.executeQuery("SELECT false AS f, true AS t"); assertTrue(rs.next()); assertFalse(rs.getBoolean(1)); assertFalse(rs.getBoolean("f")); assertTrue(rs.getBoolean(2)); assertTrue(rs.getBoolean("t")); assertTrue(!rs.next()); rs.close(); // jsonb boolean rs = stmt.executeQuery("SELECT false::jsonb AS f, true::jsonb AS t"); assertTrue(rs.next()); assertFalse(rs.getBoolean(1)); assertFalse(rs.getBoolean("f")); assertTrue(rs.getBoolean(2)); assertTrue(rs.getBoolean("t")); assertTrue(!rs.next()); rs.close(); // SQL NULL rs = stmt.executeQuery("RETURN null AS z"); assertTrue(rs.next()); assertFalse(rs.getBoolean(1)); assertFalse(rs.getBoolean("z")); assertTrue(!rs.next()); rs.close(); // jsonb NULL rs = stmt.executeQuery("SELECT 'null'::jsonb AS z"); assertTrue(rs.next()); assertFalse(rs.getBoolean(1)); assertFalse(rs.getBoolean("z")); assertTrue(!rs.next()); rs.close(); // other types rs = stmt.executeQuery("RETURN '' AS sf, 's' AS st, 0 AS lf, 7 AS lt, 0.0 AS df, 7.7 AS dt, [] AS af, [7] AS at, {} AS of, {i: 7} AS ot"); assertTrue(rs.next()); assertFalse(rs.getBoolean(1)); assertFalse(rs.getBoolean("sf")); assertTrue(rs.getBoolean(2)); assertTrue(rs.getBoolean("st")); assertFalse(rs.getBoolean(3)); assertFalse(rs.getBoolean("lf")); assertTrue(rs.getBoolean(4)); assertTrue(rs.getBoolean("lt")); assertFalse(rs.getBoolean(5)); assertFalse(rs.getBoolean("df")); assertTrue(rs.getBoolean(6)); assertTrue(rs.getBoolean("dt")); assertFalse(rs.getBoolean(7)); assertFalse(rs.getBoolean("af")); assertTrue(rs.getBoolean(8)); assertTrue(rs.getBoolean("at")); assertFalse(rs.getBoolean(9)); assertFalse(rs.getBoolean("of")); assertTrue(rs.getBoolean(10)); assertTrue(rs.getBoolean("ot")); assertTrue(!rs.next()); rs.close(); stmt.close(); } @Test public void testGetShort() throws SQLException { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("RETURN " + Short.MAX_VALUE + " AS l, 7.7 AS d"); assertTrue(rs.next()); assertEquals(Short.MAX_VALUE, rs.getShort(1)); assertEquals(Short.MAX_VALUE, rs.getShort("l")); assertEquals(7, rs.getShort(2)); assertEquals(7, rs.getShort("d")); assertTrue(!rs.next()); rs.close(); // out of range rs = stmt.executeQuery("RETURN " + ((int) Short.MAX_VALUE + 1) + " AS l"); assertTrue(rs.next()); try { rs.getShort(1); fail("SQLExecption expected"); } catch (SQLException e) { assertEquals(PSQLState.NUMERIC_VALUE_OUT_OF_RANGE.getState(), e.getSQLState()); } try { rs.getShort("l"); fail("SQLExecption expected"); } catch (SQLException e) { assertEquals(PSQLState.NUMERIC_VALUE_OUT_OF_RANGE.getState(), e.getSQLState()); } assertTrue(!rs.next()); rs.close(); stmt.close(); } @Test public void testGetInt() throws SQLException { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("RETURN " + Integer.MAX_VALUE + " AS l, 7.7 AS d"); assertTrue(rs.next()); assertEquals(Integer.MAX_VALUE, rs.getInt(1)); assertEquals(Integer.MAX_VALUE, rs.getInt("l")); assertEquals(7, rs.getInt(2)); assertEquals(7, rs.getInt("d")); assertTrue(!rs.next()); rs.close(); // out of range rs = stmt.executeQuery("RETURN " + ((long) Integer.MAX_VALUE + 1) + " AS l"); assertTrue(rs.next()); try { rs.getInt(1); fail("SQLExecption expected"); } catch (SQLException e) { assertEquals(PSQLState.NUMERIC_VALUE_OUT_OF_RANGE.getState(), e.getSQLState()); } try { rs.getInt("l"); fail("SQLExecption expected"); } catch (SQLException e) { assertEquals(PSQLState.NUMERIC_VALUE_OUT_OF_RANGE.getState(), e.getSQLState()); } assertTrue(!rs.next()); rs.close(); stmt.close(); } @Test public void testGetLong() throws SQLException { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("RETURN " + Long.MAX_VALUE + " AS l, 7.7 AS d"); assertTrue(rs.next()); assertEquals(Long.MAX_VALUE, rs.getLong(1)); assertEquals(Long.MAX_VALUE, rs.getLong("l")); assertEquals(7, rs.getLong(2)); assertEquals(7, rs.getLong("d")); assertTrue(!rs.next()); rs.close(); // out of range rs = stmt.executeQuery("RETURN " + Long.MAX_VALUE + "0 AS l"); assertTrue(rs.next()); try { rs.getLong(1); fail("SQLExecption expected"); } catch (SQLException e) { assertEquals(PSQLState.NUMERIC_VALUE_OUT_OF_RANGE.getState(), e.getSQLState()); } try { rs.getLong("l"); fail("SQLExecption expected"); } catch (SQLException e) { assertEquals(PSQLState.NUMERIC_VALUE_OUT_OF_RANGE.getState(), e.getSQLState()); } assertTrue(!rs.next()); rs.close(); stmt.close(); } @Test public void testGetFloat() throws SQLException { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("RETURN " + Float.MAX_VALUE + " AS d"); assertTrue(rs.next()); assertEquals(Float.MAX_VALUE, rs.getFloat(1)); assertEquals(Float.MAX_VALUE, rs.getFloat("d")); assertTrue(!rs.next()); rs.close(); stmt.close(); } @Test public void testGetDouble() throws SQLException { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("RETURN " + Double.MAX_VALUE + " AS d"); assertTrue(rs.next()); assertEquals(Double.MAX_VALUE, rs.getDouble(1)); assertEquals(Double.MAX_VALUE, rs.getDouble("d")); assertTrue(!rs.next()); rs.close(); stmt.close(); } @Test public void testGetBigDecimal() throws SQLException { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("RETURN " + Double.MAX_VALUE + " AS d"); assertTrue(rs.next()); assertEquals(Double.MAX_VALUE, rs.getBigDecimal(1).doubleValue()); assertEquals(Double.MAX_VALUE, rs.getBigDecimal("d").doubleValue()); assertTrue(!rs.next()); rs.close(); stmt.close(); } @Test public void testGetStringToShort() throws SQLException { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("RETURN ' 0' AS s"); assertTrue(rs.next()); assertEquals(0, rs.getShort(1)); assertTrue(!rs.next()); rs = stmt.executeQuery("RETURN '" + Short.MAX_VALUE + "' AS s"); assertTrue(rs.next()); assertEquals(Short.MAX_VALUE, rs.getShort(1)); assertTrue(!rs.next()); rs = stmt.executeQuery("RETURN '0x' AS s"); assertTrue(rs.next()); try { rs.getShort(1); fail("SQLExecption expected"); } catch (SQLException e) { assertEquals(PSQLState.NUMERIC_VALUE_OUT_OF_RANGE.getState(), e.getSQLState()); } assertTrue(!rs.next()); rs = stmt.executeQuery("RETURN "+ Short.toString(Short.MAX_VALUE) + " AS s"); assertTrue(rs.next()); assertEquals(Short.MAX_VALUE, rs.getShort(1)); assertTrue(!rs.next()); rs.close(); stmt.close(); } @Test public void testGetStringToInt() throws SQLException { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("RETURN ' 0' AS i"); assertTrue(rs.next()); assertEquals(0, rs.getInt(1)); assertTrue(!rs.next()); rs = stmt.executeQuery("RETURN '" + Integer.MAX_VALUE + "' AS i"); assertTrue(rs.next()); assertEquals(Integer.MAX_VALUE, rs.getLong(1)); assertTrue(!rs.next()); rs = stmt.executeQuery("RETURN '0x' AS i"); assertTrue(rs.next()); try { rs.getInt(1); fail("SQLExecption expected"); } catch (SQLException e) { assertEquals(PSQLState.NUMERIC_VALUE_OUT_OF_RANGE.getState(), e.getSQLState()); } assertTrue(!rs.next()); rs = stmt.executeQuery("RETURN "+ Integer.toString(Integer.MAX_VALUE) + " AS i"); assertTrue(rs.next()); assertEquals(Integer.MAX_VALUE, rs.getInt(1)); assertTrue(!rs.next()); rs.close(); stmt.close(); } @Test public void testGetStringToLong() throws SQLException { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("RETURN ' 0' AS l"); assertTrue(rs.next()); assertEquals(0, rs.getLong(1)); assertTrue(!rs.next()); rs = stmt.executeQuery("RETURN '" + Long.MAX_VALUE + "' AS l"); assertTrue(rs.next()); assertEquals(Long.MAX_VALUE, rs.getLong(1)); assertTrue(!rs.next()); rs = stmt.executeQuery("RETURN '0x' AS l"); assertTrue(rs.next()); try { rs.getLong(1); fail("SQLExecption expected"); } catch (SQLException e) { assertEquals(PSQLState.NUMERIC_VALUE_OUT_OF_RANGE.getState(), e.getSQLState()); } assertTrue(!rs.next()); rs = stmt.executeQuery("RETURN "+ Long.toString(Long.MAX_VALUE) + " AS l"); assertTrue(rs.next()); assertEquals(Long.MAX_VALUE, rs.getLong(1)); assertTrue(!rs.next()); rs.close(); stmt.close(); } @Test public void testGetStringToFloat() throws SQLException { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("RETURN ' 0.0' AS f"); assertTrue(rs.next()); assertEquals(0.0F, rs.getFloat(1)); assertTrue(!rs.next()); rs = stmt.executeQuery("RETURN '" + Float.MAX_VALUE + "' AS f"); assertTrue(rs.next()); assertEquals(Float.MAX_VALUE, rs.getFloat(1)); assertTrue(!rs.next()); rs = stmt.executeQuery("RETURN '0.0x' AS d"); assertTrue(rs.next()); try { rs.getFloat(1); fail("SQLExecption expected"); } catch (SQLException e) { assertEquals(PSQLState.NUMERIC_VALUE_OUT_OF_RANGE.getState(), e.getSQLState()); } assertTrue(!rs.next()); rs = stmt.executeQuery("RETURN "+ Float.toString(Float.MAX_VALUE) + " AS f"); assertTrue(rs.next()); assertEquals(Float.MAX_VALUE, rs.getFloat(1)); assertTrue(!rs.next()); rs.close(); stmt.close(); } @Test public void testGetStringToDouble() throws SQLException { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("RETURN ' 0.0' AS d"); assertTrue(rs.next()); assertEquals(0.0D, rs.getDouble(1)); assertTrue(!rs.next()); rs = stmt.executeQuery("RETURN '0.0x' AS d"); assertTrue(rs.next()); try { rs.getDouble(1); fail("SQLExecption expected"); } catch (SQLException e) { assertEquals(PSQLState.NUMERIC_VALUE_OUT_OF_RANGE.getState(), e.getSQLState()); } assertTrue(!rs.next()); rs = stmt.executeQuery("RETURN "+ Double.toString(Double.MAX_VALUE) + " AS d"); assertTrue(rs.next()); assertEquals(Double.MAX_VALUE, rs.getDouble(1)); assertTrue(!rs.next()); rs.close(); stmt.close(); } @Test public void testGetStringToBigDecimal() throws SQLException { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("RETURN ' 0.0' AS b"); assertTrue(rs.next()); assertEquals(0.0, rs.getBigDecimal(1).doubleValue()); assertTrue(!rs.next()); rs = stmt.executeQuery("RETURN '0.0x' AS b"); assertTrue(rs.next()); try { rs.getBigDecimal(1); fail("SQLExecption expected"); } catch (SQLException e) { assertEquals(PSQLState.NUMERIC_VALUE_OUT_OF_RANGE.getState(), e.getSQLState()); } assertTrue(!rs.next()); rs = stmt.executeQuery("RETURN "+ Double.toString(Double.MAX_VALUE) + " AS d"); assertTrue(rs.next()); assertEquals(Double.MAX_VALUE, rs.getBigDecimal(1).doubleValue()); assertTrue(!rs.next()); rs.close(); stmt.close(); } } <|start_filename|>src/main/java/net/bitnine/agensgraph/util/Jsonb.java<|end_filename|> /* * Copyright (c) 2014-2018, Bitnine Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.bitnine.agensgraph.util; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.postgresql.util.PGobject; import org.postgresql.util.PSQLException; import org.postgresql.util.PSQLState; import java.io.Serializable; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * This class is for a Jsonb value which is returned from server or will be sent to the server. */ public class Jsonb extends PGobject implements JsonbObject, Serializable, Cloneable { private Object jsonValue = null; /** * This constructor should not be used directly. */ public Jsonb() { setType("jsonb"); } /** * This constructor should not be used directly. */ Jsonb(Object obj) { this(); jsonValue = obj; } /** * This method should not be used directly. */ @Override public void setValue(String value) throws SQLException { Object obj; try { obj = JSONValue.parseWithException(value); } catch (Exception e) { throw new PSQLException("Parsing jsonb failed", PSQLState.DATA_ERROR, e); } super.setValue(value); this.jsonValue = obj; } /** * Returns a string representation of the Json value. * * @return a string representation of the Json value */ @Override public String getValue() { if (value == null) value = JSONValue.toJSONString(jsonValue); return value; } /** * Returns the internal structure (from json-simple 1.1.1) of the Json value. * * @return the internal structure (from json-simple 1.1.1) of the Json value */ public Object getJsonValue() { return jsonValue; } private String getString(Object obj) { if (obj instanceof String) return (String) obj; throw new UnsupportedOperationException("Not a string: " + obj); } private boolean isInteger(long l) { return (l >= Integer.MIN_VALUE && l <= Integer.MAX_VALUE); } private int getInt(Object obj) { if (obj instanceof Long) { long l = (Long) obj; if (isInteger(l)) return (int) l; throw new IllegalArgumentException("Bad value for type int: " + l); } if (obj instanceof String) { String s = getString(obj); s = s.trim(); if (isLong(s)) return getInt(Long.parseLong(s)); } throw new UnsupportedOperationException("Not an int: " + obj); } private boolean isLong(String s) { try { Long.parseLong(s); return true; } catch (NumberFormatException e) { return false; } } private long getLong(Object obj) { if (obj instanceof Long) return (Long) obj; if (obj instanceof String) { String s = getString(obj); s = s.trim(); if (isLong(s)) return getLong(Long.parseLong(s)); } throw new UnsupportedOperationException("Not a long: " + obj); } private boolean isDouble(String s) { try { Double.parseDouble(s); return true; } catch(NumberFormatException e) { return false; } } private double getDouble(Object obj) { if (obj instanceof Double) return (Double) obj; if (obj instanceof String) { String s = getString(obj); s = s.trim(); if (isDouble(s)) return getDouble(Double.parseDouble(s)); } throw new UnsupportedOperationException("Not a double: " + obj); } private boolean getBoolean(Object obj) { if (obj instanceof Boolean) return (Boolean) obj; if (obj instanceof String) return ((String) obj).length() > 0; else if (obj instanceof Long) return (Long) obj != 0L; else if (obj instanceof Double) return (Double) obj != 0.0; else if (obj instanceof JSONArray) return ((JSONArray) obj).size() > 0; else if (obj instanceof JSONObject) return ((JSONObject) obj).size() > 0; else return false; } private Jsonb getArray(Object obj) { if (obj instanceof JSONArray) return new Jsonb(obj); throw new UnsupportedOperationException("Not an array: " + obj); } private Jsonb getObject(Object obj) { if (obj instanceof JSONObject) return new Jsonb(obj); throw new UnsupportedOperationException("Not an object: " + obj); } /** * Returns the string value if the Json value is string or returns null. * * @return the string value if the Json value is string or returns null */ public String tryGetString() { if (jsonValue instanceof String) return (String) jsonValue; return null; } /** * Returns the string value if the Json value is string or throws UnsupportedOperationException. * * @return the string value if the Json value is string or throws UnsupportedOperationException * @throws UnsupportedOperationException not a string */ public String getString() { return getString(jsonValue); } /** * Returns the integer value if the Json value is integer or throws UnsupportedOperationException. * * @return the integer value if the Json value is integer or throws UnsupportedOperationException * @throws UnsupportedOperationException not an int */ public int getInt() { return getInt(jsonValue); } /** * Returns the long value if the Json value is long or throws UnsupportedOperationException. * * @return the long value if the Json value is long or throws UnsupportedOperationException * @throws UnsupportedOperationException not a long */ public long getLong() { return getLong(jsonValue); } /** * Returns the double value if the Json value is double or throws UnsupportedOperationException. * * @return the double value if the Json value is double or throws UnsupportedOperationException * @throws UnsupportedOperationException not a double */ public double getDouble() { return getDouble(jsonValue); } /** * Returns the boolean value if the Json value is boolean. * * @return the boolean value if the Json value is boolean */ public boolean getBoolean() { return getBoolean(jsonValue); } /** * Returns true if the Json value is null. * * @return true if the Json value is null */ public boolean isNull() { return jsonValue == null; } /** * Returns a Jsonb that wraps the array value if the Json value is array or throws UnsupportedOperationException. * * @return a Jsonb that wraps the array value if the Json value is array or throws UnsupportedOperationException */ public Jsonb getArray() { return getArray(jsonValue); } /** * Returns a Jsonb that wraps the object value if the Json value is object or throws UnsupportedOperationException. * * @return a Jsonb that wraps the object value if the Json value is object or throws UnsupportedOperationException * @throws UnsupportedOperationException not an object */ public Jsonb getObject() { return getObject(jsonValue); } /** * Returns the string value if the value at index of the array is string or throws UnsupportedOperationException. * * @param index the index of the array * @return the string value if the value at index of the array is string or throws UnsupportedOperationException * @throws UnsupportedOperationException not an array */ public String getString(int index) { if (!(jsonValue instanceof JSONArray)) throw new UnsupportedOperationException("Not an array: " + jsonValue); JSONArray a = (JSONArray) jsonValue; return getString(a.get(index)); } /** * Returns the integer value if the value at index of the array is integer or throws UnsupportedOperationException. * * @param index the index of the array * @return the integer value if the value at index of the array is integer or throws UnsupportedOperationException * @throws UnsupportedOperationException not an array */ public int getInt(int index) { if (!(jsonValue instanceof JSONArray)) throw new UnsupportedOperationException("Not an array: " + jsonValue); JSONArray a = (JSONArray) jsonValue; return getInt(a.get(index)); } /** * Returns the long value if the value at index of the array is long or throws UnsupportedOperationException. * * @param index the index of the array * @return the long value if the value at index of the array is long or throws UnsupportedOperationException * @throws UnsupportedOperationException not an array */ public long getLong(int index) { if (!(jsonValue instanceof JSONArray)) throw new UnsupportedOperationException("Not an array: " + jsonValue); JSONArray a = (JSONArray) jsonValue; return getLong(a.get(index)); } /** * Returns the double value if the value at index of the array is double or throws UnsupportedOperationException. * * @param index the index of the array * @return the double value if the value at index of the array is double or throws UnsupportedOperationException * @throws UnsupportedOperationException not an array */ public double getDouble(int index) { if (!(jsonValue instanceof JSONArray)) throw new UnsupportedOperationException("Not an array: " + jsonValue); JSONArray a = (JSONArray) jsonValue; return getDouble(a.get(index)); } /** * Returns the boolean value if the value at index of the array is boolean or throws UnsupportedOperationException. * * @param index the index of the array * @return the boolean value if the value at index of the array is boolean or throws UnsupportedOperationException * @throws UnsupportedOperationException not an array */ public boolean getBoolean(int index) { if (!(jsonValue instanceof JSONArray)) throw new UnsupportedOperationException("Not an array: " + jsonValue); JSONArray a = (JSONArray) jsonValue; return getBoolean(a.get(index)); } /** * Returns a Jsonb that wraps the array value if the value at index of the array is array * or throws UnsupportedOperationException. * * @param index the index of the array * @return a Jsonb that wraps the array value if the value at index of the array is array * or throws UnsupportedOperationException * @throws UnsupportedOperationException not an array */ public Jsonb getArray(int index) { if (!(jsonValue instanceof JSONArray)) throw new UnsupportedOperationException("Not an array: " + jsonValue); JSONArray a = (JSONArray) jsonValue; return getArray(a.get(index)); } /** * Returns a Jsonb that wraps the object value if the value at index of the array is object * or throws UnsupportedOperationException. * * @param index the index of the array * @return a Jsonb that wraps the object value if the value at index of the array is object * or throws UnsupportedOperationException * @throws UnsupportedOperationException not an array */ public Jsonb getObject(int index) { if (!(jsonValue instanceof JSONArray)) throw new UnsupportedOperationException("Not an array: " + jsonValue); JSONArray a = (JSONArray) jsonValue; return getObject(a.get(index)); } /** * Returns true if the value at index of the array is null or throws UnsupportedOperationException. * * @param index the index of the array * @return true if the value at index of the array is null or throws UnsupportedOperationException * @throws UnsupportedOperationException not an array */ public boolean isNull(int index) { if (!(jsonValue instanceof JSONArray)) throw new UnsupportedOperationException("Not an array: " + jsonValue); JSONArray a = (JSONArray) jsonValue; return a.get(index) == null; } @Override public Iterable<String> getKeys() { if (!(jsonValue instanceof JSONObject)) throw new UnsupportedOperationException("Not an object: " + jsonValue); JSONObject o = (JSONObject) jsonValue; ArrayList<String> keys = new ArrayList<>(o.size()); for (Object k : o.keySet()) keys.add((String) k); return keys; } @Override public boolean containsKey(String key) { if (!(jsonValue instanceof JSONObject)) throw new UnsupportedOperationException("Not an object: " + jsonValue); JSONObject o = (JSONObject) jsonValue; return o.containsKey(key); } @Override public String getString(String key) { if (!(jsonValue instanceof JSONObject)) throw new UnsupportedOperationException("Not an object: " + jsonValue); JSONObject o = (JSONObject) jsonValue; return getString(o.get(key)); } @Override public String getString(String key, String defaultValue) { return containsKey(key) ? getString(key) : defaultValue; } private Object getIntObject(String key) { if (!(jsonValue instanceof JSONObject)) throw new UnsupportedOperationException("Not an object: " + jsonValue); JSONObject o = (JSONObject) jsonValue; return o.get(key); } @Override public int getInt(String key) { return getInt(getIntObject(key)); } @Override public int getInt(String key, int defaultValue) { return containsKey(key) ? getInt(key) : defaultValue; } @Override public long getLong(String key) { if (!(jsonValue instanceof JSONObject)) throw new UnsupportedOperationException("Not an object: " + jsonValue); JSONObject o = (JSONObject) jsonValue; return getLong(o.get(key)); } @Override public long getLong(String key, long defaultValue) { return containsKey(key) ? getLong(key) : defaultValue; } @Override public double getDouble(String key) { if (!(jsonValue instanceof JSONObject)) throw new UnsupportedOperationException("Not an object: " + jsonValue); JSONObject o = (JSONObject) jsonValue; return getDouble(o.get(key)); } @Override public double getDouble(String key, double defaultValue) { return containsKey(key) ? getDouble(key) : defaultValue; } @Override public boolean getBoolean(String key) { if (!(jsonValue instanceof JSONObject)) throw new UnsupportedOperationException("Not an object: " + jsonValue); JSONObject o = (JSONObject) jsonValue; return getBoolean(o.get(key)); } @Override public boolean getBoolean(String key, boolean defaultValue) { return containsKey(key) ? getBoolean(key) : defaultValue; } @Override public Jsonb getArray(String key) { if (!(jsonValue instanceof JSONObject)) throw new UnsupportedOperationException("Not an object: " + jsonValue); JSONObject o = (JSONObject) jsonValue; return getArray(o.get(key)); } @Override public Jsonb getObject(String key) { if (!(jsonValue instanceof JSONObject)) throw new UnsupportedOperationException("Not an object: " + jsonValue); JSONObject o = (JSONObject) jsonValue; return getObject(o.get(key)); } @Override public boolean isNull(String key) { if (!(jsonValue instanceof JSONObject)) throw new UnsupportedOperationException("Not an object: " + jsonValue); JSONObject o = (JSONObject) jsonValue; return o.get(key) == null; } /** * Returns the size of Json value if the value is array or object. * * @return the size of Json value if the value is array or object */ public int size() { if (jsonValue instanceof JSONArray) return ((JSONArray) jsonValue).size(); else if (jsonValue instanceof JSONObject) return ((JSONObject) jsonValue).size(); else throw new UnsupportedOperationException("Not an array or an object: " + jsonValue); } private Object getTypedValue(Object obj) { if (obj instanceof Long) { long l = (Long) obj; if (isInteger(l)) return (int) l; else return l; } else if (obj instanceof JSONArray) { JSONArray a = (JSONArray) obj; ArrayList<Object> newa = new ArrayList<>(a.size()); for (Object e : a) newa.add(getTypedValue(e)); return newa; } else if (obj instanceof JSONObject) { JSONObject o = (JSONObject) obj; HashMap<String, Object> newo = new HashMap<>(o.size()); for (Object _e : o.entrySet()) { Map.Entry e = (Map.Entry) _e; newo.put((String) e.getKey(), getTypedValue(e.getValue())); } return newo; } else { return obj; } } /** * Returns an object that wraps automatically the value by type. * * @return an object that wraps automatically the value by type */ public Object getTypedValue() { return getTypedValue(jsonValue); } @Override public String toString() { return getValue(); } } <|start_filename|>src/main/java/net/bitnine/agensgraph/jdbc/AgArray.java<|end_filename|> /* * Copyright (c) 2014-2018, Bitnine Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.bitnine.agensgraph.jdbc; import net.bitnine.agensgraph.core.Oid; import net.bitnine.agensgraph.util.AgTokenizer; import org.postgresql.core.BaseConnection; import org.postgresql.core.BaseStatement; import org.postgresql.core.Field; import org.postgresql.jdbc.PgArray; import org.postgresql.util.GT; import org.postgresql.util.PSQLException; import org.postgresql.util.PSQLState; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Array is used collect one column of query result data. */ public class AgArray extends PgArray { /** * The OID of this field. */ private int oid; /** * Value of field. Will be initialized only once within * {@link #buildArrayList()}. */ private ArrayList<String> arrayList; /** * Create a new Array. * * @param connection a database connection * @param oid the oid of the array datatype * @param fieldString the array data in string form * @throws SQLException if something wrong happens */ public AgArray(BaseConnection connection, int oid, String fieldString) throws SQLException { super(connection, oid, fieldString); this.oid = oid; } /** * Create a new Array. * * @param connection a database connection * @param oid the oid of the array datatype * @param fieldBytes the array data in byte form * @throws SQLException if something wrong happens */ public AgArray(BaseConnection connection, int oid, byte[] fieldBytes) throws SQLException { super(connection, oid, fieldBytes); this.oid = oid; } @Override public Object getArrayImpl(long index, int count, Map<String, Class<?>> map) throws SQLException { // for now maps aren't supported. if (map != null && !map.isEmpty()) { throw org.postgresql.Driver.notImplemented(this.getClass(), "getArrayImpl(long,int,Map)"); } // array index is out of range if (index < 1) { throw new PSQLException(GT.tr("The array index is out of range: {0}", index), PSQLState.DATA_ERROR); } if (fieldBytes != null) { throw new PSQLException(GT.tr("The type Binary is not supported."), PSQLState.DATA_ERROR); } if (fieldString == null) { return null; } buildArrayList(); if (count == 0) { count = arrayList.size(); } // array index out of range if ((--index) + count > arrayList.size()) { throw new PSQLException( GT.tr("The array index is out of range: {0}, number of elements: {1}.", index + count, (long) arrayList.size()), PSQLState.DATA_ERROR); } return buildArray(arrayList, (int) index, count); } /** * Build {@link ArrayList} from field's string input. As a result of this method * {@link #arrayList} is build. Method can be called many times in order to make sure that array * list is ready to use, however {@link #arrayList} will be set only once during first call. */ private void buildArrayList() throws SQLException { if (arrayList != null) { return; } arrayList = AgTokenizer.tokenize(fieldString); } /** * Convert {@link ArrayList} to array. * * @param input list to be converted into array */ private Object buildArray(ArrayList<String> input, int index, int count) throws SQLException { if (count < 0) { count = input.size(); } // array to be returned Object ret = null; // array elements counter int length = 0; // array elements name String typeName = getBaseTypeName(); Object[] oa = null; ret = oa = (Object[]) java.lang.reflect.Array .newInstance(connection.getTypeInfo().getPGobject(typeName), count); // add elements for (; count > 0; count--) { String v = input.get(index++); if (v == null) { oa[length++] = null; } else { oa[length++] = connection.getObject(typeName, v, null); } } return ret; } @Override public String getBaseTypeName() throws SQLException { buildArrayList(); int elementOID = connection.getTypeInfo().getPGArrayElement(oid); return connection.getTypeInfo().getPGType(elementOID); } @Override public ResultSet getResultSetImpl(long index, int count, Map<String, Class<?>> map) throws SQLException { // for now maps aren't supported if (map != null && !map.isEmpty()) { throw org.postgresql.Driver.notImplemented(this.getClass(), "getResultSetImpl(long,int,Map)"); } // array index is out of range if (index < 1) { throw new PSQLException(GT.tr("The array index is out of range: {0}", index), PSQLState.DATA_ERROR); } if (fieldBytes != null) { throw new PSQLException(GT.tr("The type Binary is not supported."), PSQLState.DATA_ERROR); } buildArrayList(); if (count == 0) { count = arrayList.size(); } // array index out of range if ((--index) + count > arrayList.size()) { throw new PSQLException( GT.tr("The array index is out of range: {0}, number of elements: {1},", index + count, (long) arrayList.size()), PSQLState.DATA_ERROR); } List<byte[][]> rows = new ArrayList<byte[][]>(); Field[] fields = new Field[2]; final int baseOid = connection.getTypeInfo().getPGArrayElement(oid); fields[0] = new Field("INDEX", Oid.INT4); fields[1] = new Field("VALUE", baseOid); for (int i = 0; i < count; i++) { int offset = (int) index + i; byte[][] t = new byte[2][0]; String v = arrayList.get(offset); t[0] = connection.encodeString(Integer.toString(offset + 1)); t[1] = v == null ? null : connection.encodeString(v); rows.add(t); } BaseStatement stat = (BaseStatement) connection .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); return stat.createDriverResultSet(fields, rows); } @Override public void free() throws SQLException { super.free(); arrayList = null; } } <|start_filename|>src/test/java/net/bitnine/agensgraph/test/jdbc/AgArrayTest.java<|end_filename|> /* * Copyright (c) 2014-2018, Bitnine Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.bitnine.agensgraph.test.jdbc; import junit.framework.TestCase; import net.bitnine.agensgraph.graph.Edge; import net.bitnine.agensgraph.graph.GraphId; import net.bitnine.agensgraph.graph.Vertex; import net.bitnine.agensgraph.jdbc.AgConnection; import net.bitnine.agensgraph.test.TestUtil; import org.junit.Test; import java.sql.Array; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.PreparedStatement; import java.sql.Types; public class AgArrayTest extends TestCase { private AgConnection conn; @Override public void setUp() throws Exception { conn = TestUtil.openDB().unwrap(AgConnection.class); Statement stmt = conn.createStatement(); stmt.execute("DROP GRAPH IF EXISTS t CASCADE"); stmt.execute("CREATE GRAPH t"); stmt.execute("SET graph_path = t"); stmt.execute("CREATE (:v{vid:1})-[:r{rid:1}]->(:v{vid:2})-[:r{rid:2}]->(:v{vid:3})"); stmt.close(); } @Override public void tearDown() throws SQLException { Statement stmt = conn.createStatement(); stmt.execute("DROP GRAPH t CASCADE"); stmt.close(); TestUtil.closeDB(conn); } @Test public void testEdgeArray() throws SQLException { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("MATCH p=()-[]->()-[]->() RETURN relationships(p)"); assertTrue(rs.next()); Array arr = rs.getArray(1); Edge[] e = (Edge[]) arr.getArray(); for (int i = 0; i < e.length; i++) { assertEquals("edge", e[i].getType()); } assertTrue(!rs.next()); rs.close(); stmt.close(); } @Test public void testEdgeResultSet() throws SQLException { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("MATCH ()-[rel:r *2..]-() RETURN rel"); assertTrue(rs.next()); Array arr = rs.getArray(1); rs = arr.getResultSet(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); Edge e1 = (Edge) rs.getObject(2); assertEquals(1, e1.getInt("rid")); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); Edge e2 = (Edge) rs.getObject(2); assertEquals(2, e2.getInt("rid")); assertTrue(!rs.next()); rs.close(); stmt.close(); } @Test public void testVertexArray() throws SQLException { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("MATCH p=()-[]->()-[]->() RETURN nodes(p)"); assertTrue(rs.next()); Array arr = rs.getArray(1); Vertex[] v = (Vertex[]) arr.getArray(); for (int i = 0; i < v.length; i++) { assertEquals("vertex", v[i].getType()); } assertTrue(!rs.next()); rs.close(); stmt.close(); } @Test public void testVertexResultSet() throws SQLException { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("MATCH p=()-[]->()-[]->() RETURN nodes(p)"); assertTrue(rs.next()); Array arr = rs.getArray(1); rs = arr.getResultSet(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); Vertex v1 = (Vertex) rs.getObject(2); assertEquals(1, v1.getInt("vid")); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); Vertex v2 = (Vertex) rs.getObject(2); assertEquals(2, v2.getInt("vid")); assertTrue(rs.next()); assertEquals(3, rs.getInt(1)); Vertex v3 = (Vertex) rs.getObject(2); assertEquals(3, v3.getInt("vid")); assertTrue(!rs.next()); rs.close(); stmt.close(); } @Test public void testGraphIdArray() throws SQLException { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("MATCH (v)-[]->() RETURN array_agg(id(v))"); assertTrue(rs.next()); Array arr = rs.getArray(1); GraphId[] gid = (GraphId[]) arr.getArray(); for (int i = 0; i < gid.length; i++) { assertEquals("graphid", gid[i].getType()); } assertTrue(!rs.next()); rs.close(); stmt.close(); } @Test public void testGraphIdResultSet() throws SQLException { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("MATCH ()-[r]->() RETURN array_agg(id(r))"); assertTrue(rs.next()); Array arr = rs.getArray(1); rs = arr.getResultSet(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); GraphId gid1 = (GraphId) rs.getObject(2); assertEquals("graphid", gid1.getType()); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); GraphId gid2 = (GraphId) rs.getObject(2); assertEquals("graphid", gid2.getType()); assertTrue(!rs.next()); rs.close(); stmt.close(); } @Test public void testGetBaseTypeName() throws SQLException { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("MATCH p=()-[]->()-[]->() RETURN relationships(p)"); assertTrue(rs.next()); Array arr = rs.getArray(1); assertEquals("edge", arr.getBaseTypeName()); assertTrue(!rs.next()); rs.close(); stmt.close(); } @Test public void testGetBaseType() throws SQLException { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("MATCH p=()-[]->()-[]->() RETURN relationships(p)"); assertTrue(rs.next()); Array arr = rs.getArray(1); assertEquals(Types.STRUCT, arr.getBaseType()); assertTrue(!rs.next()); rs.close(); stmt.close(); } @Test public void testWriteGraphIdArray() throws SQLException { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("MATCH (v)-[]->() RETURN array_agg(id(v))"); assertTrue(rs.next()); Array arr = rs.getArray(1); assertTrue(!rs.next()); rs.close(); stmt.close(); PreparedStatement pstmt = conn.prepareStatement("RETURN ?"); pstmt.setArray(1, arr); rs = pstmt.executeQuery(); assertTrue(rs.next()); arr = rs.getArray(1); GraphId[] gid = (GraphId[]) arr.getArray(); for (int i = 0; i < gid.length; i++) { assertEquals("graphid", gid[i].getType()); } assertTrue(!rs.next()); rs.close(); pstmt.setArray(1, conn.createArrayOf("graphid", gid)); rs = pstmt.executeQuery(); assertTrue(rs.next()); arr = rs.getArray(1); gid = (GraphId[]) arr.getArray(); for (int i = 0; i < gid.length; i++) { assertEquals("graphid", gid[i].getType()); } assertTrue(!rs.next()); rs.close(); pstmt.close(); } } <|start_filename|>src/main/java/net/bitnine/agensgraph/util/AgTokenizer.java<|end_filename|> /* * Copyright (c) 2014-2018, Bitnine Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.bitnine.agensgraph.util; import org.postgresql.util.PSQLException; import org.postgresql.util.PSQLState; import java.sql.SQLException; import java.util.ArrayList; /** * This class is used to tokenize the text output. */ public class AgTokenizer { private AgTokenizer() { } /** * This create tokens from a new string. * * @param string containing tokens * @return The tokens value * @throws SQLException if something wrong happens */ public static ArrayList<String> tokenize(String string) throws SQLException { ArrayList<String> tokens = new ArrayList<>(); // ignore wrapping '[' and ']' characters int pos = 1; int len = string.length() -1; int start = pos; int depth = 0; // id of vertex or edge boolean veid = false; String buffer = null; while (pos < len) { char c = string.charAt(pos); switch (c) { case '"': if (depth > 0) { // Parse "string". // Leave pos unchanged if unmatched right " were found. boolean escape = false; for (int i = pos + 1; i < len; i++) { c = string.charAt(i); if (c == '\\') { escape = !escape; } else if (c == '"') { if (escape) escape = false; else { pos = i; break; } } else { escape = false; } } } break; case '[': if (depth == 0) veid = true; break; case ']': if (depth == 0) veid = false; break; case '{': depth++; break; case '}': depth--; if (depth < 0) { throw new PSQLException("Parsing graphpath failed", PSQLState.DATA_ERROR); } break; case ',': if (depth == 0 && !veid) { buffer = string.substring(start, pos); // Add null for "" and "NULL" because AgTokenizer can be used to parse array elements // and in this case, array index is important. if (buffer.isEmpty() || "NULL".equals(buffer)) { tokens.add(null); } else { tokens.add(buffer); } start = pos + 1; } break; default: break; } pos++; } /* add the last token */ buffer = string.substring(start, pos); if (buffer.isEmpty() || "NULL".equals(buffer)) { tokens.add(null); } else { tokens.add(buffer); } return tokens; } } <|start_filename|>src/main/java/net/bitnine/agensgraph/graph/Path.java<|end_filename|> /* * Copyright (c) 2014-2018, Bitnine Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.bitnine.agensgraph.graph; import net.bitnine.agensgraph.util.AgTokenizer; import org.postgresql.util.PGobject; import java.io.Serializable; import java.sql.SQLException; import java.util.ArrayList; /** * This class defines the type path. */ public class Path extends PGobject implements Serializable, Cloneable { private ArrayList<Vertex> vertices; private ArrayList<Edge> edges; public Path() { setType("graphpath"); } @Override public void setValue(String value) throws SQLException { ArrayList<String> tokens = AgTokenizer.tokenize(value); ArrayList<Vertex> vertices = new ArrayList<>(); ArrayList<Edge> edges = new ArrayList<>(); for (int i = 0; i < tokens.size(); i++) { if (i % 2 == 0) { Vertex v = new Vertex(); v.setValue(tokens.get(i)); vertices.add(v); } else { Edge e = new Edge(); e.setValue(tokens.get(i)); edges.add(e); } } this.vertices = vertices; this.edges = edges; super.setValue(value); } /** * Returns a set of the vertices. * * @return a set of the vertices. */ public Iterable<Vertex> vertices() { return vertices; } /** * Returns a set of the edges. * * @return a set of the edges. */ public Iterable<Edge> edges() { return edges; } /** * Returns the length of the edges. * * @return the length of the edges */ public int length() { return edges.size(); } }
bitnine-oss/agensgraph-jdbc
<|start_filename|>add-on/src/popup/logo.js<|end_filename|> 'use strict' /* eslint-env browser, webextensions */ const html = require('choo/html') const { braveNodeType } = require('../lib/ipfs-client/brave') function logo ({ path, size = 52, ipfsNodeType = 'external', isIpfsOnline = true, heartbeat = true }) { return html` <img alt="IPFS" src="${path}/${logoFileName(ipfsNodeType, isIpfsOnline)}" class="v-mid ${isIpfsOnline ? '' : 'o-40'} ${isIpfsOnline && heartbeat ? 'heartbeat' : ''}" style="width:${size}px; height:${size}px" /> ` } function logoFileName (nodeType, isIpfsOnline) { let prefix if (nodeType.startsWith('embedded')) prefix = 'js-' if (nodeType === braveNodeType) prefix = 'brave-' return `${prefix || ''}ipfs-logo-${isIpfsOnline ? 'on' : 'off'}.svg` } module.exports = logo <|start_filename|>scripts/fetch-webui-from-gateway.js<|end_filename|> /* This is a fallback script used when ipfs cli fails or is not available * More details: https://github.com/ipfs-shipyard/ipfs-webui/issues/843 * See also why this is not used anymore: https://github.com/ipfs-shipyard/ipfs-companion/issues/679 */ const tar = require('tar') const request = require('request') const progress = require('request-progress') const cid = process.argv[2] const destination = process.argv[3] // use public gw const url = 'https://ipfs.io/api/v0/get?arg=' + cid + '&archive=true&compress=true' console.log('Fallback to HTTP GET from: ' + url) progress(request(url), { lengthHeader: 'x-content-length', delay: 10000 }) .on('progress', (state) => console.log(`progress: ${Math.round(state.percent)} %, transferred: ${state.size.transferred}`, state)) .on('response', (response) => console.log('Status Code', response.statusCode)) .on('error', (error) => console.log('Download Error', error)) .on('close', () => console.log('Done! webui extracted to: ' + destination)) .pipe( tar.extract({ strip: 1, C: destination }) ) <|start_filename|>add-on/src/landing-pages/welcome/welcome.css<|end_filename|> @import url('~tachyons/css/tachyons.css'); @import url('~ipfs-css/ipfs.css'); @import url('../../popup/heartbeat.css'); #left-col { background-image: url('../../../images/stars.png'), linear-gradient(to bottom, #041727 0%, #043b55 100%); background-size: 100%; background-repeat: repeat; } .underline-under { text-decoration: underline; text-underline-position: under; } a:hover { text-decoration: underline; } .state-unknown { opacity: 0; filter: blur( .15em ); } /* https://github.com/tachyons-css/tachyons-queries Tachyons: $point == large */ @media (min-width: 64em) { #left-col { position: fixed; top: 0; right: 50%; width: 50%; background-image: url('../../../images/stars.png'), linear-gradient(to bottom, #041727 0%, #043b55 100%); background-size: 100%; background-repeat: repeat; } #right-col { margin-left: 50%; } } @media (max-height: 800px) { #left-col img { width: 98px !important; height: 98px !important; } #left-col svg { width: 60px; } } <|start_filename|>add-on/src/lib/notifier.js<|end_filename|> 'use strict' const browser = require('webextension-polyfill') const debug = require('debug') const log = debug('ipfs-companion:notifier') log.error = debug('ipfs-companion:notifier:error') function createNotifier (getState) { const { getMessage } = browser.i18n return async (titleKey, messageKey, messageParam) => { const title = browser.i18n.getMessage(titleKey) || titleKey let message if (messageKey.startsWith('notify_')) { message = messageParam ? getMessage(messageKey, messageParam) : getMessage(messageKey) } else { message = messageKey } log(`${title}: ${message}`) if (getState().displayNotifications && browser && browser.notifications.create) { try { return await browser.notifications.create({ type: 'basic', iconUrl: browser.runtime.getURL('icons/ipfs-logo-on.svg'), title: title, message: message }) } catch (err) { log.error('failed to create a notification', err) } } } } module.exports = createNotifier <|start_filename|>add-on/src/lib/copier.js<|end_filename|> 'use strict' const { findValueForContext } = require('./context-menus') async function copyTextToClipboard (text, notify) { try { try { // Modern API (spotty support, but works in Firefox) await navigator.clipboard.writeText(text) // FUN FACT: // Before this API existed we had no access to cliboard from // the background page in Firefox and had to inject content script // into current page to copy there: // https://github.com/ipfs-shipyard/ipfs-companion/blob/b4a168880df95718e15e57dace6d5006d58e7f30/add-on/src/lib/copier.js#L10-L35 // :-)) } catch (e) { // Fallback to old API (works only in Chromium) function oncopy (event) { // eslint-disable-line no-inner-declarations document.removeEventListener('copy', oncopy, true) event.stopImmediatePropagation() event.preventDefault() event.clipboardData.setData('text/plain', text) } document.addEventListener('copy', oncopy, true) document.execCommand('copy') } notify('notify_copiedTitle', text) } catch (error) { console.error('[ipfs-companion] Failed to copy text', error) notify('notify_addonIssueTitle', 'Unable to copy') } } function createCopier (notify, ipfsPathValidator) { return { async copyTextToClipboard (text) { await copyTextToClipboard(text, notify) }, async copyCanonicalAddress (context, contextType) { const url = await findValueForContext(context, contextType) const ipfsPath = ipfsPathValidator.resolveToIpfsPath(url) await copyTextToClipboard(ipfsPath, notify) }, async copyCidAddress (context, contextType) { const url = await findValueForContext(context, contextType) const ipfsPath = await ipfsPathValidator.resolveToImmutableIpfsPath(url) await copyTextToClipboard(ipfsPath, notify) }, async copyRawCid (context, contextType) { const url = await findValueForContext(context, contextType) try { const cid = await ipfsPathValidator.resolveToCid(url) await copyTextToClipboard(cid, notify) } catch (error) { console.error('Unable to resolve/copy direct CID:', error.message) if (notify) { const errMsg = error.toString() if (errMsg.startsWith('Error: no link')) { // Sharding support is limited: // - https://github.com/ipfs/js-ipfs/issues/1279 // - https://github.com/ipfs/go-ipfs/issues/5270 notify('notify_addonIssueTitle', 'Unable to resolve CID within HAMT-sharded directory, sorry! Will be fixed soon.') } else { notify('notify_addonIssueTitle', 'notify_inlineErrorMsg', error.message) } } } }, async copyAddressAtPublicGw (context, contextType) { const url = await findValueForContext(context, contextType) const publicUrl = ipfsPathValidator.resolveToPublicUrl(url) await copyTextToClipboard(publicUrl, notify) }, async copyPermalink (context, contextType) { const url = await findValueForContext(context, contextType) const permalink = await ipfsPathValidator.resolveToPermalink(url) await copyTextToClipboard(permalink, notify) } } } module.exports = createCopier <|start_filename|>add-on/src/lib/runtime-checks.js<|end_filename|> 'use strict' /* eslint-env browser, webextensions */ const { brave } = require('./ipfs-client/brave') // this is our kitchen sink for runtime detection function getBrowserInfo (browser) { // browser.runtime.getBrowserInfo is not available in Chromium-based browsers if (browser && browser.runtime && browser.runtime.getBrowserInfo) { return browser.runtime.getBrowserInfo() } return Promise.resolve({}) } function getPlatformInfo (browser) { if (browser && browser.runtime && browser.runtime.getPlatformInfo) { return browser.runtime.getPlatformInfo() } return Promise.resolve() } async function createRuntimeChecks (browser) { // browser const { name, version } = await getBrowserInfo(browser) const isFirefox = name && (name.includes('Firefox') || name.includes('Fennec')) const hasNativeProtocolHandler = !!(browser && browser.protocol && browser.protocol.registerStringProtocol) // TODO: chrome.ipfs support // platform const platformInfo = await getPlatformInfo(browser) const isAndroid = platformInfo ? platformInfo.os === 'android' : false return Object.freeze({ browser, brave, // easy Boolean(runtime.brave) isFirefox, isAndroid, requiresXHRCORSfix: !!(isFirefox && version && version.startsWith('68')), hasNativeProtocolHandler }) } module.exports.createRuntimeChecks = createRuntimeChecks <|start_filename|>add-on/src/lib/http-proxy.js<|end_filename|> 'use strict' /* eslint-env browser, webextensions */ const browser = require('webextension-polyfill') const { safeURL } = require('./options') const debug = require('debug') const log = debug('ipfs-companion:http-proxy') log.error = debug('ipfs-companion:http-proxy:error') // Preface: // // When go-ipfs runs on localhost, it exposes two types of gateway: // 127.0.0.1:8080 - old school path gateway // localhost:8080 - subdomain gateway supporting Origins like $cid.ipfs.localhost // More: https://docs.ipfs.io/how-to/address-ipfs-on-web/#subdomain-gateway // // In a web browser contexts we care about Origin per content root (CID) // because entire web security model uses it as a basis for sandboxing and // access controls: // https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy // registerSubdomainProxy is necessary wourkaround for supporting subdomains // under 'localhost' (*.ipfs.localhost) because some operating systems do not // resolve them to local IP and return NX error not found instead // // State in Q2 2020: // - Chromium hardcodes `localhost` name to point at local IP and proxy is not // really necessary. The code is here (inactivE) in case we need it in the future. // - Firefox requires proxy to avoid DNS lookup, but there is an open issue // that will remove that need at some point: // https://bugzilla.mozilla.org/show_bug.cgi?id=1220810 async function registerSubdomainProxy (getState, runtime, notify) { // At the moment only firefox requires proxy registration if (!runtime.isFirefox) return try { const { active, useSubdomains, gwURLString } = getState() const enable = active && useSubdomains // HTTP Proxy feature is exposed on the gateway port // Just ensure we use localhost IP to remove any dependency on DNS const { hostname, port } = safeURL(gwURLString, { useLocalhostName: false }) // Firefox uses own APIs for selective proxying if (runtime.isFirefox) { return await registerSubdomainProxyFirefox(enable, hostname, port) } // At this point we would asume Chromium, but its not needed atm // Uncomment below if ever needed (+ add 'proxy' permission to manifest.json) // return await registerSubdomainProxyChromium(enable, hostname, port) } catch (err) { // registerSubdomainProxy is just a failsafe, not necessary in most cases, // so we should not break init when it fails. // For now we just log error and exit as NOOP log.error('registerSubdomainProxy failed', err) // Show pop-up only the first time, during init() when notify is passed try { if (notify) notify('notify_addonIssueTitle', 'notify_addonIssueMsg') } catch (_) { } } } // storing listener for later let onRequestProxyListener // registerSubdomainProxyFirefox sets proxy using API available in Firefox // https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/proxy/onRequest async function registerSubdomainProxyFirefox (enable, hostname, port) { const { onRequest } = browser.proxy // always remove the old listener (host and port could change) const oldListener = onRequestProxyListener if (oldListener && onRequest.hasListener(oldListener)) { onRequest.removeListener(oldListener) } if (enable) { // create new listener with the latest host:port note: the listener is // handling requests made to all localhost ports (limitation of the API, // port is ignored) that is why we manually check port inside of the listener onRequestProxyListener = (request) => { if (new URL(request.url).port === port) { return { type: 'http', host: hostname, port } } return { type: 'direct' } } // register the listener onRequest.addListener(onRequestProxyListener, { urls: ['http://*.localhost/*'], incognito: false }) log(`enabled ${hostname}:${port} as HTTP proxy for *.localhost`) return } // at this point we effectively disabled proxy log('disabled HTTP proxy for *.localhost') } /* * Chromium 80 does not need proxy, so below is not used. * Uncomment below if ever needed (+ add 'proxy' permission to manifest.json) // Helpers for converting callback chrome.* API to promises const cb = (resolve, reject) => (result) => { const err = chrome.runtime.lastError if (err) return reject(err) return resolve(result) } const get = async (opts) => new Promise((resolve, reject) => chrome.proxy.settings.get(opts, cb(resolve, reject))) const set = async (opts) => new Promise((resolve, reject) => chrome.proxy.settings.set(opts, cb(resolve, reject))) const clear = async (opts) => new Promise((resolve, reject) => chrome.proxy.settings.clear(opts, cb(resolve, reject))) // registerSubdomainProxyChromium sets proxy using API available in Chromium // https://developer.chrome.com/extensions/proxy async function registerSubdomainProxyChromium (enable, hostname, port) { const scope = 'regular_only' // read current proxy settings const settings = await get({ incognito: false }) // set or update, if enabled if (enable) { // PAC script enables selective routing to PROXY at host+port // here, PROXY is the same as HTTP API endpoint const pacConfig = { mode: 'pac_script', pacScript: { data: 'function FindProxyForURL(url, host) {\n' + ` if (shExpMatch(host, '*.localhost:${port}'))\n` + ` return 'PROXY ${hostname}:${port}';\n` + " return 'DIRECT';\n" + '}' } } await set({ value: pacConfig, scope }) log(`enabled ${hostname}:${port} as HTTP proxy for *.localhost`) // log('updated chrome.proxy.settings', await get({ incognito: false })) return } // else: remove any existing proxy settings if (settings && settings.levelOfControl === 'controlled_by_this_extension') { // remove any proxy settings ipfs-companion set up before await clear({ scope }) log('disabled HTTP proxy for *.localhost') } } */ module.exports.registerSubdomainProxy = registerSubdomainProxy <|start_filename|>add-on/src/lib/ipfs-proxy/enable-command.js<|end_filename|> const debug = require('debug') const log = debug('ipfs-companion:proxy') log.error = debug('ipfs-companion:proxy:error') const { inCommandWhitelist, createCommandWhitelistError } = require('./pre-command') const { createProxyAclError } = require('./pre-acl') // Artificial API command responsible for backend orchestration // during window.ipfs.enable() function createEnableCommand (getIpfs, getState, getScope, accessControl, requestAccess) { return async (opts) => { const scope = await getScope() const state = getState() log(`received window.ipfs.enable request from ${scope}`, opts) // Check if access to the IPFS node is disabled if (!state.ipfsProxy || !state.activeIntegrations(scope)) throw new Error('User disabled access to API proxy in IPFS Companion') // NOOP if .enable() was called without any arguments if (!opts) return // Validate and prompt for any missing permissions in bulk // if a list of needed commands is announced up front if (opts.commands) { const missingAcls = [] const deniedAcls = [] for (const command of opts.commands) { // Fail fast if command is not allowed to be proxied at all if (!inCommandWhitelist(command)) { throw createCommandWhitelistError(command) } // Get the current access flag to decide if it should be added // to the list of permissions to be prompted about in the next step const access = await accessControl.getAccess(scope, command) if (!access) { missingAcls.push(command) } else if (access.allow !== true) { deniedAcls.push(command) } } // Fail fast if user already denied any of requested permissions if (deniedAcls.length) { throw createProxyAclError(scope, deniedAcls) } // Display a single prompt with all missing permissions if (missingAcls.length) { const { allow, wildcard } = await requestAccess(scope, missingAcls) const access = await accessControl.setAccess(scope, wildcard ? '*' : missingAcls, allow) if (!access.allow) { throw createProxyAclError(scope, missingAcls) } } } } } module.exports = createEnableCommand <|start_filename|>test/functional/pages/proxy-access-dialog/page.test.js<|end_filename|> 'use strict' const { describe, it } = require('mocha') const { expect } = require('chai') const createProxyAccessDialogPage = require('../../../../add-on/src/pages/proxy-access-dialog/page') const createMockI18n = require('../../../helpers/mock-i18n') describe('pages/proxy-access-dialog/page', () => { it('should display title, wildcard checkbox and allow/deny buttons', async () => { const i18n = createMockI18n() const state = { scope: 'http://ipfs.io', permissions: ['files.add'] } let res expect(() => { res = createProxyAccessDialogPage(i18n)(state).toString() }).to.not.throw() expect(res).to.have.string(`page_proxyAccessDialog_title[${state.scope},${state.permissions}]`) expect(res).to.have.string(`page_proxyAccessDialog_wildcardCheckbox_label[${state.scope}]`) expect(res).to.have.string('page_proxyAccessDialog_denyButton_text') expect(res).to.have.string('page_proxyAccessDialog_allowButton_text') }) }) <|start_filename|>add-on/src/lib/ipfs-proxy/pre-acl.js<|end_filename|> // Creates a "pre" function that is called prior to calling a real function // on the IPFS instance. It will throw if access is denied, and ask the user if // no access decision has been made yet. function createPreAcl (permission, getState, getScope, accessControl, requestAccess) { return async (...args) => { const scope = await getScope() const state = getState() // Check if access to the IPFS node is disabled if (!state.ipfsProxy || !state.activeIntegrations(scope)) { throw createProxyAclError(undefined, undefined, 'User disabled access to API proxy in IPFS Companion') } const access = await getAccessWithPrompt(accessControl, requestAccess, scope, permission) if (!access.allow) { throw createProxyAclError(scope, permission) } return args } } async function getAccessWithPrompt (accessControl, requestAccess, scope, permission) { let access = await accessControl.getAccess(scope, permission) if (!access) { const { allow, wildcard } = await requestAccess(scope, permission) access = await accessControl.setAccess(scope, wildcard ? '*' : permission, allow) } return access } // Standardized error thrown when a command access is denied // TODO: return errors following conventions from https://github.com/ipfs/js-ipfs/pull/1746 function createProxyAclError (scope, permission, message) { const err = new Error(message || `User denied access to selected commands over IPFS proxy: ${permission}`) const permissions = Array.isArray(permission) ? permission : [permission] err.output = { payload: { // Error follows convention from https://github.com/ipfs/js-ipfs/pull/1746/files code: 'ERR_IPFS_PROXY_ACCESS_DENIED', permissions, scope, // TODO: remove below after deprecation period ends with Q1 get isIpfsProxyAclError () { console.warn("[ipfs-companion] reading .isIpfsProxyAclError from Ipfs Proxy errors is deprecated, use '.code' instead") return true }, get permission () { if (!this.permissions || !this.permissions.length) return undefined console.warn("[ipfs-companion] reading .permission from Ipfs Proxy errors is deprecated, use '.permissions' instead") return this.permissions[0] } } } return err } module.exports = { createPreAcl, createProxyAclError } <|start_filename|>add-on/src/popup/browser-action/tools.js<|end_filename|> 'use strict' /* eslint-env browser, webextensions */ const browser = require('webextension-polyfill') const html = require('choo/html') const toolsButton = require('./tools-button') module.exports = function tools ({ active, ipfsNodeType, isIpfsOnline, isApiAvailable, onQuickImport, onOpenWebUi }) { const activeQuickImport = active && isIpfsOnline && isApiAvailable const activeWebUI = active && isIpfsOnline && ipfsNodeType !== 'embedded' return html` <div class="flex pb2 ph2 justify-between"> ${toolsButton({ text: browser.i18n.getMessage('panel_quickImport'), title: browser.i18n.getMessage('panel_quickImportTooltip'), disabled: !activeQuickImport, onClick: onQuickImport, iconSize: 20, iconD: 'M71.13 28.87a29.88 29.88 0 100 42.26 29.86 29.86 0 000-42.26zm-18.39 37.6h-5.48V52.74H33.53v-5.48h13.73V33.53h5.48v13.73h13.73v5.48H52.74z' })} ${toolsButton({ text: browser.i18n.getMessage('panel_openWebui'), title: browser.i18n.getMessage('panel_openWebuiTooltip'), disabled: !activeWebUI, onClick: onOpenWebUi, iconSize: 18, iconD: 'M69.69 20.57c-.51-.51-1.06-1-1.62-1.47l-.16-.1c-.56-.46-1.15-.9-1.76-1.32l-.5-.35c-.25-.17-.52-.32-.79-.48A28.27 28.27 0 0050 12.23h-.69a28.33 28.33 0 00-27.52 28.36c0 13.54 19.06 37.68 26 46a3.21 3.21 0 005 0c6.82-8.32 25.46-32.25 25.46-45.84a28.13 28.13 0 00-8.56-20.18zM51.07 49.51a9.12 9.12 0 119.13-9.12 9.12 9.12 0 01-9.13 9.12z' })} </div> ` } <|start_filename|>add-on/src/options/forms/dnslink-form.js<|end_filename|> 'use strict' /* eslint-env browser, webextensions */ const browser = require('webextension-polyfill') const html = require('choo/html') const switchToggle = require('../../pages/components/switch-toggle') function dnslinkForm ({ dnslinkPolicy, dnslinkDataPreload, dnslinkRedirect, onOptionChange }) { const onDnslinkPolicyChange = onOptionChange('dnslinkPolicy') const onDnslinkRedirectChange = onOptionChange('dnslinkRedirect') const onDnslinkDataPreloadChange = onOptionChange('dnslinkDataPreload') return html` <form> <fieldset class="mb3 pa1 pa4-ns pa3 bg-snow-muted charcoal"> <h2 class="ttu tracked f6 fw4 teal mt0-ns mb3-ns mb1 mt2 ">${browser.i18n.getMessage('option_header_dnslink')}</h2> <div class="flex-row-ns pb0-ns"> <label for="dnslinkPolicy"> <dl> <dt>${browser.i18n.getMessage('option_dnslinkPolicy_title')}</dt> <dd> ${browser.i18n.getMessage('option_dnslinkPolicy_description')} <p><a class="link underline hover-aqua" href="https://docs.ipfs.io/how-to/dnslink-companion/" target="_blank"> ${browser.i18n.getMessage('option_legend_readMore')} </a></p> </dd> </dl> </label> <select id="dnslinkPolicy" name='dnslinkPolicy' class="self-center-ns bg-white navy" onchange=${onDnslinkPolicyChange}> <option value='false' selected=${String(dnslinkPolicy) === 'false'}> ${browser.i18n.getMessage('option_dnslinkPolicy_disabled')} </option> <option value='best-effort' selected=${dnslinkPolicy === 'best-effort'}> ${browser.i18n.getMessage('option_dnslinkPolicy_bestEffort')} </option> <option value='enabled' selected=${dnslinkPolicy === 'enabled'}> ${browser.i18n.getMessage('option_dnslinkPolicy_enabled')} </option> </select> </div> <div class="flex-row-ns pb0-ns"> <label for="dnslinkDataPreload"> <dl> <dt>${browser.i18n.getMessage('option_dnslinkDataPreload_title')}</dt> <dd>${browser.i18n.getMessage('option_dnslinkDataPreload_description')}</dd> </dl> </label> <div class="self-center-ns">${switchToggle({ id: 'dnslinkDataPreload', checked: dnslinkDataPreload, disabled: dnslinkRedirect, onchange: onDnslinkDataPreloadChange })}</div> </div> <div class="flex-row-ns pb0-ns"> <label for="dnslinkRedirect"> <dl> <dt>${browser.i18n.getMessage('option_dnslinkRedirect_title')}</dt> <dd> ${browser.i18n.getMessage('option_dnslinkRedirect_description')} ${dnslinkRedirect ? html`<p class="red i">${browser.i18n.getMessage('option_dnslinkRedirect_warning')}</p>` : null} <p><a class="link underline hover-aqua" href="https://docs.ipfs.io/how-to/address-ipfs-on-web/#subdomain-gateway" target="_blank"> ${browser.i18n.getMessage('option_legend_readMore')} </a></p> </dd> </dl> </label> <div class="self-center-ns">${switchToggle({ id: 'dnslinkRedirect', checked: dnslinkRedirect, onchange: onDnslinkRedirectChange })}</div> </div> </fieldset> </form> ` } module.exports = dnslinkForm <|start_filename|>add-on/src/options/store.js<|end_filename|> 'use strict' /* eslint-env browser, webextensions */ const browser = require('webextension-polyfill') const { optionDefaults } = require('../lib/options') const { createRuntimeChecks } = require('../lib/runtime-checks') // The store contains and mutates the state for the app module.exports = (state, emitter) => { state.options = optionDefaults const updateStateOptions = async () => { const runtime = await createRuntimeChecks(browser) state.withNodeFromBrave = runtime.brave && await runtime.brave.getIPFSEnabled() state.options = await getOptions() emitter.emit('render') } emitter.on('DOMContentLoaded', async () => { updateStateOptions() browser.storage.onChanged.addListener(updateStateOptions) }) emitter.on('optionChange', ({ key, value }) => ( browser.storage.local.set({ [key]: value }) )) emitter.on('optionsReset', () => ( browser.storage.local.set(optionDefaults) )) } async function getOptions () { const storedOpts = await browser.storage.local.get() return Object.keys(optionDefaults).reduce((opts, key) => { opts[key] = storedOpts[key] == null ? optionDefaults[key] : storedOpts[key] return opts }, {}) } <|start_filename|>add-on/src/lib/on-uninstalled.js<|end_filename|> 'use strict' /* eslint-env browser */ const stableChannels = new Set([ '<EMAIL>', // firefox (for legacy reasons) 'nibjojkomfdiaoajekhjakgkdhaomnch' // chromium (chrome web store) ]) const stableChannelFormUrl = 'https://docs.google.com/forms/d/e/1FAIpQLSfLF7uzaxRKiF4XpPL9_DvkdaQHoRnDihRTZ1uVL6ceQwIrtg/viewform' exports.getUninstallURL = (browser) => { // on uninstall feedback form shown only on stable channel return stableChannels.has(browser.runtime.id) ? stableChannelFormUrl : '' } <|start_filename|>add-on/src/pages/components/switch-toggle.js<|end_filename|> 'use strict' /* eslint-env browser, webextensions */ const html = require('choo/html') function switchToggle ({ id, onchange, checked, disabled, style }) { if (typeof checked === 'undefined') return return html` <div class="mdc-switch ${style || ''} ${checked ? 'mdc-switch--checked' : ''} ${disabled ? 'mdc-switch--disabled' : ''}"> <div class="mdc-switch__track"></div> <div class="mdc-switch__thumb-underlay"> <div class="mdc-switch__thumb"> <input type="checkbox" id="${id}" onchange=${onchange} class="mdc-switch__native-control" role="switch" ${checked ? 'checked' : ''} ${disabled ? 'disabled' : ''}> </div> </div> </div> ` } module.exports = switchToggle <|start_filename|>add-on/src/popup/browser-action/version-update-icon.js<|end_filename|> 'use strict' /* eslint-env browser, webextensions */ const html = require('choo/html') const icon = require('./icon') function versionUpdateIcon ({ newVersion, active, title, action, className, size = '1.8rem' }) { let svg = html` <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 86 86" class="fill-yellow-muted mr1" style="width:${size}; height:${size}"> <path xmlns="http://www.w3.org/2000/svg" d="M71.13 28.87a29.88 29.88 0 100 42.26 29.86 29.86 0 000-42.26zm-18.39 37.6h-5.48V44.71h5.48zm0-26.53h-5.48v-5.49h5.48z"/> </svg> ` // special handling for beta and dev builds // TODO: remove when we have no users on beta channel anymore if (newVersion.match(/\./g).length > 2) { svg = html` <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 86 86" class="fill-red-muted mr1" style="width:${size}; height:${size}"> <path d="M82.84 71.14L55.06 23a5.84 5.84 0 00-10.12 0L17.16 71.14a5.85 5.85 0 005.06 8.77h55.56a5.85 5.85 0 005.06-8.77zm-30.1-.66h-5.48V65h5.48zm0-10.26h-5.48V38.46h5.48z"/> </svg> ` title = 'Beta channel is deprecated, please switch to regular releases' className = `${className} blink` } return icon({ svg, title, active, action, className }) } module.exports = versionUpdateIcon <|start_filename|>scripts/prom-client-stub/index.js<|end_filename|> 'use strict' // This is a basic stub to build node-like js-ipfs // for use in Brave, but without prometheus libs which are not compatible // with browser context function Gauge () {} module.exports = { Gauge, register: { clear () { } } } <|start_filename|>add-on/src/lib/dnslink.js<|end_filename|> 'use strict' /* eslint-env browser */ const debug = require('debug') const log = debug('ipfs-companion:dnslink') log.error = debug('ipfs-companion:dnslink:error') const IsIpfs = require('is-ipfs') const LRU = require('lru-cache') const { default: PQueue } = require('p-queue') const { offlinePeerCount } = require('./state') const { ipfsContentPath, sameGateway, pathAtHttpGateway } = require('./ipfs-path') module.exports = function createDnslinkResolver (getState) { // DNSLink lookup result cache const cacheOptions = { max: 1000, maxAge: 1000 * 60 * 60 * 12 } const cache = new LRU(cacheOptions) // upper bound for concurrent background lookups done by resolve(url) const lookupQueue = new PQueue({ concurrency: 4 }) // preload of DNSLink data const preloadUrlCache = new LRU(cacheOptions) const preloadQueue = new PQueue({ concurrency: 4 }) const dnslinkResolver = { get _cache () { return cache }, setDnslink (fqdn, value) { cache.set(fqdn, value) }, clearCache () { cache.reset() }, cachedDnslink (fqdn) { return cache.get(fqdn) }, canLookupURL (requestUrl) { // skip URLs that could produce infinite recursion or weird loops const state = getState() return state.dnslinkPolicy && requestUrl.startsWith('http') && !IsIpfs.url(requestUrl) && !sameGateway(requestUrl, state.apiURL) && !sameGateway(requestUrl, state.gwURL) }, dnslinkAtGateway (url, dnslink) { if (typeof url === 'string') { url = new URL(url) } if (dnslinkResolver.canRedirectToIpns(url, dnslink)) { const state = getState() // redirect to IPNS and leave it up to the gateway // to load the correct path from IPFS // - https://github.com/ipfs/ipfs-companion/issues/298 const ipnsPath = dnslinkResolver.convertToIpnsPath(url) const gateway = state.redirect && state.localGwAvailable ? state.gwURLString : state.pubGwURLString return pathAtHttpGateway(ipnsPath, gateway) } }, readAndCacheDnslink (fqdn) { let dnslink = dnslinkResolver.cachedDnslink(fqdn) if (typeof dnslink === 'undefined') { try { log(`dnslink cache miss for '${fqdn}', running DNS TXT lookup`) dnslink = dnslinkResolver.readDnslinkFromTxtRecord(fqdn) if (dnslink) { // TODO: set TTL as maxAge: setDnslink(fqdn, dnslink, maxAge) dnslinkResolver.setDnslink(fqdn, dnslink) log(`found dnslink: '${fqdn}' -> '${dnslink}'`) } else { dnslinkResolver.setDnslink(fqdn, false) log(`found NO dnslink for '${fqdn}'`) } } catch (error) { log.error(`error in readAndCacheDnslink for '${fqdn}'`, error) } } else { // Most of the time we will hit cache, which makes below line is too noisy // console.info(`[ipfs-companion] using cached dnslink: '${fqdn}' -> '${dnslink}'`) } return dnslink }, // runs async lookup in a queue in the background and returns the record async resolve (url) { if (!dnslinkResolver.canLookupURL(url)) return const fqdn = new URL(url).hostname const cachedResult = dnslinkResolver.cachedDnslink(fqdn) if (cachedResult) return cachedResult return lookupQueue.add(() => { return dnslinkResolver.readAndCacheDnslink(fqdn) }) }, // preloads data behind the url to local node async preloadData (url) { const state = getState() if (!state.dnslinkDataPreload || state.dnslinkRedirect) return if (preloadUrlCache.get(url)) return preloadUrlCache.set(url, true) const dnslink = await dnslinkResolver.resolve(url) if (!dnslink) return if (!state.localGwAvailable) return if (state.peerCount < 1) return return preloadQueue.add(async () => { const { pathname } = new URL(url) const preloadUrl = new URL(state.gwURLString) preloadUrl.pathname = `${dnslink}${pathname}` await fetch(preloadUrl.toString(), { method: 'HEAD' }) return preloadUrl }) }, // low level lookup without cache readDnslinkFromTxtRecord (fqdn) { const state = getState() let apiProvider if (!state.ipfsNodeType.startsWith('embedded') && state.peerCount !== offlinePeerCount) { // Use gw port so it can be a GET: // Chromium does not execute onBeforeSendHeaders for synchronous calls // made from the same extension context as onBeforeSendHeaders // which means we are unable to fixup Origin on the fly for this // This will no longer be needed when we switch // to async lookup via ipfs.dns everywhere apiProvider = state.gwURLString } else { // fallback to resolver at public gateway apiProvider = 'https://ipfs.io/' } // js-ipfs-api does not provide method for fetching this // TODO: revisit after https://github.com/ipfs/js-ipfs-api/issues/501 is addressed // TODO: consider worst-case-scenario fallback to https://developers.google.com/speed/public-dns/docs/dns-over-https const apiCall = `${apiProvider}api/v0/name/resolve/${fqdn}?r=false` const xhr = new XMLHttpRequest() // older XHR API us used because window.fetch appends Origin which causes error 403 in go-ipfs // synchronous mode with small timeout // (it is okay, because we do it only once, then it is cached and read via readAndCacheDnslink) xhr.open('GET', apiCall, false) xhr.setRequestHeader('Accept', 'application/json') xhr.send(null) if (xhr.status === 200) { const dnslink = JSON.parse(xhr.responseText).Path // console.log('readDnslinkFromTxtRecord', readDnslinkFromTxtRecord) if (!IsIpfs.path(dnslink)) { throw new Error(`dnslink for '${fqdn}' is not a valid IPFS path: '${dnslink}'`) } return dnslink } else if (xhr.status === 500) { // go-ipfs returns 500 if host has no dnslink or an error occurred // TODO: find/fill an upstream bug to make this more intuitive return false } else { throw new Error(xhr.statusText) } }, canRedirectToIpns (url, dnslink) { if (typeof url === 'string') { url = new URL(url) } // Safety check: detect and skip gateway paths // Public gateways such as ipfs.io are often exposed under the same domain name. // We don't want dnslink to interfere with content-addressing redirects, // or things like /api/v0 paths exposed by the writable gateway // so we ignore known namespaces exposed by HTTP2IPFS gateways // and ignore them even if things like CID are invalid // -- we don't want to skew errors from gateway const path = url.pathname const httpGatewayPath = path.startsWith('/ipfs/') || path.startsWith('/ipns/') || path.startsWith('/api/v') if (!httpGatewayPath) { const fqdn = url.hostname // If dnslink policy is 'enabled' then lookups will be // executed for every unique hostname on every visited website. // Until we get efficient DNS TXT Lookup API there will be an overhead, // so 'enabled' policy is an opt-in for now. By default we use // 'best-effort' policy which does async lookups to populate dnslink cache // in the background and do blocking lookup only when X-Ipfs-Path header // is found in initial response. // More: https://github.com/ipfs-shipyard/ipfs-companion/blob/master/docs/dnslink.md const foundDnslink = dnslink || (getState().dnslinkPolicy === 'enabled' ? dnslinkResolver.readAndCacheDnslink(fqdn) : dnslinkResolver.cachedDnslink(fqdn)) if (foundDnslink) { return true } } return false }, convertToIpnsPath (url) { if (typeof url === 'string') { url = new URL(url) } return `/ipns/${url.hostname}${url.pathname}${url.search}${url.hash}` }, // Test if URL contains a valid DNSLink FQDN // in url.hostname OR in url.pathname (/ipns/<fqdn>) // and return matching FQDN if present findDNSLinkHostname (url) { if (!url) return // Normalize subdomain and path gateways to to /ipns/<fqdn> const contentPath = ipfsContentPath(url) if (IsIpfs.ipnsPath(contentPath)) { // we may have false-positives here, so we do additional checks below const ipnsRoot = contentPath.match(/^\/ipns\/([^/]+)/)[1] // console.log('findDNSLinkHostname ==> inspecting IPNS root', ipnsRoot) // Ignore PeerIDs, match DNSLink only if (!IsIpfs.cid(ipnsRoot) && dnslinkResolver.readAndCacheDnslink(ipnsRoot)) { // console.log('findDNSLinkHostname ==> found DNSLink for FQDN in url.pathname: ', ipnsRoot) return ipnsRoot } } // Check main hostname const { hostname } = new URL(url) if (dnslinkResolver.readAndCacheDnslink(hostname)) { // console.log('findDNSLinkHostname ==> found DNSLink for url.hostname', hostname) return hostname } } } return dnslinkResolver } <|start_filename|>test/functional/lib/ipfs-request-workarounds.test.js<|end_filename|> 'use strict' const { describe, it, before, beforeEach, after } = require('mocha') const { expect, assert } = require('chai') const { URL } = require('url') // URL implementation with support for .origin attribute const browser = require('sinon-chrome') const { initState } = require('../../../add-on/src/lib/state') const { createRuntimeChecks } = require('../../../add-on/src/lib/runtime-checks') const { createRequestModifier } = require('../../../add-on/src/lib/ipfs-request') const createDNSLinkResolver = require('../../../add-on/src/lib/dnslink') const { createIpfsPathValidator } = require('../../../add-on/src/lib/ipfs-path') const { optionDefaults } = require('../../../add-on/src/lib/options') const { braveNodeType } = require('../../../add-on/src/lib/ipfs-client/brave') const { spoofDnsTxtRecord } = require('./dnslink.test.js') // const nodeTypes = ['external', 'embedded'] describe('modifyRequest processing', function () { let state, getState, dnslinkResolver, ipfsPathValidator, modifyRequest, runtime before(function () { global.URL = URL global.browser = browser }) beforeEach(async function () { browser.runtime.getURL.flush() state = initState(optionDefaults) getState = () => state const getIpfs = () => {} dnslinkResolver = createDNSLinkResolver(getState) runtime = Object.assign({}, await createRuntimeChecks(browser)) // make it mutable for tests ipfsPathValidator = createIpfsPathValidator(getState, getIpfs, dnslinkResolver) modifyRequest = createRequestModifier(getState, dnslinkResolver, ipfsPathValidator, runtime) }) // Additional handling is required for redirected IPFS subresources on regular HTTPS pages // (eg. image embedded from public gateway on HTTPS website) describe('a subresource request on HTTPS website', function () { const cid = 'QmbWqxBEKC3P8tqsKc98xmWNzrzDtRLMiMPL8wBuTGsMnR' it('should be routed to "127.0.0.1" gw in Chromium if type is image', function () { runtime.isFirefox = false const request = { method: 'GET', type: 'image', url: `https://ipfs.io/ipfs/${cid}`, initiator: 'https://some-website.example.com' // Chromium } expect(modifyRequest.onBeforeRequest(request).redirectUrl) .to.equal(`http://127.0.0.1:8080/ipfs/${cid}`) }) it('should be routed to "localhost" gw in Chromium if not a subresource', function () { runtime.isFirefox = false const request = { method: 'GET', type: 'main_frame', url: `https://ipfs.io/ipfs/${cid}`, initiator: 'https://some-website.example.com' // Chromium } expect(modifyRequest.onBeforeRequest(request).redirectUrl) .to.equal(`http://localhost:8080/ipfs/${cid}`) }) it('should be routed to "127.0.0.1" gw to avoid mixed content warning in Firefox', function () { runtime.isFirefox = true const request = { method: 'GET', type: 'image', url: `https://ipfs.io/ipfs/${cid}`, originUrl: 'https://some-website.example.com/some/page.html' // FF only } expect(modifyRequest.onBeforeRequest(request).redirectUrl) .to.equal(`http://127.0.0.1:8080/ipfs/${cid}`) }) it('should be routed to "localhost" gw in Firefox if not a subresource', function () { runtime.isFirefox = true const request = { method: 'GET', type: 'main_frame', url: `https://ipfs.io/ipfs/${cid}`, originUrl: 'https://some-website.example.com/some/page.html' // FF only } expect(modifyRequest.onBeforeRequest(request).redirectUrl) .to.equal(`http://localhost:8080/ipfs/${cid}`) }) }) describe('a request to <apiURL>/api/v0/add with stream-channels=true', function () { const expectHeader = { name: 'Expect', value: '100-continue' } it('should apply the "Expect: 100-continue" fix for https://github.com/ipfs/go-ipfs/issues/5168 ', function () { const request = { method: 'POST', requestHeaders: [ { name: 'Content-Type', value: 'multipart/form-data; boundary=--------------------------015695779813832455524979' } ], type: 'xmlhttprequest', url: `${state.apiURLString}api/v0/add?progress=true&wrapWithDirectory=true&pin=true&wrap-with-directory=true&stream-channels=true` } modifyRequest.onBeforeRequest(request) // executes before onBeforeSendHeaders, may mutate state expect(modifyRequest.onBeforeSendHeaders(request).requestHeaders).to.deep.include(expectHeader) }) }) // The Origin header set by browser for requests coming from within a browser // extension has been a mess for years, and by now we simply have zero trust // in stability of this header. Instead, we use WebExtension's webRequest API // to tell if a request comes from our browser extension and manually set // Origin to look like a request coming from the same Origin as IPFS API. // // The full context can be found in ipfs-request.js, where isCompanionRequest // check is executed. describe('Origin header in a request to <apiURL>/api/v0/', function () { it('set to API if request comes from Companion in Firefox <85', async function () { // Context: Firefox 65 started setting this header // set vendor-specific Origin for WebExtension context browser.runtime.getURL.withArgs('/').returns('moz-extension://0f334731-19e3-42f8-85e2-03dbf50026df/') // ensure clean modifyRequest runtime = Object.assign({}, await createRuntimeChecks(browser)) // make it mutable for tests modifyRequest = createRequestModifier(getState, dnslinkResolver, ipfsPathValidator, runtime) // test const originalOriginHeader = { name: 'Origin', value: 'moz-extension://0f334731-19e3-42f8-85e2-03dbf50026df' } const apiOriginHeader = { name: 'Origin', value: getState().apiURL.origin } const request = { requestHeaders: [originalOriginHeader], originUrl: 'moz-extension://0f334731-19e3-42f8-85e2-03dbf50026df/path/to/background.html', // FF specific WebExtension API type: 'xmlhttprequest', url: `${state.apiURLString}api/v0/id` } modifyRequest.onBeforeRequest(request) // executes before onBeforeSendHeaders, may mutate state expect(modifyRequest.onBeforeSendHeaders(request).requestHeaders) .to.deep.include(apiOriginHeader) }) it('set to API if request comes from Companion in Firefox 85', async function () { // Context: https://github.com/ipfs-shipyard/ipfs-companion/issues/955#issuecomment-753413988 browser.runtime.getURL.withArgs('/').returns('moz-extension://0f334731-19e3-42f8-85e2-03dbf50026df/') // ensure clean modifyRequest runtime = Object.assign({}, await createRuntimeChecks(browser)) // make it mutable for tests modifyRequest = createRequestModifier(getState, dnslinkResolver, ipfsPathValidator, runtime) // test const originalOriginHeader = { name: 'Origin', value: 'null' } const apiOriginHeader = { name: 'Origin', value: getState().apiURL.origin } const request = { requestHeaders: [originalOriginHeader], originUrl: 'moz-extension://0f334731-19e3-42f8-85e2-03dbf50026df/path/to/background.html', // FF specific WebExtension API type: 'xmlhttprequest', url: `${state.apiURLString}api/v0/id` } modifyRequest.onBeforeRequest(request) // executes before onBeforeSendHeaders, may mutate state expect(modifyRequest.onBeforeSendHeaders(request).requestHeaders) .to.deep.include(apiOriginHeader) }) it('set to API if request comes from Companion in Chromium <72', async function () { // set vendor-specific Origin for WebExtension context browser.runtime.getURL.withArgs('/').returns('chrome-extension://nibjojkomfdiaoajekhjakgkdhaomnch/') // ensure clean modifyRequest runtime = Object.assign({}, await createRuntimeChecks(browser)) // make it mutable for tests modifyRequest = createRequestModifier(getState, dnslinkResolver, ipfsPathValidator, runtime) // test const bogusOriginHeader = { name: 'Origin', value: 'null' } const apiOriginHeader = { name: 'Origin', value: getState().apiURL.origin } const request = { requestHeaders: [bogusOriginHeader], initiator: 'chrome-extension://nibjojkomfdiaoajekhjakgkdhaomnch/', // Chromium specific WebExtension API type: 'xmlhttprequest', url: `${state.apiURLString}api/v0/id` } modifyRequest.onBeforeRequest(request) // executes before onBeforeSendHeaders, may mutate state expect(modifyRequest.onBeforeSendHeaders(request).requestHeaders) .to.deep.include(apiOriginHeader) }) it('set to API if request comes from Companion in Chromium 72', async function () { // Context: Chromium 72 started setting this header to chrome-extension:// URI // set vendor-specific Origin for WebExtension context browser.runtime.getURL.withArgs('/').returns('chrome-extension://nibjojkomfdiaoajekhjakgkdhaomnch/') // ensure clean modifyRequest runtime = Object.assign({}, await createRuntimeChecks(browser)) // make it mutable for tests modifyRequest = createRequestModifier(getState, dnslinkResolver, ipfsPathValidator, runtime) // test const bogusOriginHeader = { name: 'Origin', value: 'chrome-extension://nibjojkomfdiaoajekhjakgkdhaomnch' } const apiOriginHeader = { name: 'Origin', value: getState().apiURL.origin } const request = { requestHeaders: [bogusOriginHeader], initiator: 'chrome-extension://nibjojkomfdiaoajekhjakgkdhaomnch/', // Chromium specific WebExtension API type: 'xmlhttprequest', url: `${state.apiURLString}api/v0/id` } modifyRequest.onBeforeRequest(request) // executes before onBeforeSendHeaders, may mutate state expect(modifyRequest.onBeforeSendHeaders(request).requestHeaders) .to.deep.include(apiOriginHeader) }) it('keep Origin as-is if request does not come from Companion (Chromium)', async function () { browser.runtime.getURL.withArgs('/').returns('chrome-extension://nibjojkomfdiaoajekhjakgkdhaomnch/') // ensure clean modifyRequest runtime = Object.assign({}, await createRuntimeChecks(browser)) // make it mutable for tests modifyRequest = createRequestModifier(getState, dnslinkResolver, ipfsPathValidator, runtime) // test const originHeader = { name: 'Origin', value: 'https://some.website.example.com' } const expectedOriginHeader = { name: 'Origin', value: 'https://some.website.example.com' } const request = { requestHeaders: [originHeader], initiator: 'https://some.website.example.com', // Chromium specific WebExtension API type: 'xmlhttprequest', url: `${state.apiURLString}api/v0/id` } modifyRequest.onBeforeRequest(request) // executes before onBeforeSendHeaders, may mutate state expect(modifyRequest.onBeforeSendHeaders(request).requestHeaders) .to.deep.include(expectedOriginHeader) }) it('keep Origin as-is if request does not come from Companion (Firefox)', async function () { browser.runtime.getURL.withArgs('/').returns('moz-extension://0f334731-19e3-42f8-85e2-03dbf50026df/') // ensure clean modifyRequest runtime = Object.assign({}, await createRuntimeChecks(browser)) // make it mutable for tests modifyRequest = createRequestModifier(getState, dnslinkResolver, ipfsPathValidator, runtime) // test const originHeader = { name: 'Origin', value: 'https://some.website.example.com' } const expectedOriginHeader = { name: 'Origin', value: 'https://some.website.example.com' } const request = { requestHeaders: [originHeader], originUrl: 'https://some.website.example.com/some/path.html', // Firefox specific WebExtension API type: 'xmlhttprequest', url: `${state.apiURLString}api/v0/id` } modifyRequest.onBeforeRequest(request) // executes before onBeforeSendHeaders, may mutate state expect(modifyRequest.onBeforeSendHeaders(request).requestHeaders) .to.deep.include(expectedOriginHeader) }) it('keep the "Origin: null" if request does not come from Companion (Chromium)', async function () { // Presence of Origin header is important as it protects API from XSS via sandboxed iframe // NOTE: Chromium <72 was setting this header in requests sent by browser extension, // but they fixed it since then, and we switched to reading origin via webRequest API, // which is independent from the HTTP header. browser.runtime.getURL.withArgs('/').returns('chrome-extension://nibjojkomfdiaoajekhjakgkdhaomnch/') // ensure clean modifyRequest runtime = Object.assign({}, await createRuntimeChecks(browser)) // make it mutable for tests modifyRequest = createRequestModifier(getState, dnslinkResolver, ipfsPathValidator, runtime) // test const nullOriginHeader = { name: 'Origin', value: 'null' } const expectedOriginHeader = { name: 'Origin', value: 'null' } const request = { requestHeaders: [nullOriginHeader], initiator: 'https://random.website.example.com', // Chromium specific WebExtension API type: 'xmlhttprequest', url: `${state.apiURLString}api/v0/id` } modifyRequest.onBeforeRequest(request) // executes before onBeforeSendHeaders, may mutate state expect(modifyRequest.onBeforeSendHeaders(request).requestHeaders) .to.deep.include(expectedOriginHeader) }) it('keep the "Origin: null" if request does not come from Companion (Firefox)', async function () { // Presence of Origin header is important as it protects API from XSS via sandboxed iframe browser.runtime.getURL.withArgs('/').returns('moz-extension://0f334731-19e3-42f8-85e2-03dbf50026df/') // ensure clean modifyRequest runtime = Object.assign({}, await createRuntimeChecks(browser)) // make it mutable for tests modifyRequest = createRequestModifier(getState, dnslinkResolver, ipfsPathValidator, runtime) // test const nullOriginHeader = { name: 'Origin', value: 'null' } const expectedOriginHeader = { name: 'Origin', value: 'null' } const request = { requestHeaders: [nullOriginHeader], originUrl: 'https://random.website.example.com/some/path.html', // Firefox specific WebExtension API type: 'xmlhttprequest', url: `${state.apiURLString}api/v0/id` } modifyRequest.onBeforeRequest(request) // executes before onBeforeSendHeaders, may mutate state expect(modifyRequest.onBeforeSendHeaders(request).requestHeaders) .to.deep.include(expectedOriginHeader) }) }) // We've moved blog to blog.ipfs.io but links to ipfs.io/blog/* // are still around due to the way Discourse integration was done for comments. // https://github.com/ipfs/blog/issues/360 describe('a failed main_frame request to /ipns/ipfs.io/blog', function () { it('should be updated to /ipns/blog.ipfs.io', async function () { const brokenDNSLinkUrl = 'http://example.com/ipns/ipfs.io/blog/some-post' const fixedDNSLinkUrl = 'http://example.com/ipns/blog.ipfs.io/some-post' // ensure clean modifyRequest runtime = Object.assign({}, await createRuntimeChecks(browser)) // make it mutable for tests modifyRequest = createRequestModifier(getState, dnslinkResolver, ipfsPathValidator, runtime) // test const request = { tabId: 42404, statusCode: 404, type: 'main_frame', url: brokenDNSLinkUrl } browser.tabs.update.flush() assert.ok(browser.tabs.update.withArgs(request.tabId, { url: fixedDNSLinkUrl }).notCalled) modifyRequest.onCompleted(request) assert.ok(browser.tabs.update.withArgs(request.tabId, { url: fixedDNSLinkUrl }).calledOnce) browser.tabs.update.flush() }) }) // Brave seems to ignore redirect to ipfs:// and ipns://, but if we force tab update via tabs API, // then address bar is correct describe('redirect of main_frame request to local gateway when Brave node is used', function () { it('should force native URI in address bar via tabs.update API', async function () { const httpDNSLinkUrl = 'https://example.com/ipns/docs.ipfs.io/some/path?query=val' const nativeDNSLinkUri = 'ipns://docs.ipfs.io/some/path?query=val' spoofDnsTxtRecord('docs.ipfs.io', dnslinkResolver, '/ipfs/bafkqae2xmvwgg33nmuqhi3zajfiemuzahiwss') state.ipfsNodeType = braveNodeType // ensure clean modifyRequest runtime = Object.assign({}, await createRuntimeChecks(browser)) // make it mutable for tests modifyRequest = createRequestModifier(getState, dnslinkResolver, ipfsPathValidator, runtime) // test const request = { tabId: 42, type: 'main_frame', url: httpDNSLinkUrl } browser.tabs.update.flush() assert.ok(browser.tabs.update.withArgs(request.tabId, { url: nativeDNSLinkUri }).notCalled) await modifyRequest.onBeforeRequest(request) assert.ok(browser.tabs.update.withArgs(request.tabId, { url: nativeDNSLinkUri }).calledOnce) browser.tabs.update.flush() }) }) // https://github.com/ipfs-shipyard/ipfs-companion/issues/962 describe('redirect of IPFS resource to local gateway in Brave', function () { it('should be redirected if not a subresource (not impacted by Brave Shields)', function () { runtime.isFirefox = false runtime.brave = { thisIsFakeBraveRuntime: true } const request = { method: 'GET', type: 'image', url: 'https://ipfs.io/ipfs/bafkqae2xmvwgg33nmuqhi3zajfiemuzahiwss', initiator: 'https://some-website.example.com' // Brave (built on Chromium) } expect(modifyRequest.onBeforeRequest(request)) .to.equal(undefined) }) it('should be left untouched if subresource (would be blocked by Brave Shields)', function () { runtime.isFirefox = false runtime.brave = { thisIsFakeBraveRuntime: true } const cid = 'bafkqae2xmvwgg33nmuqhi3zajfiemuzahiwss' const request = { method: 'GET', type: 'main_frame', url: `https://ipfs.io/ipfs/${cid}`, initiator: 'https://some-website.example.com' // Brave (built on Chromium) } expect(modifyRequest.onBeforeRequest(request).redirectUrl) .to.equal(`http://localhost:8080/ipfs/${cid}`) }) }) after(function () { delete global.URL delete global.browser browser.flush() }) }) <|start_filename|>add-on/src/popup/browser-action/ipfs-version.js<|end_filename|> 'use strict' /* eslint-env browser, webextensions */ const browser = require('webextension-polyfill') const html = require('choo/html') function statusEntry ({ label, labelLegend, title, value, check, valueClass = '' }) { const offline = browser.i18n.getMessage('panel_statusOffline') label = label ? browser.i18n.getMessage(label) : null labelLegend = labelLegend ? browser.i18n.getMessage(labelLegend) : label value = value || value === 0 ? value : offline return html` <div title="${labelLegend}" class="ma0 pa0" style="line-height: 0.25"> <span class="f7 tr monospace force-select-all ${valueClass}" title="${title}">${value.substring(0, 13)}</span> </div> ` } module.exports = function ipfsVersion ({ gatewayVersion }) { return html` ${statusEntry({ label: 'panel_statusGatewayVersion', title: browser.i18n.getMessage('panel_statusGatewayVersionTitle'), value: gatewayVersion, check: gatewayVersion })} ` } <|start_filename|>add-on/src/popup/browser-action/redirect-icon.js<|end_filename|> 'use strict' /* eslint-env browser, webextensions */ const html = require('choo/html') const icon = require('./icon') function redirectIcon ({ active, title, action, size = '2rem' }) { const svg = html` <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" class="fill-current-color" style="width:${size}; height:${size}"> <path d="M75.4 41.6l-7.3-11.2c-.1-.2-.4-.2-.5 0l-7.3 11.3c-.1.2 0 .4.2.4h4.3l-.2 20.6c0 3.2-2.6 5.8-5.8 5.8h-.2a5.8 5.8 0 0 1-5.8-5.8V37.3a11.8 11.8 0 0 0-23.6 0L29 58.7h-4.3c-.2 0-.4.3-.3.5l7.3 11.6c.1.2.4.2.6 0l7.3-11.6c.1-.2 0-.5-.3-.5h-4.2l.2-21.5a5.8 5.8 0 0 1 11.6 0v25.3c0 6.5 5.3 11.8 11.8 11.8h.2c6.5 0 11.8-5.3 11.8-11.8l.2-20.4h4.4c.4 0 .2-.4.1-.5z"/> </svg> ` return icon({ svg, title, active, action }) } module.exports = redirectIcon <|start_filename|>add-on/src/options/forms/file-import-form.js<|end_filename|> 'use strict' /* eslint-env browser, webextensions */ const browser = require('webextension-polyfill') const html = require('choo/html') const switchToggle = require('../../pages/components/switch-toggle') function fileImportForm ({ importDir, openViaWebUI, preloadAtPublicGateway, onOptionChange }) { const onImportDirChange = onOptionChange('importDir') const onOpenViaWebUIChange = onOptionChange('openViaWebUI') const onPreloadAtPublicGatewayChange = onOptionChange('preloadAtPublicGateway') return html` <form> <fieldset class="mb3 pa1 pa4-ns pa3 bg-snow-muted charcoal"> <h2 class="ttu tracked f6 fw4 teal mt0-ns mb3-ns mb1 mt2 ">${browser.i18n.getMessage('option_header_fileImport')}</h2> <div class="flex-row-ns pb0-ns"> <label for="importDir"> <dl> <dt>${browser.i18n.getMessage('option_importDir_title')}</dt> <dd> ${browser.i18n.getMessage('option_importDir_description')} <p><a class="link underline hover-aqua" href="https://docs.ipfs.io/concepts/file-systems/#mutable-file-system-mfs" target="_blank"> ${browser.i18n.getMessage('option_legend_readMore')} </a></p> </dd> </dl> </label> <input class="bg-white navy self-center-ns" id="importDir" type="text" pattern="^\/(.*)" required onchange=${onImportDirChange} value=${importDir} /> </div> <div class="flex-row-ns pb0-ns"> <label for="openViaWebUI"> <dl> <dt>${browser.i18n.getMessage('option_openViaWebUI_title')}</dt> <dd>${browser.i18n.getMessage('option_openViaWebUI_description')}</dd> </dl> </label> <div class="self-center-ns">${switchToggle({ id: 'openViaWebUI', checked: openViaWebUI, onchange: onOpenViaWebUIChange })}</div> </div> <div class="flex-row-ns pb0-ns"> <label for="preloadAtPublicGateway"> <dl> <dt>${browser.i18n.getMessage('option_preloadAtPublicGateway_title')}</dt> <dd>${browser.i18n.getMessage('option_preloadAtPublicGateway_description')}</dd> </dl> </label> <div class="self-center-ns">${switchToggle({ id: 'preloadAtPublicGateway', checked: preloadAtPublicGateway, onchange: onPreloadAtPublicGatewayChange })}</div> </div> </fieldset> </form> ` } module.exports = fileImportForm <|start_filename|>test/functional/lib/runtime-checks.test.js<|end_filename|> 'use strict' /* eslint-env browser, webextensions */ const { describe, it, before, beforeEach, after } = require('mocha') const { expect } = require('chai') const browser = require('sinon-chrome') const { createRuntimeChecks } = require('../../../add-on/src/lib/runtime-checks') const promiseStub = (result) => () => Promise.resolve(result) describe('runtime-checks.js', function () { before(() => { global.browser = browser global.chrome = {} }) beforeEach(function () { browser.flush() }) describe('isFirefox', function () { beforeEach(function () { browser.flush() }) it('should return true when in Firefox runtime', async function () { browser.runtime.getBrowserInfo = promiseStub({ name: 'Firefox' }) const runtime = await createRuntimeChecks(browser) expect(runtime.isFirefox).to.equal(true) }) it('should return false when not in Firefox runtime', async function () { browser.runtime.getBrowserInfo = promiseStub({ name: 'SomethingElse' }) const runtime = await createRuntimeChecks(browser) expect(runtime.isFirefox).to.equal(false) }) }) describe('requiresXHRCORSfix', function () { beforeEach(function () { browser.flush() }) it('should return true when in Firefox runtime < 69', async function () { browser.runtime.getBrowserInfo = promiseStub({ name: 'Firefox', version: '68.0.0' }) const runtime = await createRuntimeChecks(browser) expect(runtime.requiresXHRCORSfix).to.equal(true) }) it('should return false when in Firefox runtime >= 69', async function () { browser.runtime.getBrowserInfo = promiseStub({ name: 'Firefox', version: '69.0.0' }) const runtime = await createRuntimeChecks(browser) expect(runtime.requiresXHRCORSfix).to.equal(false) }) it('should return false when if getBrowserInfo is not present', async function () { browser.runtime.getBrowserInfo = undefined const runtime = await createRuntimeChecks(browser) expect(runtime.requiresXHRCORSfix).to.equal(false) }) }) describe('isAndroid', function () { beforeEach(function () { browser.flush() }) it('should return true when in Android runtime', async function () { browser.runtime.getPlatformInfo.returns({ os: 'android' }) const runtime = await createRuntimeChecks(browser) expect(runtime.isAndroid).to.equal(true) }) it('should return false when not in Android runtime', async function () { browser.runtime.getPlatformInfo.returns({ name: 'SomethingElse' }) const runtime = await createRuntimeChecks(browser) expect(runtime.isAndroid).to.equal(false) }) }) describe('hasNativeProtocolHandler', function () { beforeEach(function () { browser.flush() }) it('should return true when browser.protocol namespace is present', async function () { // pretend API is in place browser.protocol = {} browser.protocol.registerStringProtocol = () => Promise.resolve({}) const runtime = await createRuntimeChecks(browser) expect(runtime.hasNativeProtocolHandler).to.equal(true) }) it('should return false browser.protocol APIs are missing', async function () { // API is missing browser.protocol = undefined const runtime = await createRuntimeChecks(browser) expect(runtime.hasNativeProtocolHandler).to.equal(false) }) }) after(function () { delete global.browser browser.flush() }) }) <|start_filename|>add-on/src/pages/proxy-acl/page.js<|end_filename|> 'use strict' const html = require('choo/html') const logo = require('../../popup/logo') function createProxyAclPage (i18n) { return function proxyAclPage (state, emit) { const onRevoke = (e) => emit('revoke', e) const onToggleAllow = (e) => emit('toggleAllow', e) const { acl } = state const scopes = Array.from(state.acl.keys()) const hasGrants = scopes.some((scope) => !!acl.get(scope).size) return html` <div class="avenir pt5" style="background: linear-gradient(to top, #041727 0%,#043b55 100%); min-height:100%;"> <div class="mw8 center pa3 white"> <header class="flex items-center mb4"> ${logo({ size: 80, path: '../../../icons', heartbeat: false })} <div class="pl3"> <h1 class="f2 fw5 ma0"> ${i18n.getMessage('page_proxyAcl_title')} </h1> <p class="f3 fw2 lh-copy ma0 light-gray"> ${i18n.getMessage('page_proxyAcl_subtitle')} </p> </div> </header> ${hasGrants ? html`<table class="w-100 mb4" style="border-spacing: 0"> ${scopes.reduce((rows, scope) => { const permissions = acl.get(scope) if (!permissions.size) return rows return rows.concat( scopeRow({ onRevoke, scope, i18n }), Array.from(permissions.keys()) .sort() .map((permission) => accessRow({ scope, permission, allow: permissions.get(permission), onRevoke, onToggleAllow, i18n })) ) }, [])} </table> ` : html`<p class="f5 light-gray i">${i18n.getMessage('page_proxyAcl_no_perms')}</p>`} </div> </div> ` } } module.exports = createProxyAclPage function scopeRow ({ scope, onRevoke, i18n }) { return html` <tr class=""> <th class="f3 normal tl light-gray pv3 ph2 bb b--white-40" colspan="2">${scope}</th> <th class="tr pv3 ph0 bb b--white-40">${revokeButton({ onRevoke, scope, i18n })}</th> </tr> ` } function accessRow ({ scope, permission, allow, onRevoke, onToggleAllow, i18n }) { const title = i18n.getMessage( allow ? 'page_proxyAcl_toggle_to_deny_button_title' : 'page_proxyAcl_toggle_to_allow_button_title' ) return html` <tr class="bg-animate hover-bg-white-o-005 hide-child"> <td class="f5 white ph3 pv2 ${allow ? 'bg-green' : 'bg-red'} tc bb b--white-10 pointer" style="width: 75px" onclick=${onToggleAllow} data-scope="${scope}" data-permission="${permission}" data-allow=${allow} title="${title}"> ${i18n.getMessage(allow ? 'page_proxyAcl_allow_button_value' : 'page_proxyAcl_deny_button_value')} </td> <td class="f5 light-gray ph3 pv2 bb b--white-10">${permission}</td> <td class="tr bb b--white-10"> <div class="child"> ${revokeButton({ onRevoke, scope, permission, i18n })} </div> </td> </tr> ` } function revokeButton ({ onRevoke, scope, permission = null, i18n }) { const title = permission ? i18n.getMessage('page_proxyAcl_revoke_button_title', permission) : i18n.getMessage('page_proxyAcl_revoke_all_button_title') return html` <button class="button-reset outline-0 bg-transparent bw0 pointer ph3 pv1 light-gray hover-red" onclick=${onRevoke} data-scope="${scope}" data-permission="${permission || ''}" title="${title}"> ${closeIcon()} </button> ` } function closeIcon () { return html` <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="21" height="21"> <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z " /> </svg> ` } <|start_filename|>add-on/manifest.chromium.json<|end_filename|> { "minimum_chrome_version": "72", "permissions": [ "<all_urls>", "idle", "tabs", "notifications", "storage", "unlimitedStorage", "contextMenus", "clipboardWrite", "webNavigation", "webRequest", "webRequestBlocking" ], "incognito": "not_allowed" } <|start_filename|>add-on/src/popup/browser-action/options-icon.js<|end_filename|> 'use strict' /* eslint-env browser, webextensions */ const html = require('choo/html') const icon = require('./icon') function optionsIcon ({ active, title, action, size = '1.8rem' }) { const svg = html` <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 86 86" class="fill-current-color" style="width:${size}; height:${size}"> <path d="M74.05 50.23c-.07-3.58 1.86-5.85 5.11-7.1-.2-2-2.48-7.45-3.63-8.76-3.11 1.46-6.06 1.23-8.54-1.22s-2.72-5.46-1.26-8.64a29.24 29.24 0 0 0-8.8-3.63c-1.06 3.08-3.12 5-6.35 5.25-3.82.29-6.29-1.69-7.61-5.22a30.11 30.11 0 0 0-8.77 3.67c1.5 3.16 1.3 6.1-1.15 8.6s-5.45 2.76-8.64 1.29a29.33 29.33 0 0 0-3.58 8.79C24 44.43 25.94 46.62 26 50s-1.82 5.84-5.1 7.12a29.21 29.21 0 0 0 3.68 8.71c3.09-1.38 6-1.15 8.42 1.22s2.79 5.33 1.41 8.49a29.72 29.72 0 0 0 8.76 3.57 1.46 1.46 0 0 0 .11-.21 7.19 7.19 0 0 1 13.53-.16c.13.33.28.32.55.25a29.64 29.64 0 0 0 8-3.3 4 4 0 0 0 .37-.25c-1.27-2.86-1.15-5.57.88-7.94 2.44-2.84 5.5-3.26 8.91-1.8a29.23 29.23 0 0 0 3.65-8.7c-3.17-1.22-5.05-3.38-5.12-6.77zM50 59.54a8.57 8.57 0 1 1 8.59-8.31A8.58 8.58 0 0 1 50 59.54z"/> </svg> ` return icon({ svg, title, active, action }) } module.exports = optionsIcon <|start_filename|>add-on/src/lib/constants.js<|end_filename|> 'use strict' /* eslint-env browser, webextensions */ exports.welcomePage = '/dist/landing-pages/welcome/index.html' exports.optionsPage = '/dist/options/options.html' exports.tickMs = 250 // no CPU spike, but still responsive enough <|start_filename|>add-on/src/lib/inspector.js<|end_filename|> 'use strict' const browser = require('webextension-polyfill') const { findValueForContext } = require('./context-menus') const { pathAtHttpGateway } = require('./ipfs-path') function createInspector (notify, ipfsPathValidator, getState) { return { async viewOnGateway (context, contextType) { const url = await findValueForContext(context, contextType) const ipfsPath = ipfsPathValidator.resolveToIpfsPath(url) const gateway = getState().pubGwURLString const gatewayUrl = pathAtHttpGateway(ipfsPath, gateway) await browser.tabs.create({ url: gatewayUrl }) } // TODO: view in WebUI's Files // TODO: view in WebUI's IPLD Explorer } } module.exports = createInspector <|start_filename|>add-on/src/popup/browser-action/header.js<|end_filename|> 'use strict' /* eslint-env browser, webextensions */ const html = require('choo/html') const logo = require('../logo') const versionUpdateIcon = require('./version-update-icon') const powerIcon = require('./power-icon') const optionsIcon = require('./options-icon') const ipfsVersion = require('./ipfs-version') const gatewayStatus = require('./gateway-status') module.exports = function header (props) { const { ipfsNodeType, active, onToggleActive, onOpenPrefs, onOpenReleaseNotes, isIpfsOnline, onOpenWelcomePage, newVersion } = props return html` <div> <div class="pt3 pr3 pb2 pl3 no-user-select flex justify-between items-center"> <div class="inline-flex items-center"> <div onclick=${onOpenWelcomePage} class="transition-all pointer ${active ? '' : 'o-40'}" style="${active ? '' : 'filter: blur( .15em )'}"> ${logo({ size: 54, path: '../../../icons', ipfsNodeType, isIpfsOnline: (active && isIpfsOnline) })} </div> <div class="flex flex-column ml2 white ${active ? '' : 'o-40'}"> <div> <h1 class="inter fw6 f2 ttu ma0 pa0"> IPFS </h1> </div> <span class="${active ? '' : 'o-0'}">${ipfsVersion(props)}</span> </div> </div> <div class="tr ma0 pb1"> ${newVersion ? versionUpdateIcon({ newVersion, active, title: 'panel_headerNewVersionTitle', action: onOpenReleaseNotes }) : null} ${powerIcon({ active, title: 'panel_headerActiveToggleTitle', action: onToggleActive })} ${optionsIcon({ active, title: 'panel_openPreferences', action: onOpenPrefs })} </div> </div> <div class="pb1 ${active ? '' : 'o-40'}"> ${gatewayStatus(props)} </div> </div> ` } <|start_filename|>add-on/manifest.brave-beta.json<|end_filename|> { "key": "<KEY>" } <|start_filename|>test/functional/lib/ipfs-import.test.js<|end_filename|> 'use strict' const { describe, it, before, after } = require('mocha') const { expect } = require('chai') const { useFakeTimers } = require('sinon') const browser = require('sinon-chrome') describe('ipfs-import.js', function () { let formatImportDirectory before(function () { global.document = {} global.browser = browser // ipfs-import depends on webextension/polyfill which can't be imported // in a non-browser environment unless global.browser is stubbed // need to force Date to return a particular date global.clock = useFakeTimers({ now: new Date(2017, 10, 5, 12, 1, 1) }) formatImportDirectory = require('../../../add-on/src/lib/ipfs-import').formatImportDirectory }) describe('formatImportDirectory', function () { it('should change nothing if path is properly formatted and date wildcards are not provided', function () { const path = '/ipfs-companion-imports/my-directory/' expect(formatImportDirectory(path)).to.equal('/ipfs-companion-imports/my-directory/') }) it('should replace two successive slashes with a single slash', function () { const path = '/ipfs-companion-imports//my-directory/' expect(formatImportDirectory(path)).to.equal('/ipfs-companion-imports/my-directory/') }) it('should replace multiple slashes with a single slash', function () { const path = '/ipfs-companion-imports/////////my-directory/' expect(formatImportDirectory(path)).to.equal('/ipfs-companion-imports/my-directory/') }) it('should add trailing slash if not present', function () { const path = '/ipfs-companion-imports/my-directory' expect(formatImportDirectory(path)).to.equal('/ipfs-companion-imports/my-directory/') }) it('should replace date wildcards with padded dates', function () { const path = '/ipfs-companion-imports/%Y-%M-%D_%h%m%s/' expect(formatImportDirectory(path)).to.equal('/ipfs-companion-imports/2017-11-05_120101/') }) }) // TODO: complete tests // describe('openFilesAtWebUI', function () { // }) // // describe('openFilesAtGateway', function () { // }) // // describe('importFiles', function () { // }) after(function () { global.browser.flush() global.clock.restore() delete global.document delete global.browser }) }) <|start_filename|>add-on/src/pages/proxy-access-dialog/proxy-access-dialog.css<|end_filename|> @import url('~tachyons/css/tachyons.css'); @import url('~ipfs-css/ipfs.css'); .hover-bg-aqua-muted:hover { background-color: #9ad4db; } .hover-bg-red-muted:hover { background-color: #f36149; } label:hover, button:hover { cursor: pointer; } <|start_filename|>add-on/src/lib/ipfs-client/index.js<|end_filename|> 'use strict' /* eslint-env browser, webextensions */ const debug = require('debug') const log = debug('ipfs-companion:client') log.error = debug('ipfs-companion:client:error') const external = require('./external') const embedded = require('./embedded') const brave = require('./brave') const { precache } = require('../precache') // ensure single client at all times, and no overlap between init and destroy let client async function initIpfsClient (browser, opts) { log('init ipfs client') if (client) return // await destroyIpfsClient() let backend switch (opts.ipfsNodeType) { case 'embedded:chromesockets': // TODO: remove this one-time migration after in second half of 2021 setTimeout(async () => { log('converting embedded:chromesockets to native external:brave') opts.ipfsNodeType = 'external:brave' await browser.storage.local.set({ ipfsNodeType: 'external:brave', ipfsNodeConfig: '{}' // remove chrome-apps config }) await browser.tabs.create({ url: 'https://docs.ipfs.io/how-to/companion-node-types/#native' }) }, 0) // Halt client init throw new Error('Embedded + chrome.sockets is deprecated. Switching to Native IPFS in Brave.') case 'embedded': backend = embedded break case 'external:brave': backend = brave break case 'external': backend = external break default: throw new Error(`Unsupported ipfsNodeType: ${opts.ipfsNodeType}`) } const instance = await backend.init(browser, opts) _reloadIpfsClientDependents(browser, instance, opts) // async (API is present) client = backend return instance } async function destroyIpfsClient (browser) { log('destroy ipfs client') if (!client) return try { await client.destroy(browser) await _reloadIpfsClientDependents(browser) // sync (API stopped working) } finally { client = null } } function _isWebuiTab (url) { const bundled = !url.startsWith('http') && url.includes('/webui/index.html#/') const ipns = url.includes('/webui.ipfs.io/#/') return bundled || ipns } function _isInternalTab (url, extensionOrigin) { return url.startsWith(extensionOrigin) } async function _reloadIpfsClientDependents (browser, instance, opts) { // online || offline if (browser.tabs && browser.tabs.query) { const tabs = await browser.tabs.query({}) if (tabs) { const extensionOrigin = browser.runtime.getURL('/') tabs.forEach((tab) => { // detect bundled webui in any of open tabs if (_isWebuiTab(tab.url)) { log(`reloading webui at ${tab.url}`) browser.tabs.reload(tab.id) } else if (_isInternalTab(tab.url, extensionOrigin)) { log(`reloading internal extension page at ${tab.url}`) browser.tabs.reload(tab.id) } }) } } // online only if (client && instance && opts) { // add important data to local ipfs repo for instant load setTimeout(() => precache(instance, opts), 5000) } } exports.initIpfsClient = initIpfsClient exports.destroyIpfsClient = destroyIpfsClient <|start_filename|>add-on/src/lib/state.js<|end_filename|> 'use strict' /* eslint-env browser, webextensions */ const { safeURL, isHostname } = require('./options') const offlinePeerCount = -1 function initState (options, overrides) { // we store options and some pregenerated values to avoid async storage // reads and minimize performance impact on overall browsing experience const state = Object.assign({}, options) // generate some additional values state.peerCount = offlinePeerCount state.pubGwURL = safeURL(options.publicGatewayUrl) state.pubGwURLString = state.pubGwURL.toString() delete state.publicGatewayUrl state.pubSubdomainGwURL = safeURL(options.publicSubdomainGatewayUrl) state.pubSubdomainGwURLString = state.pubSubdomainGwURL.toString() delete state.publicSubdomainGatewayUrl state.redirect = options.useCustomGateway delete state.useCustomGateway state.apiURL = safeURL(options.ipfsApiUrl, { useLocalhostName: false }) // go-ipfs returns 403 if IP is beautified to 'localhost' state.apiURLString = state.apiURL.toString() delete state.ipfsApiUrl state.gwURL = safeURL(options.customGatewayUrl, { useLocalhostName: state.useSubdomains }) state.gwURLString = state.gwURL.toString() delete state.customGatewayUrl state.dnslinkPolicy = String(options.dnslinkPolicy) === 'false' ? false : options.dnslinkPolicy // attach helper functions state.activeIntegrations = (url) => { if (!state.active) return false try { const hostname = isHostname(url) ? url : new URL(url).hostname // opt-out has more weight, we also match parent domains const disabledDirectlyOrIndirectly = state.disabledOn.some(optout => hostname.endsWith(optout)) // ..however direct opt-in should overwrite parent's opt-out const enabledDirectly = state.enabledOn.some(optin => optin === hostname) return !(disabledDirectlyOrIndirectly && !enabledDirectly) } catch (_) { return false } } // TODO state.connected ~= state.peerCount > 0 // TODO state.nodeActive ~= API is online,eg. state.peerCount > offlinePeerCount Object.defineProperty(state, 'localGwAvailable', { // TODO: make quick fetch to confirm it works? get: function () { return this.ipfsNodeType !== 'embedded' } }) Object.defineProperty(state, 'webuiRootUrl', { get: function () { // Did user opt-in for rolling release published on DNSLink? if (state.useLatestWebUI) return `${state.gwURLString}ipns/webui.ipfs.io/` return `${state.apiURLString}webui` } }) // apply optional overrides if (overrides) Object.assign(state, overrides) return state } exports.initState = initState exports.offlinePeerCount = offlinePeerCount <|start_filename|>add-on/manifest.firefox.json<|end_filename|> { "browser_action": { "browser_style": false }, "options_ui": { "browser_style": false }, "applications": { "gecko": { "id": "<EMAIL>", "strict_min_version": "68.0" } }, "permissions": [ "<all_urls>", "idle", "tabs", "notifications", "proxy", "storage", "unlimitedStorage", "contextMenus", "clipboardWrite", "webNavigation", "webRequest", "webRequestBlocking" ], "content_scripts": [ ], "protocol_handlers": [ { "protocol": "web+dweb", "name": "IPFS Companion: DWEB Protocol Handler", "uriTemplate": "https://dweb.link/ipfs/?uri=%s" }, { "protocol": "web+ipns", "name": "IPFS Companion: IPNS Protocol Handler", "uriTemplate": "https://dweb.link/ipns/?uri=%s" }, { "protocol": "web+ipfs", "name": "IPFS Companion: IPFS Protocol Handler", "uriTemplate": "https://dweb.link/ipfs/?uri=%s" }, { "protocol": "dweb", "name": "IPFS Companion: DWEB Protocol Handler", "uriTemplate": "https://dweb.link/ipfs/?uri=%s" }, { "protocol": "ipns", "name": "IPFS Companion: IPNS Protocol Handler", "uriTemplate": "https://dweb.link/ipns/?uri=%s" }, { "protocol": "ipfs", "name": "IPFS Companion: IPFS Protocol Handler", "uriTemplate": "https://dweb.link/ipfs/?uri=%s" } ] } <|start_filename|>add-on/src/popup/browser-action/store.js<|end_filename|> 'use strict' /* eslint-env browser, webextensions */ const browser = require('webextension-polyfill') const isIPFS = require('is-ipfs') const { browserActionFilesCpImportCurrentTab } = require('../../lib/ipfs-import') const { ipfsContentPath } = require('../../lib/ipfs-path') const { welcomePage, optionsPage } = require('../../lib/constants') const { contextMenuViewOnGateway, contextMenuCopyAddressAtPublicGw, contextMenuCopyPermalink, contextMenuCopyRawCid, contextMenuCopyCanonicalAddress, contextMenuCopyCidAddress } = require('../../lib/context-menus') // The store contains and mutates the state for the app module.exports = (state, emitter) => { Object.assign(state, { // Global toggles active: true, redirect: true, // UI contexts isIpfsContext: false, // Active Tab represents IPFS resource isRedirectContext: false, // Active Tab or its subresources could be redirected // IPFS details ipfsNodeType: 'external', isIpfsOnline: false, ipfsApiUrl: null, publicGatewayUrl: null, publicSubdomainGatewayUrl: null, gatewayAddress: null, swarmPeers: null, gatewayVersion: null, isApiAvailable: false, // isRedirectContext currentTab: null, currentFqdn: null, currentDnslinkFqdn: null, enabledOn: [], disabledOn: [] }) let port emitter.on('DOMContentLoaded', async () => { // initial render with status stub emitter.emit('render') // initialize connection to the background script which will trigger UI updates port = browser.runtime.connect({ name: 'browser-action-port' }) port.onMessage.addListener(async (message) => { if (message.statusUpdate) { const status = message.statusUpdate console.log('In browser action, received message from background:', message) await updateBrowserActionState(status) emitter.emit('render') } }) // fix for https://github.com/ipfs-shipyard/ipfs-companion/issues/318 setTimeout(() => { document.body.style.height = window.innerHeight + 1 + 'px' setTimeout(() => document.body.style.removeProperty('height'), 50) }, 100) }) emitter.on('viewOnGateway', async () => { port.postMessage({ event: contextMenuViewOnGateway }) window.close() }) emitter.on('copy', function (copyAction) { switch (copyAction) { case contextMenuCopyCanonicalAddress: port.postMessage({ event: contextMenuCopyCanonicalAddress }) break case contextMenuCopyCidAddress: port.postMessage({ event: contextMenuCopyCidAddress }) break case contextMenuCopyRawCid: port.postMessage({ event: contextMenuCopyRawCid }) break case contextMenuCopyAddressAtPublicGw: port.postMessage({ event: contextMenuCopyAddressAtPublicGw }) break case contextMenuCopyPermalink: port.postMessage({ event: contextMenuCopyPermalink }) break } window.close() }) emitter.on('filesCpImport', () => { port.postMessage({ event: browserActionFilesCpImportCurrentTab }) window.close() }) emitter.on('quickImport', () => { browser.tabs.create({ url: browser.runtime.getURL('dist/popup/quick-import.html') }) window.close() }) emitter.on('openWelcomePage', async () => { try { await browser.tabs.create({ url: welcomePage }) window.close() } catch (error) { console.error(`Unable Open WelcomePage (${welcomePage})`, error) } }) emitter.on('openWebUi', async (page = '/') => { const url = `${state.webuiRootUrl}#${page}` try { await browser.tabs.create({ url }) window.close() } catch (error) { console.error(`Unable Open Web UI (${url})`, error) } }) emitter.on('openReleaseNotes', async () => { const { version } = browser.runtime.getManifest() const stableChannel = version.match(/\./g).length === 2 let url try { if (stableChannel) { url = `https://github.com/ipfs-shipyard/ipfs-companion/releases/tag/v${version}` await browser.storage.local.set({ dismissedUpdate: version }) } else { // swap URL and do not dismiss url = 'https://github.com/ipfs-shipyard/ipfs-companion/issues/964' } // Note: opening tab needs to happen after storage.local.set because in Chromium 86 // it triggers a premature window.close, which aborts storage update await browser.tabs.create({ url }) window.close() } catch (error) { console.error(`Unable to open release notes (${url})`, error) } }) emitter.on('openPrefs', () => { browser.runtime.openOptionsPage() .then(() => window.close()) .catch((err) => { console.error('runtime.openOptionsPage() failed, opening options page in tab instead.', err) // brave: fallback to opening options page as a tab. browser.tabs.create({ url: browser.runtime.getURL(optionsPage) }) }) }) emitter.on('toggleGlobalRedirect', async () => { const redirectEnabled = state.redirect state.redirect = !redirectEnabled state.gatewayAddress = state.redirect ? state.gwURLString : state.pubGwURLString emitter.emit('render') try { await browser.storage.local.set({ useCustomGateway: !redirectEnabled }) } catch (error) { console.error(`Unable to update redirect state due to ${error}`) state.redirect = redirectEnabled emitter.emit('render') } }) emitter.on('toggleSiteIntegrations', async () => { const wasOptedOut = state.currentTabIntegrationsOptOut state.currentTabIntegrationsOptOut = !wasOptedOut emitter.emit('render') try { let { enabledOn, disabledOn, currentTab, currentDnslinkFqdn, currentFqdn } = state // if we are on /ipns/fqdn.tld/ then use hostname from DNSLink const fqdn = currentDnslinkFqdn || currentFqdn if (wasOptedOut) { disabledOn = disabledOn.filter(host => host !== fqdn) enabledOn.push(fqdn) } else { enabledOn = enabledOn.filter(host => host !== fqdn) disabledOn.push(fqdn) } // console.dir('toggleSiteIntegrations', state) await browser.storage.local.set({ disabledOn, enabledOn }) const path = ipfsContentPath(currentTab.url, { keepURIParams: true }) // Reload the current tab to apply updated redirect preference if (!currentDnslinkFqdn || !isIPFS.ipnsPath(path)) { // No DNSLink, reload URL as-is await browser.tabs.reload(currentTab.id) } else { // DNSLinked websites require URL change // from http?://gateway.tld/ipns/{fqdn}/some/path OR // from http?://{fqdn}.ipns.gateway.tld/some/path // to http://{fqdn}/some/path // (defaulting to http: https websites will have HSTS or a redirect) const originalUrl = path.replace(/^.*\/ipns\//, 'http://') await browser.tabs.update(currentTab.id, { // FF only: loadReplace: true, url: originalUrl }) } } catch (error) { console.error(`Unable to update integrations state due to ${error}`) emitter.emit('render') } }) emitter.on('toggleActive', async () => { const prev = state.active state.active = !prev if (!state.active) { state.gatewayAddress = state.pubGwURLString state.ipfsApiUrl = null state.gatewayVersion = null state.swarmPeers = null state.isIpfsOnline = false } try { await browser.storage.local.set({ active: state.active }) } catch (error) { console.error(`Unable to update global Active flag due to ${error}`) state.active = prev } emitter.emit('render') }) async function updateBrowserActionState (status) { if (status) { // Copy all attributes Object.assign(state, status) if (state.active && status.redirect && (status.ipfsNodeType !== 'embedded')) { state.gatewayAddress = status.gwURLString } else { state.gatewayAddress = status.pubGwURLString } // Import requires access to the background page (https://github.com/ipfs-shipyard/ipfs-companion/issues/477) state.isApiAvailable = state.active && !!(await getBackgroundPage()) && !browser.extension.inIncognitoContext // https://github.com/ipfs-shipyard/ipfs-companion/issues/243 state.swarmPeers = !state.active || status.peerCount === -1 ? null : status.peerCount state.isIpfsOnline = state.active && status.peerCount > -1 state.gatewayVersion = state.active && status.gatewayVersion ? status.gatewayVersion : null state.ipfsApiUrl = state.active ? status.apiURLString : null } else { state.ipfsNodeType = 'external' state.swarmPeers = null state.isIpfsOnline = false state.gatewayVersion = null state.isIpfsContext = false state.isRedirectContext = false } } } function getBackgroundPage () { return browser.runtime.getBackgroundPage() } <|start_filename|>add-on/src/pages/proxy-acl/index.js<|end_filename|> 'use strict' require('./proxy-acl.css') const browser = require('webextension-polyfill') const choo = require('choo') const AccessControl = require('../../lib/ipfs-proxy/access-control') const createProxyAclStore = require('./store') const createProxyAclPage = require('./page') const app = choo() app.use(createProxyAclStore(new AccessControl(browser.storage), browser.i18n)) app.route('*', createProxyAclPage(browser.i18n)) app.mount('#root') <|start_filename|>add-on/src/popup/browser-action/power-icon.js<|end_filename|> 'use strict' /* eslint-env browser, webextensions */ const html = require('choo/html') const icon = require('./icon') function powerIcon ({ active, title, action, size = '1.8rem' }) { const svg = html` <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 86 86" class="fill-current-color mr1" style="width:${size}; height:${size}"> <path d="M50 20.11A29.89 29.89 0 1 0 79.89 50 29.89 29.89 0 0 0 50 20.11zm-3.22 17a3.22 3.22 0 0 1 6.44 0v6.43a3.22 3.22 0 0 1-6.44 0zM50 66.08a16.14 16.14 0 0 1-11.41-27.49 3.28 3.28 0 0 1 1.76-.65 2.48 2.48 0 0 1 2.42 2.41 2.58 2.58 0 0 1-.77 1.77A10.81 10.81 0 0 0 38.59 50a11.25 11.25 0 0 0 22.5 0 10.93 10.93 0 0 0-3.21-7.88 3.37 3.37 0 0 1-.65-1.77 2.48 2.48 0 0 1 2.42-2.41 2.16 2.16 0 0 1 1.76.65A16.14 16.14 0 0 1 50 66.08z"/> </svg> ` return icon({ svg, title, active, action }) } module.exports = powerIcon <|start_filename|>add-on/src/background/background.js<|end_filename|> 'use strict' /* eslint-env browser, webextensions */ const browser = require('webextension-polyfill') const { onInstalled } = require('../lib/on-installed') const { getUninstallURL } = require('../lib/on-uninstalled') const { optionDefaults } = require('../lib/options') // register lifecycle hooks early, otherwise we miss first install event browser.runtime.onInstalled.addListener(onInstalled) browser.runtime.setUninstallURL(getUninstallURL(browser)) // init add-on after all libs are loaded document.addEventListener('DOMContentLoaded', async () => { // setting debug level early localStorage.debug = (await browser.storage.local.get({ logNamespaces: optionDefaults.logNamespaces })).logNamespaces // init inlined to read updated localStorage.debug const createIpfsCompanion = require('../lib/ipfs-companion') window.ipfsCompanion = await createIpfsCompanion() }) <|start_filename|>add-on/src/options/forms/global-toggle-form.js<|end_filename|> 'use strict' /* eslint-env browser, webextensions */ const browser = require('webextension-polyfill') const html = require('choo/html') const switchToggle = require('../../pages/components/switch-toggle') function globalToggleForm ({ active, onOptionChange }) { const toggle = onOptionChange('active') return html` <form class="db b mb3 bg-aqua-muted charcoal"> <label for="active" class="dib pa3 flex items-center pointer ${!active ? 'charcoal bg-gray-muted br2' : ''}"> ${switchToggle({ id: 'active', checked: active, onchange: toggle, style: 'mr3' })} ${browser.i18n.getMessage('panel_headerActiveToggleTitle')} </label> </form> ` } module.exports = globalToggleForm <|start_filename|>add-on/src/options/forms/reset-form.js<|end_filename|> 'use strict' /* eslint-env browser, webextensions */ const browser = require('webextension-polyfill') const html = require('choo/html') function resetForm ({ onOptionsReset }) { return html` <form> <fieldset class="mb3 pa1 pa4-ns pa3 bg-snow-muted charcoal"> <h2 class="ttu tracked f6 fw4 teal mt0-ns mb3-ns mb1 mt2 ">${browser.i18n.getMessage('option_header_reset')}</h2> <div class="flex-row-ns pb0-ns"> <label for="resetAllOptions"> <dl> <dt>${browser.i18n.getMessage('option_resetAllOptions_title')}</dt> <dd>${browser.i18n.getMessage('option_resetAllOptions_description')}</dd> </dl> </label> <div class="self-center-ns"><button id="resetAllOptions" class="Button transition-all sans-serif v-mid fw5 nowrap lh-copy bn br1 pa2 pointer focus-outline white bg-red white" onclick=${onOptionsReset}>${browser.i18n.getMessage('option_resetAllOptions_title')}</button></div> </div> </fieldset> </form> ` } module.exports = resetForm <|start_filename|>add-on/src/pages/proxy-access-dialog/index.js<|end_filename|> 'use strict' require('./proxy-access-dialog.css') const browser = require('webextension-polyfill') const choo = require('choo') const createProxyAccessDialogStore = require('./store') const createProxyAccessDialogPage = require('./page') const app = choo() app.use(createProxyAccessDialogStore(browser.i18n, browser.runtime)) app.route('*', createProxyAccessDialogPage(browser.i18n)) app.mount('#root') // Fix for Fx57 bug where bundled page loaded using // browser.windows.create won't show contents unless resized. // See https://bugzilla.mozilla.org/show_bug.cgi?id=1402110 browser.windows.getCurrent() .then(win => browser.windows.update(win.id, { width: win.width + 1 })) <|start_filename|>add-on/src/popup/browser-action/tools-button.js<|end_filename|> 'use strict' /* eslint-env browser, webextensions */ const html = require('choo/html') function toolsButton ({ iconD, iconSize, text, title, disabled, style, onClick }) { let buttonStyle = 'header-icon fade-in w-50 ba bw1 snow b--snow bg-transparent f7 ph1 pv0 br4 ma1 flex justify-center items-center truncate' if (disabled) { buttonStyle += ' o-60' } else { buttonStyle += ' pointer' } if (style) { buttonStyle += ` ${style}` } if (disabled) { title = '' } return html` <div class="${buttonStyle}" onclick=${disabled ? null : onClick} title="${title || ''}" ${disabled ? 'disabled' : ''}> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" class="mr1" width="${iconSize}" height="${iconSize}"><path fill="currentColor" d="${iconD}"/></svg> <div class="flex flex-row items-center justify-between"><div class="truncate">${text}</div></div> </div> ` } module.exports = toolsButton
Carson12345/ipfs-companion
<|start_filename|>share.js<|end_filename|> "use strict"; module.exports = function() { /* https://github.com/EliF-Lee/shareKakao */ function t() { this.h = { ct: "application/x-www-form-urlencoded", cj: "application/json", ua: "KakaoTalk Share Extension/9.1.7" }, this.pa = null, this.mi = null, this.k = [ ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"], [10, 2, 3, -4, 20, 73, 47, -38, 27, -22, 11, -20, -22, 37, 36, 54], [67, 109, -115, -110, -23, 119, 33, 86, -99, -28, -102, 109, -73, 13, 43, -96, 109, -76, 91, -83, 73, -14, 107, -88, 6, 11, 74, 109, 84, -68, -80, 15], "dkljleskljfeisflssljeif " ], this.p = { pu: "hw.perferences.xml", at: "authorization.preferences.xml" }, this.d = '<string name="d_id">', this.e = '<string name="encrypted_auth_token">', this.kv = "8.9.7"; } return t.prototype.setPackage = function(t, v) { this.pa = "data/data/" + t + "/shared_prefs/KakaoTalk."; this.kv = v; this.d = Number(this.kv.slice(0, 1)) <= 8 ? '<string name="deviceUUID">' : '<string name="d_id">'; }, t.prototype.setUserId = function(i) { this.mi = i; }, t.prototype.auth = function() { return this.gOT() + "-" + this.gDI(); }, t.prototype.r = function(t) { return FileStream.read(t); }, t.prototype.gDI = function() { if(Number(this.kv.slice(0, 1)) <= 8) { let t = java.security.MessageDigest.getInstance("SHA"); t.reset(), t.update(this.j(this.k[3] + this.r(this.pa + this.p.pu).split(this.d)[1].split("</string>")[0]).getBytes()); let e = t.digest(), a = new java.lang.StringBuffer, n = this.k[0]; for (let t = 0; t < e.length; t++) { let s = e[t]; a.append(n[(240 & s) >> 4]), a.append(n[15 & s]); } return a.toString(); } let t = this.r(this.pa + this.p.pu).split(this.d)[1].split("</string>")[0]; return t; }, t.prototype.gOT = function() { let t = this.r(this.pa + this.p.at).split(this.e)[1].split("</string>")[0], e = new javax.crypto.Cipher.getInstance("AES/CBC/PKCS5PADDING"), a = new javax.crypto.spec.SecretKeySpec(this.k[2], "AES"), n = new javax.crypto.spec.IvParameterSpec(this.k[1]); e.init(2, a, n); let s = this.j(e.doFinal(android.util.Base64.decode(t, 0)), "UTF-8"); return JSON.parse(s).access_token; }, t.prototype.rN = function() { return Math.random()*10000|0; }, t.prototype.j = function(t) { return new java.lang.String(t); }, t.prototype.shareSharp = function(t, e) { let content = [], bul = []; if(e.type.toLowerCase() === "image") { for(let j in e.object.content) content.push({I: e.object.content[j].image_url, W: e.object.content[j].width, H: e.object.content[j].height, L: e.object.content[j].web_url}); } else for(let i in e.object.content) content.push({T: e.object.content[i].title, D: e.object.content[i].description, L: e.object.content[i].web_url}); for(let l in e.object.button) bul.push({T: e.object.button[l].title, L: e.object.button[l].web_url}); const response = org.jsoup.Jsoup.connect("https://talk-pilsner.kakao.com/search-express") .header("Content-Type", this.h.cj).header("authorization", this.auth()) .requestBody(JSON.stringify({ userId: this.mi, chatId: t, msgId: this.rN(), dc: "SH1", query: e.query, message: { isExpress: true, V: e.type, Q: e.query, L: e.web_url, R: content, F: { BU: bul } } })).ignoreContentType(true).ignoreHttpErrors(true).method(org.jsoup.Connection.Method.POST).execute(); return (response.statusCode() === 200) ? response.body() : "ERROR"; }, t.prototype.share = function(t, e) { const response = org.jsoup.Jsoup.connect("https://talk-shareex.kakao.com/authWrite") .header("Content-Type", this.h.ct).userAgent(this.h.ua) .requestBody("chatLog=" + JSON.stringify({ type: e.type, message: e.message, extra: JSON.stringify(e.attachment) }) + "&duuid=" + this.gDI() + "&oauthToken=" + this.gOT() + "&target=" + JSON.stringify({ chatId: t })).ignoreContentType(true).ignoreHttpErrors(true) .method(org.jsoup.Connection.Method.POST).execute(); return (response.statusCode() === 200) ? response.body() : "ERROR"; }, t; }();
archethic/shareKakao
<|start_filename|>Assets/TextureLoader/Scripts/TextureStreamingLoader.cs<|end_filename|> using UnityEngine; using System.Collections; namespace TextureLoader { [AddComponentMenu("Common/TextureLoader (Streaming Assets)")] public class TextureStreamingLoader : TextureLoader { public override void Load(string url) { string path; switch (Application.platform) { case RuntimePlatform.IPhonePlayer: path = "file://" + Application.dataPath + "/Raw/"; break; case RuntimePlatform.Android: path = "jar:file://" + Application.dataPath + "!/assets/"; break; case RuntimePlatform.OSXEditor: case RuntimePlatform.WindowsEditor: case RuntimePlatform.OSXPlayer: case RuntimePlatform.WindowsPlayer: path = "file://" + Application.dataPath + "/StreamingAssets/"; break; default: path = Application.dataPath + "/StreamingAssets/"; Debug.LogWarning("UNKNOWN Platform : " + Application.platform.ToString()); break; } base.Load(path + url); } } } <|start_filename|>Assets/TextureLoader/Scripts/Editor/TextureLoaderEditor.cs<|end_filename|> using UnityEngine; using UnityEditor; namespace TextureLoader { [CustomEditor(typeof(TextureLoader))] [CanEditMultipleObjects] public class TextureLoaderEditor : Editor { TextureLoader _target; void OnEnable() { _target = target as TextureLoader; } new void OnInspectorGUI() { DrawDefaultInspector(); } protected virtual void OnSceneGUI() { Vector3 pos = _target.transform.position; Handles.Label(pos, "[TEXTURE]" + _target.URL); } [MenuItem("Tools/Create/TextureLoader (from url)")] public static GameObject Create() { return Create<TextureLoader>(); } protected static GameObject Create<T>() where T : Component { GameObject go = CreateTool.CreatePlane(); go.AddComponent<T>(); go.name = typeof(T).ToString(); return go; } } } <|start_filename|>Assets/TextureLoader/Scripts/Editor/CreateTool.cs<|end_filename|> using System.Collections; using UnityEngine; using UnityEngine.Rendering; using UnityEditor; /// <summary> /// Editor Utility tool. /// author <NAME> /// </summary> public class CreateTool : ScriptableObject { static GameObject _CreateChild(string name) { GameObject go = new GameObject(name); Transform t = go.transform; t.parent = Selection.activeTransform; t.localScale = Vector3.one; t.localPosition = Vector3.zero; t.localRotation = Quaternion.identity; Transform parent = Selection.activeTransform; if (parent != null) { go.layer = parent.gameObject.layer; } Selection.activeGameObject = go; return go; } /// <summary> /// Create selected object's child. /// SHORTCUT KEY [cmd shift N] /// </summary> /// <returns> /// created gameobject /// </returns> [MenuItem("Tools/Create/Blank Child %#n")] public static GameObject CreateChild() { return _CreateChild("GameObject"); } /// <summary> /// Creates 4 poly plane. /// </summary> /// <returns> /// The plane gameobject /// </returns> [MenuItem("Tools/Create/Plane")] public static GameObject CreatePlane() { GameObject go = _CreateChild("Plane"); MeshRenderer renderer = go.AddComponent<MeshRenderer>(); renderer.shadowCastingMode = ShadowCastingMode.Off; renderer.receiveShadows = false; Mesh mesh = new Mesh(); go.AddComponent<MeshFilter>().sharedMesh = mesh; // make 4 vertices plane Vector3 offset = new Vector3(-0.5f, -0.5f, 0); // centering offset Vector3[] vertices = new Vector3[4] { new Vector3(0, 0, 0), new Vector3(0, 1, 0), new Vector3(1, 1, 0), new Vector3(1, 0, 0) }; /* 1-2 |/| 0-3 */ for (int i = 0; i < vertices.Length; i++) { vertices[i] += offset; } mesh.vertices = vertices; mesh.uv = new Vector2[4] { new Vector2(0, 0), new Vector2(0, 1), new Vector2(1, 1), new Vector2(1, 0) }; mesh.triangles = new int[6] { 0, 1, 2, 0, 2, 3 }; return go; } /// <summary> /// Delete all player preferences. /// </summary> [MenuItem("Tools/Delete/Delete PlayerPref")] public static void DeletePlayerPref() { PlayerPrefs.DeleteAll(); Debug.LogWarning("deleted"); } } <|start_filename|>Assets/TextureLoader/Scripts/TextureLoader.cs<|end_filename|> using System; using System.Collections; using UnityEngine; namespace TextureLoader { /// <summary> /// Common Texture loader /// </summary> [AddComponentMenu("Common/TextureLoader")] [RequireComponent(typeof(Renderer))] public class TextureLoader : MonoBehaviour { [SerializeField] string url; [SerializeField] bool autoStart = true; [SerializeField] bool aspectFit = true; [SerializeField] bool useCustomMaterial = false; Material _material; Renderer _renderer; public event Action<TextureLoader> OnFinish; #region life cycle void Awake() { this.isLoaed = false; } void Start() { _renderer = GetComponent<Renderer>(); if (useCustomMaterial) { _material = _renderer.material; } else { // mat = new Material(_DEFAULT_SHADER); _material = new Material(Shader.Find("Mobile/Particles/Alpha Blended")); _renderer.material = _material; } if (autoStart) { Load(url); } _renderer.enabled = false; } void OnDrawGizmos() { } #endregion #region public public virtual void Load(string url) { StartCoroutine(_load(url)); } #endregion #region privates IEnumerator _load(string url) { using (WWW www = new WWW(url)) { yield return www; if (string.IsNullOrEmpty(www.error)) { SetTexture(www.texture); this.hasError = false; this.isLoaed = true; } else { this.error = www.error; this.hasError = true; this.isLoaed = true; Debug.LogWarning("error:" + www.error); } } yield return null; if (OnFinish != null) { OnFinish(this); } } void SetTexture(Texture2D texture) { _material.mainTexture = texture; if (aspectFit) { Vector3 size = transform.localScale; float aspect = (float)texture.width / (float)texture.height; if (aspect < 1) { size.x *= aspect; } else { size.y /= aspect; } transform.localScale = size; } _renderer.enabled = true; } #endregion #region getter setter public string URL { get { return url; } } public bool isLoaed { get; protected set; } public string error { get; protected set; } public bool hasError { get; protected set; } #endregion } } <|start_filename|>Assets/TextureLoader/Scripts/Editor/TextureStreamingLoaderEditor.cs<|end_filename|> using UnityEngine; using UnityEditor; namespace TextureLoader { [CustomEditor(typeof(TextureStreamingLoader))] [CanEditMultipleObjects] public class TextureStreamingLoaderEditor : TextureLoaderEditor { // simple overrides [MenuItem("Tools/Create/TextureLoader (from SteamingAssets)")] public static new GameObject Create() { return Create<TextureStreamingLoader>(); } } }
asus4/UnityTextureLoader
<|start_filename|>Setup.lhs<|end_filename|> #!/usr/local/bin/runhaskell \begin{code} import Distribution.Simple main = defaultMainWithHooks autoconfUserHooks \end{code} <|start_filename|>System/Console/Terminfo/Effects.hs<|end_filename|> {-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ >= 703 {-# LANGUAGE Safe #-} #endif -- | -- Maintainer : <EMAIL> -- Stability : experimental -- Portability : portable (FFI) module System.Console.Terminfo.Effects( -- * Bell alerts bell,visualBell, -- * Text attributes Attributes(..), defaultAttributes, withAttributes, setAttributes, allAttributesOff, -- ** Mode wrappers withStandout, withUnderline, withBold, -- ** Low-level capabilities enterStandoutMode, exitStandoutMode, enterUnderlineMode, exitUnderlineMode, reverseOn, blinkOn, boldOn, dimOn, invisibleOn, protectedOn ) where import System.Console.Terminfo.Base import Control.Monad wrapWith :: TermStr s => Capability s -> Capability s -> Capability (s -> s) wrapWith start end = do s <- start e <- end return (\t -> s <#> t <#> e) -- | Turns on standout mode before outputting the given -- text, and then turns it off. withStandout :: TermStr s => Capability (s -> s) withStandout = wrapWith enterStandoutMode exitStandoutMode -- | Turns on underline mode before outputting the given -- text, and then turns it off. withUnderline :: TermStr s => Capability (s -> s) withUnderline = wrapWith enterUnderlineMode exitUnderlineMode -- | Turns on bold mode before outputting the given text, and then turns -- all attributes off. withBold :: TermStr s => Capability (s -> s) withBold = wrapWith boldOn allAttributesOff enterStandoutMode :: TermStr s => Capability s enterStandoutMode = tiGetOutput1 "smso" exitStandoutMode :: TermStr s => Capability s exitStandoutMode = tiGetOutput1 "rmso" enterUnderlineMode :: TermStr s => Capability s enterUnderlineMode = tiGetOutput1 "smul" exitUnderlineMode :: TermStr s => Capability s exitUnderlineMode = tiGetOutput1 "rmul" reverseOn :: TermStr s => Capability s reverseOn = tiGetOutput1 "rev" blinkOn:: TermStr s => Capability s blinkOn = tiGetOutput1 "blink" boldOn :: TermStr s => Capability s boldOn = tiGetOutput1 "bold" dimOn :: TermStr s => Capability s dimOn = tiGetOutput1 "dim" invisibleOn :: TermStr s => Capability s invisibleOn = tiGetOutput1 "invis" protectedOn :: TermStr s => Capability s protectedOn = tiGetOutput1 "prot" -- | Turns off all text attributes. This capability will always succeed, but it has -- no effect in terminals which do not support text attributes. allAttributesOff :: TermStr s => Capability s allAttributesOff = tiGetOutput1 "sgr0" `mplus` return mempty data Attributes = Attributes { standoutAttr, underlineAttr, reverseAttr, blinkAttr, dimAttr, boldAttr, invisibleAttr, protectedAttr :: Bool -- NB: I'm not including the "alternate character set." } -- | Sets the attributes on or off before outputting the given text, -- and then turns them all off. This capability will always succeed; properties -- which cannot be set in the current terminal will be ignored. withAttributes :: TermStr s => Capability (Attributes -> s -> s) withAttributes = do set <- setAttributes off <- allAttributesOff return $ \attrs to -> set attrs <#> to <#> off -- | Sets the attributes on or off. This capability will always succeed; -- properties which cannot be set in the current terminal will be ignored. setAttributes :: TermStr s => Capability (Attributes -> s) setAttributes = usingSGR0 `mplus` manualSets where usingSGR0 = do sgr <- tiGetOutput1 "sgr" return $ \a -> let mkAttr f = if f a then 1 else 0 :: Int in sgr (mkAttr standoutAttr) (mkAttr underlineAttr) (mkAttr reverseAttr) (mkAttr blinkAttr) (mkAttr dimAttr) (mkAttr boldAttr) (mkAttr invisibleAttr) (mkAttr protectedAttr) (0::Int) -- for alt. character sets attrCap :: TermStr s => (Attributes -> Bool) -> Capability s -> Capability (Attributes -> s) attrCap f cap = do {to <- cap; return $ \a -> if f a then to else mempty} `mplus` return (const mempty) manualSets = do cs <- sequence [attrCap standoutAttr enterStandoutMode , attrCap underlineAttr enterUnderlineMode , attrCap reverseAttr reverseOn , attrCap blinkAttr blinkOn , attrCap boldAttr boldOn , attrCap dimAttr dimOn , attrCap invisibleAttr invisibleOn , attrCap protectedAttr protectedOn ] return $ \a -> mconcat $ map ($ a) cs -- | These attributes have all properties turned off. defaultAttributes :: Attributes defaultAttributes = Attributes False False False False False False False False -- | Sound the audible bell. bell :: TermStr s => Capability s bell = tiGetOutput1 "bel" -- | Present a visual alert using the @flash@ capability. visualBell :: Capability TermOutput visualBell = tiGetOutput1 "flash" <|start_filename|>System/Console/Terminfo/Cursor.hs<|end_filename|> {-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ >= 703 {-# LANGUAGE Safe #-} #endif -- | -- Maintainer : <EMAIL> -- Stability : experimental -- Portability : portable (FFI) -- -- This module provides capabilities for moving the cursor on the terminal. module System.Console.Terminfo.Cursor( -- * Terminal dimensions -- | Get the default size of the terminal. For -- resizeable terminals (e.g., @xterm@), these may not -- correspond to the actual dimensions. termLines, termColumns, -- * Cursor flags autoRightMargin, autoLeftMargin, wraparoundGlitch, -- * Scrolling carriageReturn, newline, scrollForward, scrollReverse, -- * Relative cursor movements -- | The following functions for cursor movement will -- combine the more primitive capabilities. For example, -- 'moveDown' may use either 'cursorDown' or -- 'cursorDown1' depending on the parameter and which of -- @cud@ and @cud1@ are defined. moveDown, moveLeft, moveRight, moveUp, -- ** Primitive movement capabilities -- | These capabilities correspond directly to @cub@, @cud@, -- @cub1@, @cud1@, etc. cursorDown1, cursorLeft1, cursorRight1, cursorUp1, cursorDown, cursorLeft, cursorRight, cursorUp, cursorHome, cursorToLL, -- * Absolute cursor movements cursorAddress, Point(..), rowAddress, columnAddress ) where import System.Console.Terminfo.Base import Control.Monad termLines :: Capability Int termColumns :: Capability Int termLines = tiGetNum "lines" termColumns = tiGetNum "cols" -- | This flag specifies that the cursor wraps automatically from the last -- column of one line to the first column of the next. autoRightMargin :: Capability Bool autoRightMargin = tiGetFlag "am" -- | This flag specifies that a backspace at column 0 wraps the cursor to -- the last column of the previous line. autoLeftMargin :: Capability Bool autoLeftMargin = tiGetFlag "bw" -- | This flag specifies that the terminal does not perform -- 'autoRightMargin'-style wrapping when the character which would cause the -- wraparound is a control character. -- This is also known as the \"newline glitch\" or \"magic wrap\". -- -- For example, in an 80-column terminal with this behavior, the following -- will print single-spaced instead of double-spaced: -- -- > replicateM_ 5 $ putStr $ replicate 80 'x' ++ "\n" -- wraparoundGlitch :: Capability Bool wraparoundGlitch = tiGetFlag "xenl" {-- On many terminals, the @cud1@ ('cursorDown1') capability is the line feed character '\n'. However, @stty@ settings may cause that character to have other effects than intended; e.g. ONLCR turns LF into CRLF, and as a result @cud1@ will always move the cursor to the first column of the next line. Looking at the source code of curses (lib_mvcur.c) and other similar programs, they use @cud@ instead of @cud1@ if it's '\n' and ONLCR is turned on. Since there's no easy way to check for ONLCR at this point, I've just made moveDown only use cud1 if it's not '\n'. Suggestions are welcome. --} cursorDown1Fixed :: TermStr s => Capability s cursorDown1Fixed = do str <- tiGetOutput1 "cud1" guard (str /= "\n") tiGetOutput1 "cud1" cursorDown1 :: TermStr s => Capability s cursorDown1 = tiGetOutput1 "cud1" cursorLeft1 :: TermStr s => Capability s cursorLeft1 = tiGetOutput1 "cub1" cursorRight1 :: TermStr s => Capability s cursorRight1 = tiGetOutput1 "cuf1" cursorUp1 :: TermStr s => Capability s cursorUp1 = tiGetOutput1 "cuu1" cursorDown :: TermStr s => Capability (Int -> s) cursorDown = tiGetOutput1 "cud" cursorLeft :: TermStr s => Capability (Int -> s) cursorLeft = tiGetOutput1 "cub" cursorRight :: TermStr s => Capability (Int -> s) cursorRight = tiGetOutput1 "cuf" cursorUp :: TermStr s => Capability (Int -> s) cursorUp = tiGetOutput1 "cuu" cursorHome :: TermStr s => Capability s cursorHome = tiGetOutput1 "home" cursorToLL :: TermStr s => Capability s cursorToLL = tiGetOutput1 "ll" -- Movements are built out of parametrized and unparam'd movement -- capabilities. -- todo: more complicated logic like ncurses does. move :: TermStr s => Capability s -> Capability (Int -> s) -> Capability (Int -> s) move single param = let tryBoth = do s <- single p <- param return $ \n -> case n of 0 -> mempty 1 -> s _ -> p n manySingle = do s <- single return $ \n -> mconcat $ replicate n s in tryBoth `mplus` param `mplus` manySingle moveLeft :: TermStr s => Capability (Int -> s) moveLeft = move cursorLeft1 cursorLeft moveRight :: TermStr s => Capability (Int -> s) moveRight = move cursorRight1 cursorRight moveUp :: TermStr s => Capability (Int -> s) moveUp = move cursorUp1 cursorUp moveDown :: TermStr s => Capability (Int -> s) moveDown = move cursorDown1Fixed cursorDown -- | The @cr@ capability, which moves the cursor to the first column of the -- current line. carriageReturn :: TermStr s => Capability s carriageReturn = tiGetOutput1 "cr" -- | The @nel@ capability, which moves the cursor to the first column of -- the next line. It behaves like a carriage return followed by a line feed. -- -- If @nel@ is not defined, this may be built out of other capabilities. newline :: TermStr s => Capability s newline = tiGetOutput1 "nel" `mplus` (liftM2 mappend carriageReturn (scrollForward `mplus` tiGetOutput1 "cud1")) -- Note it's OK to use cud1 here, despite the stty problem referenced -- above, because carriageReturn already puts us on the first column. scrollForward :: TermStr s => Capability s scrollForward = tiGetOutput1 "ind" scrollReverse :: TermStr s => Capability s scrollReverse = tiGetOutput1 "ri" data Point = Point {row, col :: Int} cursorAddress :: TermStr s => Capability (Point -> s) cursorAddress = fmap (\g p -> g (row p) (col p)) $ tiGetOutput1 "cup" columnAddress :: TermStr s => Capability (Int -> s) columnAddress = tiGetOutput1 "hpa" rowAddress :: TermStr s => Capability (Int -> s) rowAddress = tiGetOutput1 "vpa" <|start_filename|>System/Console/Terminfo/Color.hs<|end_filename|> {-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ >= 703 {-# LANGUAGE Safe #-} #endif -- | -- Maintainer : <EMAIL> -- Stability : experimental -- Portability : portable (FFI) module System.Console.Terminfo.Color( termColors, Color(..), -- ColorPair, withForegroundColor, withBackgroundColor, -- withColorPair, setForegroundColor, setBackgroundColor, -- setColorPair, restoreDefaultColors ) where import System.Console.Terminfo.Base import Control.Monad (mplus) -- TODOs: -- examples -- try with xterm-256-colors (?) -- Color pairs, and HP terminals. -- TODO: this "white" looks more like a grey. (What does ncurses do?) -- NB: for all the terminals in ncurses' terminfo.src, colors>=8 when it's -- set. So we don't need to perform that check. -- | The maximum number of of colors on the screen. termColors :: Capability Int termColors = tiGetNum "colors" data Color = Black | Red | Green | Yellow | Blue | Magenta | Cyan | White | ColorNumber Int deriving (Show,Eq,Ord) colorIntA, colorInt :: Color -> Int colorIntA c = case c of Black -> 0 Red -> 1 Green -> 2 Yellow -> 3 Blue -> 4 Magenta -> 5 Cyan -> 6 White -> 7 ColorNumber n -> n colorInt c = case c of Black -> 0 Blue -> 1 Green -> 2 Cyan -> 3 Red -> 4 Magenta -> 5 Yellow -> 6 White -> 7 ColorNumber n -> n -- NB these aren't available on HP systems. -- also do we want to handle case when they're not available? -- | This capability temporarily sets the -- terminal's foreground color while outputting the given text, and -- then restores the terminal to its default foreground and background -- colors. withForegroundColor :: TermStr s => Capability (Color -> s -> s) withForegroundColor = withColorCmd setForegroundColor -- | This capability temporarily sets the -- terminal's background color while outputting the given text, and -- then restores the terminal to its default foreground and background -- colors. withBackgroundColor :: TermStr s => Capability (Color -> s -> s) withBackgroundColor = withColorCmd setBackgroundColor withColorCmd :: TermStr s => Capability (a -> s) -> Capability (a -> s -> s) withColorCmd getSet = do set <- getSet restore <- restoreDefaultColors return $ \c t -> set c <#> t <#> restore -- | Sets the foreground color of all further text output, using -- either the @setaf@ or @setf@ capability. setForegroundColor :: TermStr s => Capability (Color -> s) setForegroundColor = setaf `mplus` setf where setaf = fmap (. colorIntA) $ tiGetOutput1 "setaf" setf = fmap (. colorInt) $ tiGetOutput1 "setf" -- | Sets the background color of all further text output, using -- either the @setab@ or @setb@ capability. setBackgroundColor :: TermStr s => Capability (Color -> s) setBackgroundColor = setab `mplus` setb where setab = fmap (. colorIntA) $ tiGetOutput1 "setab" setb = fmap (. colorInt) $ tiGetOutput1 "setb" {- withColorPair :: TermStr s => Capability (ColorPair -> s -> s) withColorPair = withColorCmd setColorPair setColorPair :: TermStr s => Capability (ColorPair -> s) setColorPair = do setf <- setForegroundColor setb <- setBackgroundColor return (\(f,b) -> setf f <#> setb b) type ColorPair = (Color,Color) -} -- | Restores foreground/background colors to their original -- settings. restoreDefaultColors :: TermStr s => Capability s restoreDefaultColors = tiGetOutput1 "op" <|start_filename|>System/Console/Terminfo/Edit.hs<|end_filename|> {-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ >= 703 {-# LANGUAGE Safe #-} #endif -- | -- Maintainer : <EMAIL> -- Stability : experimental -- Portability : portable (FFI) module System.Console.Terminfo.Edit where import System.Console.Terminfo.Base -- | Clear the screen, and move the cursor to the upper left. clearScreen :: Capability (LinesAffected -> TermOutput) clearScreen = fmap ($ []) $ tiGetOutput "clear" -- | Clear from beginning of line to cursor. clearBOL :: TermStr s => Capability s clearBOL = tiGetOutput1 "el1" -- | Clear from cursor to end of line. clearEOL :: TermStr s => Capability s clearEOL = tiGetOutput1 "el" -- | Clear display after cursor. clearEOS :: Capability (LinesAffected -> TermOutput) clearEOS = fmap ($ []) $ tiGetOutput "ed" <|start_filename|>System/Console/Terminfo.hs<|end_filename|> {-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ >= 703 {-# LANGUAGE Safe #-} #endif {- | Maintainer : <EMAIL> Stability : experimental Portability : portable (FFI) -} module System.Console.Terminfo( module System.Console.Terminfo.Base, module System.Console.Terminfo.Keys, module System.Console.Terminfo.Cursor, module System.Console.Terminfo.Effects, module System.Console.Terminfo.Edit, module System.Console.Terminfo.Color ) where import System.Console.Terminfo.Base import System.Console.Terminfo.Keys import System.Console.Terminfo.Cursor import System.Console.Terminfo.Edit import System.Console.Terminfo.Effects import System.Console.Terminfo.Color
hvr/terminfo
<|start_filename|>.template-lintrc.js<|end_filename|> module.exports = { plugins: ["ember-template-lint-plugin-discourse"], extends: "discourse:recommended" };
Qursch/discourse-bcc
<|start_filename|>Web/CreatingPackages.cshtml<|end_filename|> @{ Layout = "~/_ContentLayout.cshtml"; } @section headerBody { <h1>Creating Packages</h1> <p class="lead">Boxstarter includes some commands that can automate a lot of the "grunt" work involved with creating and packing NuGet packages.</p> } <h3>Do you really need to create a package?</h3> <p>Maybe not. For simple "One-Off" packages or packages that do not need a home in a public NuGet feed and do not need any additional scripts or resources outside of the ChocolateyInstall.ps1 script, Boxstarter provides a means of creating "on the fly" packages from a single script file or URL. You may pass a file path or URL to the -PackageName parameter of <code>Install-BoxstarterPackage</code> and Boxstarter will generate a temporary package to install the script. If using a URL, the URL content must be plain text and not contain any markup.</p> <pre> Install-BoxstarterPackage -PackageName https://gist.github.com/mwrock/8066325/raw/e0c830528429cd68a8c71dbff6f48298576d8d20/gistfile1.txt </pre> <h3>New-PackageFromScript</h3> <p>The simplest way to create a NuGet package is using the <code>New-PackageFromScript</code> command.</p> <pre> New-PackageFromScript MyScript.ps1 MyPackage </pre> <p>This command takes either a file or http URL (like a <a href="https://gist.github.com">GitHub Gist</a>) that represents the install script. The <code>New-PackageFromScript</code> command will create a Chocolatey NuGet package with the contents of the script moved to the ChocolateyInstall.ps1 file. While this is an incredibly simple way to create a package for your Boxstarter installations, it does not provide much flexibility in customizing the nuspec manifest or adding other files to your install package.</p> <h3>New-BoxstarterPackage</h3> <p>The New-BoxstarterPackage command creates a skeletal package with a minimal *.nuspec file and ChocolateyInstall.ps1 file.</p> <pre> New-BoxstarterPackage -Name MyPackage -Description "I hope you enjoy MyPackage" </pre> <p>This creates a MyPackage.nuspec file that looks like:</p> <pre> &lt;?xml version="1.0" ?&gt; &lt;package&gt; &lt;metadata&gt; &lt;id&gt;MyPackage&lt;/id&gt; &lt;version&gt;1.0.0&lt;/version&gt; &lt;authors&gt;Matt&lt;/authors&gt; &lt;owners&gt;Matt&lt;/owners&gt; &lt;description&gt;I hope you enjoy MyPackage&lt;/description&gt; &lt;tags&gt;Boxstarter&lt;/tags&gt; &lt;/metadata&gt; &lt;/package&gt; </pre> <p>And a tools/ChocolateyInstall.ps1 with this code:</p> <pre> try { Write-Host 'MyPackage' } catch { throw } </pre> <h3>The Boxstarter Local Repository</h3> <p> These files are saved to your local Boxstarter Repository. This is where Boxstarter will store your local packages and running the Install-BoxstarterPackage command will look here first before any external feed. The repository is located in your AppData directory but you can always find out exactly where by inspecting the global Boxstarter variable <code>$Boxstarter.LocalRepo</code>. </p> <img class="img-responsive" src="Images/global.png"/> <p>You can change the location by using the Set-BoxstarterConfig command:</p> <pre> Set-BoxstarterConfig -LocalRepo "c:\some\other\location" </pre> <h3>Editing and adding resources to your package</h3> <p>Optionally, you can call the New-BoxstarterPackage command with a path argument and supply a directory that contains files you want to be included in the package:</p> <pre> New-BoxstarterPackage -Name MyPackage -Description "I hope you enjoy MyPackage" -Path "c:\somePath" </pre> <p>Boxstarter will copy all files at, and below, c:\somepath and you can refer to these files in your ChocolateyInstall.ps1 using <code>Get-PackageRoot</code>.</p> <pre> Copy-Item (Join-Path -Path (Get-PackageRoot($MyInvocation)) -ChildPath 'console.xml') -Force $env:appdata\console\console.xml </pre> <p>Assuming you have a console.xml file at the root of the path you provided to <code>New-BoxstarterPackage</code>, you can access that file from your ChocolateyInstall.ps1 script.</p> <h3>Composing the ChocolateyInstall Script</h3> <p>If you are already familiar with authoring <a href="https://github.com/chocolatey/choco/wiki/CreatePackagesQuickStart">Chocolatey package scripts</a>, you know how to do this already. The only difference with Boxstarter scripts is that your script also has access to Boxstarter's API for configuring windows, running updates as well as logging and reboot control.</p> <p>Lets open the ChocolateyInstall.ps1 script that the New-BoxstarterPackage command created for our MyPackage package:</p> <pre> Notepad (Join-Path -Path $Boxstarter.LocalRepo -ChildPath "MyPackage\tools\ChocolateyInstall.ps1") </pre> <p>Replace the boilerplate code with something that will actually do something:</p> <pre> Update-ExecutionPolicy Unrestricted Move-LibraryDirectory "Personal" "$env:UserProfile\skydrive\documents" Set-ExplorerOptions -showHiddenFilesFoldersDrives -showProtectedOSFiles -showFileExtensions Set-TaskbarSmall Enable-RemoteDesktop cinst VisualStudio2013ExpressWeb cinst fiddler4 cinst mssqlserver2012express cinst git-credential-winstore cinst console-devel cinst poshgit cinst windbg cinst Microsoft-Hyper-V-All -source windowsFeatures cinst IIS-WebServerRole -source windowsfeatures cinst IIS-HttpCompressionDynamic -source windowsfeatures cinst TelnetClient -source windowsFeatures Install-ChocolateyPinnedTaskBarItem "$env:windir\system32\mstsc.exe" Install-ChocolateyPinnedTaskBarItem "$env:programfiles\console\console.exe" Copy-Item (Join-Path -Path (Get-PackageRoot($MyInvocation)) -ChildPath 'console.xml') -Force $env:appdata\console\console.xml Install-ChocolateyVsixPackage xunit http://visualstudiogallery.msdn.microsoft.com/463c5987-f82b-46c8-a97e-b1cde42b9099/file/66837/1/xunit.runner.visualstudio.vsix Install-ChocolateyVsixPackage autowrocktestable http://visualstudiogallery.msdn.microsoft.com/ea3a37c9-1c76-4628-803e-b10a109e7943/file/73131/1/AutoWrockTestable.vsix Install-WindowsUpdate -AcceptEula </pre> <p>This script does several things and leverage's both Chocolatey and Boxstarter commands. Here is what this will do:</p> <ul> <li>Set the PowerShell execution policy to be able to run all scripts</li> <li>Move your personal folders to sync with SkyDrive</li> <li>Make Windows Explorer tolerable</li> <li>Enable Remote Desktop to the box</li> <li>Download and install a bunch of software</li> <li>Enable Windows Features Hyper-V, IIS and the Telnet client</li> <li>Create some shortcuts in the taskbar for common applications</li> <li>Copy your console configuration file with your favorite settings</li> <li>Install some Visual Studio extensions from the Visual Studio gallery</li> <li>Install all critical windows updates</li> </ul> <h3>Boxstarter ChocolateyInstall Considerations</h3> <p> Boxstarter can run any Chocolatey package and any valid PowerShell inside that package. However, there are a few things to consider that may make a Boxstarter Chocolatey package a better installation experience.</p> <ul> <li>Boxstarter Chocolatey packages should be repeatable. This is especially true if you anticipate the need to reboot. When Boxstarter reboots, it starts running the package from the beginning. So ensure that there is nothing that would cause the package to break if run twice.</li> <li>If you have several Chocolatey packages that you want to install during the Boxstarter session, it is preferable to call CINST directly from inside your ChocolateyInstall instead of declaring them as dependencies. This is because Boxstarter cannot intercept Chocolatey dependencies so those packages will not have any reboot protections.</li> <li>Do not use <code>Restart-Computer</code> or any other command that will reboot the computer. Instead use <code>Invoke-Reboot</code>. This will allow Boxstarter to get things in order first so that after the machine recovers from the reboot, Boxstarter can log the user back in and restart the install script.</li> </ul> <h3>Packing your Package .nupkg</h3> <p>Once you are finished composing your package contents, you can call the <code>Invoke-BoxstarterBuild MyPackage</code> command to generate the *.nupkg file for MyPackage. Boxstarter saves these files in the root of <code>$Boxstarter.LocalRepo</code>. If you have several packages in the local repository that you want to build all at once, omit the package name from the command to build all packages in the repository.</p> <|start_filename|>.teamcity/settings.kts<|end_filename|> import jetbrains.buildServer.configs.kotlin.v2019_2.* import jetbrains.buildServer.configs.kotlin.v2019_2.buildFeatures.pullRequests import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.nuGetPublish import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.powerShell import jetbrains.buildServer.configs.kotlin.v2019_2.triggers.vcs import jetbrains.buildServer.configs.kotlin.v2019_2.vcs.GitVcsRoot version = "2021.2" project { buildType(Boxstarter) } object Boxstarter : BuildType({ id = AbsoluteId("Boxstarter") name = "Build" artifactRules = """ buildArtifacts => buildArtifacts web => web-%system.build.number%.zip """.trimIndent() params { param("env.vcsroot.branch", "%vcsroot.branch%") param("env.Git_Branch", "%teamcity.build.vcs.branch.Boxstarter_BoxstarterVcsRoot%") param("teamcity.git.fetchAllHeads", "true") param("env.CERT_SUBJECT_NAME", "Chocolatey Software, Inc.") } vcs { root(DslContext.settingsRoot) branchFilter = """ +:* """.trimIndent() } steps { powerShell { name = "Prerequisites" scriptMode = script { content = """ if ((Get-WindowsFeature -Name NET-Framework-Core).InstallState -ne 'Installed') { Install-WindowsFeature -Name NET-Framework-Core } """.trimIndent() } } step { name = "Include Signing Keys" type = "PrepareSigningEnvironment" } powerShell { name = "Build" scriptMode = file { path = "BuildScripts/build.ps1" } param("jetbrains_powershell_scriptArguments", "quick-deploy -buildCounter %build.counter%") } nuGetPublish { name = "Publish Packages" conditions { matches("teamcity.build.branch", "^(develop|release/.*|hotfix/.*|tags/.*)${'$'}") } toolPath = "%teamcity.tool.NuGet.CommandLine.DEFAULT%" packages = "buildArtifacts/*.nupkg" serverUrl = "%env.NUGETDEV_SOURCE%" apiKey = "%env.NUGETDEV_API_KEY%" } } triggers { vcs { branchFilter = "" } } features { pullRequests { provider = github { authType = token { token = "%system.GitHubPAT%" } } } } })
mwrock/boxstarter
<|start_filename|>strslice_test.go<|end_filename|> package villa import ( "fmt" "testing" "github.com/golangplus/testing/assert" ) func TestStringSlice(t *testing.T) { defer __(o_(t)) var s StringSlice for i := 0; i < 1000; i++ { s.Add(string(rune('A' + i))) } assert.Equal(t, "len(s)", len(s), 1000) s.Clear() assert.Equal(t, "len(s)", len(s), 0) s = StringSlice{} s.Add("E", "B") s.Insert(1, "C", "D") assert.Equal(t, "len(s)", len(s), 4) assert.StringEqual(t, "s", s, "[E C D B]") } func ExampleStringSlice_direct() { type A struct { B string C int } var s StringSlice s.Add(10, "B", 30) fmt.Println(s) s.InsertSlice(len(s), []A{A{"E", 60}, A{"G", 80}}) fmt.Println(s) s.Insert(1, "D", "E") fmt.Println(s) s.Swap(1, len(s)-1) fmt.Println(s) s.RemoveRange(1, 3) fmt.Println(s) s.Fill(0, len(s), "EE") fmt.Println(s) s.Clear() fmt.Println(s) // Output: // [10 B 30] // [10 B 30 {E 60} {G 80}] // [10 D E B 30 {E 60} {G 80}] // [10 {G 80} E B 30 {E 60} D] // [10 B 30 {E 60} D] // [EE EE EE EE EE] // [] } func ExampleStringSlice_typecnv() { type A struct { B string C int } var s []string (*StringSlice)(&s).Add(10, "B", 30) fmt.Println(s) (*StringSlice)(&s).InsertSlice(len(s), []A{A{"E", 60}, A{"G", 80}}) fmt.Println(s) (*StringSlice)(&s).Insert(1, "D", "E") fmt.Println(s) StringSlice(s).Swap(1, len(s)-1) fmt.Println(s) (*StringSlice)(&s).RemoveRange(1, 3) fmt.Println(s) StringSlice(s).Fill(0, len(s), "EE") fmt.Println(s) (*StringSlice)(&s).Clear() fmt.Println(s) // Output: // [10 B 30] // [10 B 30 {E 60} {G 80}] // [10 D E B 30 {E 60} {G 80}] // [10 {G 80} E B 30 {E 60} D] // [10 B 30 {E 60} D] // [EE EE EE EE EE] // [] } func TestStringSliceRemove(t *testing.T) { defer __(o_(t)) var s StringSlice s.Add("A", "B", "C", "D", "E", "F", "G") assert.Equal(t, "len(s)", len(s), 7) assert.StringEqual(t, "s", s, "[A B C D E F G]") s.RemoveRange(2, 5) assert.Equal(t, "len(s)", len(s), 4) assert.StringEqual(t, "s", s, "[A B F G]") s.Remove(2) assert.Equal(t, "len(s)", len(s), 3) assert.StringEqual(t, "s", s, "[A B G]") } func TestStringSliceEquals(t *testing.T) { s := StringSlice([]string{"1", "2", "3", "4"}) assert.Equal(t, "s.Equals(nil)", s.Equals(nil), false) assert.Equal(t, "s.Equals([1, 2, 3, 4])", s.Equals([]string{"1", "2", "3", "4"}), true) assert.Equal(t, "s.Equals([1, 2, 5, 4])", s.Equals([]string{"1", "2", "5", "4"}), false) assert.Equal(t, "s.Equals([1, 2, 3, 4, 5])", s.Equals([]string{"1", "2", "3", "4", "5"}), false) assert.Equal(t, "nil.Equals([]int{})", StringSlice(nil).Equals(s[:0]), true) assert.Equal(t, "nil.Equals([]int{1, 2})", StringSlice(nil).Equals([]string{"1", "2"}), false) }
daviddengcn/go-villa
<|start_filename|>test/exampleFiles.js<|end_filename|> // Case 1 const emptyFile = ``; const expectedEmptyFile = emptyFile; // Case 2 const fileWithoutAnyExport = `class WithoutAnyExportDefault extends Component { render() { return 'whatever'; } }`; const expectedFileWithoutAnyExport = fileWithoutAnyExport; // Case 3 const exportClass = `export default class ExportedClass extends Component { render() { return 'whatever'; } }`; const expectedExportClass = `import {hot} from 'react-hot-loader'; class ExportedClass extends Component { render() { return 'whatever'; } } export default hot(module)(ExportedClass);`; // Case 4 const exportClassAtBottom = `class ExportedClassAtBottom extends Component { render() { return 'whatever'; } } export default ExportedClass;`; const expectedExportClassAtBottom = `import {hot} from 'react-hot-loader'; class ExportedClassAtBottom extends Component { render() { return 'whatever'; } } const reactAppToMakeSuperHot = ExportedClass; export default hot(module)(reactAppToMakeSuperHot);`; // Case 5 const functionalComponent = `export default function exportedFunction () { return 'whatever'; }`; const expectedFunctionalComponent = `import {hot} from 'react-hot-loader'; function exportedFunction () { return 'whatever'; } export default hot(module)(exportedFunction);`; // Case 6 const functionalComponentOnBottom = `function exportedFunctionOnBottom () { return 'whatever'; } export default exportedFunctionOnBottom;`; const expectedFunctionalComponentOnBottom = `import {hot} from 'react-hot-loader'; function exportedFunctionOnBottom () { return 'whatever'; } const reactAppToMakeSuperHot = exportedFunctionOnBottom; export default hot(module)(reactAppToMakeSuperHot);`; // Case 7 const arrowFunction = `export default () => 'whatever';`; const expectedArrowFunction = `import {hot} from 'react-hot-loader'; const reactAppToMakeSuperHot = () => 'whatever'; export default hot(module)(reactAppToMakeSuperHot);`; // Case 8 const wrappedWithHOC = `export class WrappedWithHOC extends Component { render() { return 'export default'; } } export default connect({}, {})(WrappedWithHOC);`; const expectedWrappedWithHOC = `import {hot} from 'react-hot-loader'; export class WrappedWithHOC extends Component { render() { return 'export default'; } } const reactAppToMakeSuperHot = connect({}, {})(WrappedWithHOC); export default hot(module)(reactAppToMakeSuperHot);`; // Case 9 const exportAnonymousClass = `export default class extends Component { render() { return 'whatever'; } }`; expectedExportAnonymousClass = `import {hot} from 'react-hot-loader'; const reactAppToMakeSuperHot = class extends Component { render() { return 'whatever'; } } export default hot(module)(reactAppToMakeSuperHot);`; // Case 10 const functionalComponentNoSpacing = `export default function exportedFunction() { return 'whatever'; }`; const expectedFunctionalComponentNoSpacing = `import {hot} from 'react-hot-loader'; function exportedFunction() { return 'whatever'; } export default hot(module)(exportedFunction);`; // Case 11 const functionalComponentWithParams = `export default function exportedFunction({ name }) { return 'whatever'; }`; const expectedFunctionalComponentWithParams = `import {hot} from 'react-hot-loader'; function exportedFunction({ name }) { return 'whatever'; } export default hot(module)(exportedFunction);`; // Case 12 const functionalComponentNoName = `export default function () { return 'whatever'; }`; const expectedFunctionalComponentNoName = `import {hot} from 'react-hot-loader'; const reactAppToMakeSuperHot = function () { return 'whatever'; } export default hot(module)(reactAppToMakeSuperHot);`; // Case 13 const functionalComponentNoNameAndNoSpace = `export default function() { return 'whatever'; }`; const expectedFunctionalComponentNoNameAndNoSpace = `import {hot} from 'react-hot-loader'; const reactAppToMakeSuperHot = function() { return 'whatever'; } export default hot(module)(reactAppToMakeSuperHot);`; const exampleFiles = { emptyFile, fileWithoutAnyExport, exportClass, exportClassAtBottom, functionalComponent, functionalComponentOnBottom, arrowFunction, wrappedWithHOC, exportAnonymousClass, functionalComponentNoSpacing, functionalComponentWithParams, functionalComponentNoName, functionalComponentNoNameAndNoSpace, }; const expectedOutputFiles = { emptyFile: expectedEmptyFile, fileWithoutAnyExport: expectedFileWithoutAnyExport, exportClass: expectedExportClass, exportClassAtBottom: expectedExportClassAtBottom, functionalComponent: expectedFunctionalComponent, functionalComponentOnBottom: expectedFunctionalComponentOnBottom, arrowFunction: expectedArrowFunction, wrappedWithHOC: expectedWrappedWithHOC, exportAnonymousClass: expectedExportAnonymousClass, functionalComponentNoSpacing: expectedFunctionalComponentNoSpacing, functionalComponentWithParams: expectedFunctionalComponentWithParams, functionalComponentNoName: expectedFunctionalComponentNoName, functionalComponentNoNameAndNoSpace: expectedFunctionalComponentNoNameAndNoSpace, }; module.exports = {exampleFiles, expectedOutputFiles}; <|start_filename|>examples/webpack/webpack-dev-server.js<|end_filename|> const webpack = require('webpack'); const WebpackDevServer = require('webpack-dev-server'); const webpackConfig = require('./webpack.config'); // Defining the Dev Server variables const [protocol, host, port] = ['http', 'localhost', 1234]; const publicPath = `${protocol}://${host}:${port}`; const devServerConfig = { host, hot: true, // allows HMR overlay: true, // allows an overlay for errors in the client noInfo: true, // make sure there are no useless logs in the terminal (will still show errors) clientLogLevel: 'info', // change to warning if there are too many messages in the browser console https: protocol === 'https', // true will generate a localhost https certificate that you should white-list by using this guide (works for all browser beside firefox, which you can whitelist manually in browser) https://www.accuweaver.com/2014/09/19/make-chrome-accept-a-self-signed-certificate-on-osx/ disableHostCheck: true, // no host check for localhost }; // Adding dev-server client too all the applications (we only have one in this example - 'app') Object.keys(webpackConfig.entry).forEach(app => { webpackConfig.entry[app].push(`webpack-dev-server/client?${publicPath}`, 'webpack/hot/dev-server'); }); // Start Webpack Dev Server const server = new WebpackDevServer(webpack(webpackConfig), devServerConfig); server.listen(port, host, () => console.log(`+*+*+ Dev Server up on ${publicPath} +*+*+`)); <|start_filename|>examples/webpack/webpack.config.js<|end_filename|> const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { mode: 'development', // 'cheap-module-source-map' is very fast and is a pretty good debugging experience // 'eval' is faster, but sources will be shown as es5 devtool: 'cheap-module-source-map', // Defining only 1 application called 'app', and in it, only one entry point -> ./src/index.js entry: { app: ['./src/index.js'], }, // Making the bundle available in the server as '/bundle.js' output: { filename: 'bundle.js', publicPath: '/', path: path.resolve(__dirname), }, // What are loaders? https://webpack.js.org/concepts/#loaders module: { rules: [ // Babel transpilation - reference: https://github.com/babel/babel-loader { test: /\.(js|jsx)$/, exclude: /node_modules.*/, use: [ { loader: require.resolve('babel-loader'), options: { // Ignore any .babelrc files, use what is defined below instead babelrc: false, // Babel preset for ES6+ and React presets: [require.resolve('@babel/preset-env'), require.resolve('@babel/preset-react')], plugins: [ // Essential for 'react-hot-loader' require.resolve('react-hot-loader/babel'), ], // use node_modules/.cache/babel-loader to cache the results of the loader cacheDirectory: true, }, }, ], // For a real project you should use Babel with something like https://github.com/amireh/happypack }, // This loader is adding the react-hot-loader's HOC wrapper to every file that match the '/App.js' RegExp // This must appear *after* Babel - to make sure this loader will happen *before* its transpilation { test: /\/App\.js$/, loader: require.resolve('react-hot-loader-loader'), }, // You can add unrelated loaders (non-js) here // For example: css pre-processing, images, sprites, etc. // Everything added here will happen to the files before react-hot-loader-loader loader ], }, // What are plugins? https://webpack.js.org/concepts/#plugins plugins: [ // This will generate a virtual '/index.html' that includes the '/bundle.js' script new HtmlWebpackPlugin(), // HMR (Hot Module Replacement) activated new webpack.HotModuleReplacementPlugin(), // Make the logs readable for humans (uses file path instead of numbers) new webpack.NamedModulesPlugin(), // This is super important - it will make sure that you will not get a full refresh after every error // so react-hot-loader can be used instead to recover after errors new webpack.NoEmitOnErrorsPlugin(), ], }; <|start_filename|>examples/webpack/src/Counter.js<|end_filename|> import React from 'react'; export default class Counter extends React.Component { constructor(props) { super(props); this.state = { counter: 0, }; } componentDidMount() { const updateCounter = () => { this.setState(state => ({ counter: state.counter + 1, })); this.lastTimeout = setTimeout(updateCounter, 1000); }; updateCounter(); } componentWillUnmount() { clearTimeout(this.lastTimeout); } render() { return this.state.counter; } } <|start_filename|>test/AddReactHotLoaderToSource.test.js<|end_filename|> const {exampleFiles, expectedOutputFiles} = require('./exampleFiles'); const ORIGINAL_NODE_ENV = process.env.NODE_ENV; beforeEach(() => { jest.resetModules(); }); describe('AddReactHotLoaderToSource', () => { Object.keys(exampleFiles).forEach(f => { it(`should match expected file for ${f}`, () => { process.env.NODE_ENV = ORIGINAL_NODE_ENV; const AddReactHotLoaderToSource = require('../src/AddReactHotLoaderToSource'); expect(AddReactHotLoaderToSource(exampleFiles[f])).toBe(expectedOutputFiles[f]); }); }); }) describe('AddReactHotLoaderToSource with NODE_ENV=production', () => { Object.keys(exampleFiles).forEach(f => { it(`should not modify file ${f}`, () => { process.env.NODE_ENV = 'production'; const AddReactHotLoaderToSource = require('../src/AddReactHotLoaderToSource'); expect(AddReactHotLoaderToSource(exampleFiles[f])).toBe(exampleFiles[f]); }); }); }); <|start_filename|>package.json<|end_filename|> { "name": "react-hot-loader-loader", "version": "0.0.7", "description": "Webpack Loader to use react-hot-loader without any changes in your App", "main": "webpack.js", "scripts": { "test": "jest" }, "repository": { "type": "git", "url": "git+https://github.com/NoamELB/react-hot-loader-loader.git" }, "keywords": [ "React", "HMR", "Webpack", "Loader" ], "author": "NoamELB", "license": "MIT", "bugs": { "url": "https://github.com/NoamELB/react-hot-loader-loader/issues" }, "homepage": "https://github.com/NoamELB/react-hot-loader-loader#readme", "devDependencies": { "jest": "^23.6.0" }, "peerDependencies": { "react-hot-loader": ">= 4.0.0" } } <|start_filename|>webpack.js<|end_filename|> module.exports = require('./src/AddReactHotLoaderToSource');
mbarzeev/react-hot-loader-loader
<|start_filename|>src/vnet/ip/ip6_packet.h<|end_filename|> /* * Copyright (c) 2015 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * ip6/packet.h: ip6 packet format * * Copyright (c) 2008 <NAME> * * 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. */ #ifndef included_ip6_packet_h #define included_ip6_packet_h #include <vnet/tcp/tcp_packet.h> #include <vnet/ip/ip4_packet.h> #include <stdbool.h> typedef union { u8 as_u8[16]; u16 as_u16[8]; u32 as_u32[4]; u64 as_u64[2]; u64x2 as_u128; uword as_uword[16 / sizeof (uword)]; } __clib_packed ip6_address_t; STATIC_ASSERT_SIZEOF (ip6_address_t, 16); typedef struct { ip6_address_t addr, mask; } ip6_address_and_mask_t; /* Packed so that the mhash key doesn't include uninitialized pad bytes */ typedef CLIB_PACKED (struct { /* IP address must be first for ip_interface_address_get_address() to work */ ip6_address_t ip6_addr; u32 fib_index; }) ip6_address_fib_t; always_inline void ip6_addr_fib_init (ip6_address_fib_t * addr_fib, const ip6_address_t * address, u32 fib_index) { addr_fib->ip6_addr = *address; addr_fib->fib_index = fib_index; } /* Special addresses: unspecified ::/128 loopback ::1/128 global unicast 2000::/3 unique local unicast fc00::/7 link local unicast fe80::/10 multicast ff00::/8 ietf reserved everything else. */ #define foreach_ip6_multicast_address_scope \ _ (loopback, 0x1) \ _ (link_local, 0x2) \ _ (admin_local, 0x4) \ _ (site_local, 0x5) \ _ (organization_local, 0x8) \ _ (global, 0xe) #define foreach_ip6_multicast_link_local_group_id \ _ (all_hosts, 0x1) \ _ (all_routers, 0x2) \ _ (rip_routers, 0x9) \ _ (eigrp_routers, 0xa) \ _ (pim_routers, 0xd) \ _ (mldv2_routers, 0x16) typedef enum { #define _(f,n) IP6_MULTICAST_SCOPE_##f = n, foreach_ip6_multicast_address_scope #undef _ } ip6_multicast_address_scope_t; typedef enum { #define _(f,n) IP6_MULTICAST_GROUP_ID_##f = n, foreach_ip6_multicast_link_local_group_id #undef _ } ip6_multicast_link_local_group_id_t; always_inline uword ip6_address_is_multicast (const ip6_address_t * a) { return a->as_u8[0] == 0xff; } always_inline void ip6_address_copy (ip6_address_t * dst, const ip6_address_t * src) { dst->as_u64[0] = src->as_u64[0]; dst->as_u64[1] = src->as_u64[1]; } always_inline void ip6_set_reserved_multicast_address (ip6_address_t * a, ip6_multicast_address_scope_t scope, u16 id) { a->as_u64[0] = a->as_u64[1] = 0; a->as_u16[0] = clib_host_to_net_u16 (0xff00 | scope); a->as_u16[7] = clib_host_to_net_u16 (id); } always_inline void ip6_set_solicited_node_multicast_address (ip6_address_t * a, u32 id) { /* 0xff02::1:ffXX:XXXX. */ a->as_u64[0] = a->as_u64[1] = 0; a->as_u16[0] = clib_host_to_net_u16 (0xff02); a->as_u8[11] = 1; ASSERT ((id >> 24) == 0); id |= 0xff << 24; a->as_u32[3] = clib_host_to_net_u32 (id); } always_inline void ip6_multicast_ethernet_address (u8 * ethernet_address, u32 group_id) { ethernet_address[0] = 0x33; ethernet_address[1] = 0x33; ethernet_address[2] = ((group_id >> 24) & 0xff); ethernet_address[3] = ((group_id >> 16) & 0xff); ethernet_address[4] = ((group_id >> 8) & 0xff); ethernet_address[5] = ((group_id >> 0) & 0xff); } always_inline uword ip6_address_is_equal (const ip6_address_t * a, const ip6_address_t * b) { int i; for (i = 0; i < ARRAY_LEN (a->as_uword); i++) if (a->as_uword[i] != b->as_uword[i]) return 0; return 1; } always_inline uword ip6_address_is_equal_masked (const ip6_address_t * a, const ip6_address_t * b, const ip6_address_t * mask) { int i; for (i = 0; i < ARRAY_LEN (a->as_uword); i++) { uword a_masked, b_masked; a_masked = a->as_uword[i] & mask->as_uword[i]; b_masked = b->as_uword[i] & mask->as_uword[i]; if (a_masked != b_masked) return 0; } return 1; } always_inline void ip6_address_mask (ip6_address_t * a, const ip6_address_t * mask) { int i; for (i = 0; i < ARRAY_LEN (a->as_uword); i++) a->as_uword[i] &= mask->as_uword[i]; } always_inline void ip6_address_set_zero (ip6_address_t * a) { int i; for (i = 0; i < ARRAY_LEN (a->as_uword); i++) a->as_uword[i] = 0; } always_inline void ip6_address_mask_from_width (ip6_address_t * a, u32 width) { int i, byte, bit, bitnum; ASSERT (width <= 128); clib_memset (a, 0, sizeof (a[0])); for (i = 0; i < width; i++) { bitnum = (7 - (i & 7)); byte = i / 8; bit = 1 << bitnum; a->as_u8[byte] |= bit; } } always_inline uword ip6_address_is_zero (const ip6_address_t * a) { int i; for (i = 0; i < ARRAY_LEN (a->as_uword); i++) if (a->as_uword[i] != 0) return 0; return 1; } /* Check for unspecified address ::0 */ always_inline uword ip6_address_is_unspecified (const ip6_address_t * a) { return ip6_address_is_zero (a); } /* Check for loopback address ::1 */ always_inline uword ip6_address_is_loopback (const ip6_address_t * a) { return (a->as_u64[0] == 0 && a->as_u32[2] == 0 && a->as_u16[6] == 0 && a->as_u8[14] == 0 && a->as_u8[15] == 1); } /* Check for link local unicast fe80::/10. */ always_inline uword ip6_address_is_link_local_unicast (const ip6_address_t * a) { return a->as_u8[0] == 0xfe && (a->as_u8[1] & 0xc0) == 0x80; } /* Check for unique local unicast fc00::/7. */ always_inline uword ip6_address_is_local_unicast (const ip6_address_t * a) { return (a->as_u8[0] & 0xfe) == 0xfc; } /* Check for unique global unicast 2000::/3. */ always_inline uword ip6_address_is_global_unicast (const ip6_address_t * a) { return (a->as_u8[0] & 0xe0) == 0x20; } /* Check for solicited node multicast 0xff02::1:ff00:0/104 */ always_inline uword ip6_is_solicited_node_multicast_address (const ip6_address_t * a) { return (a->as_u32[0] == clib_host_to_net_u32 (0xff020000) && a->as_u32[1] == 0 && a->as_u32[2] == clib_host_to_net_u32 (1) && a->as_u8[12] == 0xff); } always_inline u32 ip6_address_hash_to_u32 (const ip6_address_t * a) { return (a->as_u32[0] ^ a->as_u32[1] ^ a->as_u32[2] ^ a->as_u32[3]); } always_inline u64 ip6_address_hash_to_u64 (const ip6_address_t * a) { return (a->as_u64[0] ^ a->as_u64[1]); } typedef struct { /* 4 bit version, 8 bit traffic class and 20 bit flow label. */ u32 ip_version_traffic_class_and_flow_label; /* Total packet length not including this header (but including any extension headers if present). */ u16 payload_length; /* Protocol for next header. */ u8 protocol; /* Hop limit decremented by router at each hop. */ u8 hop_limit; /* Source and destination address. */ ip6_address_t src_address, dst_address; } ip6_header_t; #define IP6_PACKET_TC_MASK 0x0FF00000 #define IP6_PACKET_DSCP_MASK 0x0FC00000 #define IP6_PACKET_ECN_MASK 0x00300000 #define IP6_PACKET_FL_MASK 0x000FFFFF always_inline ip_dscp_t ip6_traffic_class (const ip6_header_t * i) { return (i->ip_version_traffic_class_and_flow_label & IP6_PACKET_TC_MASK) >> 20; } static_always_inline ip_dscp_t ip6_traffic_class_network_order (const ip6_header_t * ip6) { return (clib_net_to_host_u32 (ip6->ip_version_traffic_class_and_flow_label) & IP6_PACKET_TC_MASK) >> 20; } static_always_inline ip_dscp_t ip6_dscp_network_order (const ip6_header_t * ip6) { return (clib_net_to_host_u32 (ip6->ip_version_traffic_class_and_flow_label) & IP6_PACKET_DSCP_MASK) >> 22; } static_always_inline ip_ecn_t ip6_ecn_network_order (const ip6_header_t * ip6) { return (clib_net_to_host_u32 (ip6->ip_version_traffic_class_and_flow_label) & IP6_PACKET_ECN_MASK) >> 20; } static_always_inline void ip6_set_traffic_class_network_order (ip6_header_t * ip6, ip_dscp_t dscp) { u32 tmp = clib_net_to_host_u32 (ip6->ip_version_traffic_class_and_flow_label); tmp &= 0xf00fffff; tmp |= (dscp << 20); ip6->ip_version_traffic_class_and_flow_label = clib_host_to_net_u32 (tmp); } static_always_inline void ip6_set_dscp_network_order (ip6_header_t * ip6, ip_dscp_t dscp) { u32 tmp = clib_net_to_host_u32 (ip6->ip_version_traffic_class_and_flow_label); tmp &= 0xf03fffff; tmp |= (dscp << 22); ip6->ip_version_traffic_class_and_flow_label = clib_host_to_net_u32 (tmp); } static_always_inline void ip6_set_ecn_network_order (ip6_header_t * ip6, ip_ecn_t ecn) { u32 tmp = clib_net_to_host_u32 (ip6->ip_version_traffic_class_and_flow_label); tmp &= 0xffcfffff; tmp |= ((0x3 & ecn) << 20); ip6->ip_version_traffic_class_and_flow_label = clib_host_to_net_u32 (tmp); } static_always_inline u32 ip6_flow_label_network_order (const ip6_header_t *ip6) { u32 tmp = clib_net_to_host_u32 (ip6->ip_version_traffic_class_and_flow_label); return (tmp & 0xfffff); } static_always_inline void ip6_set_flow_label_network_order (ip6_header_t *ip6, u32 flow_label) { u32 tmp = clib_net_to_host_u32 (ip6->ip_version_traffic_class_and_flow_label); tmp &= 0xfff00000; tmp |= flow_label & 0x000fffff; ip6->ip_version_traffic_class_and_flow_label = clib_host_to_net_u32 (tmp); } static_always_inline u32 ip6_hop_limit_network_order (const ip6_header_t *ip6) { return (ip6->hop_limit); } static_always_inline void ip6_set_hop_limit_network_order (ip6_header_t *ip6, u8 hop_limit) { ip6->hop_limit = hop_limit; } always_inline void * ip6_next_header (ip6_header_t * i) { return (void *) (i + 1); } always_inline void ip6_copy_header (ip6_header_t * dst, const ip6_header_t * src) { dst->ip_version_traffic_class_and_flow_label = src->ip_version_traffic_class_and_flow_label; dst->payload_length = src->payload_length; dst->protocol = src->protocol; dst->hop_limit = src->hop_limit; dst->src_address.as_uword[0] = src->src_address.as_uword[0]; dst->src_address.as_uword[1] = src->src_address.as_uword[1]; dst->dst_address.as_uword[0] = src->dst_address.as_uword[0]; dst->dst_address.as_uword[1] = src->dst_address.as_uword[1]; } always_inline void ip6_tcp_reply_x1 (ip6_header_t * ip0, tcp_header_t * tcp0) { { ip6_address_t src0, dst0; src0 = ip0->src_address; dst0 = ip0->dst_address; ip0->src_address = dst0; ip0->dst_address = src0; } { u16 src0, dst0; src0 = tcp0->src; dst0 = tcp0->dst; tcp0->src = dst0; tcp0->dst = src0; } } always_inline void ip6_tcp_reply_x2 (ip6_header_t * ip0, ip6_header_t * ip1, tcp_header_t * tcp0, tcp_header_t * tcp1) { { ip6_address_t src0, dst0, src1, dst1; src0 = ip0->src_address; src1 = ip1->src_address; dst0 = ip0->dst_address; dst1 = ip1->dst_address; ip0->src_address = dst0; ip1->src_address = dst1; ip0->dst_address = src0; ip1->dst_address = src1; } { u16 src0, dst0, src1, dst1; src0 = tcp0->src; src1 = tcp1->src; dst0 = tcp0->dst; dst1 = tcp1->dst; tcp0->src = dst0; tcp1->src = dst1; tcp0->dst = src0; tcp1->dst = src1; } } typedef CLIB_PACKED (struct { u8 data; }) ip6_pad1_option_t; typedef CLIB_PACKED (struct { u8 type; u8 len; u8 data[0]; }) ip6_padN_option_t; typedef CLIB_PACKED (struct { #define IP6_MLDP_ALERT_TYPE 0x5 u8 type; u8 len; u16 value; }) ip6_router_alert_option_t; typedef CLIB_PACKED (struct { u8 next_hdr; /* Length of this header plus option data in 8 byte units. */ u8 n_data_u64s; }) ip6_ext_header_t; #define foreach_ext_hdr_type \ _(IP6_HOP_BY_HOP_OPTIONS) \ _(IPV6_ROUTE) \ _(IP6_DESTINATION_OPTIONS) \ _(MOBILITY) \ _(HIP) \ _(SHIM6) always_inline u8 ip6_ext_hdr (u8 nexthdr) { #ifdef CLIB_HAVE_VEC128 static const u8x16 ext_hdr_types = { #define _(x) IP_PROTOCOL_##x, foreach_ext_hdr_type #undef _ }; return !u8x16_is_all_zero (ext_hdr_types == u8x16_splat (nexthdr)); #else /* * find out if nexthdr is an extension header or a protocol */ return 0 #define _(x) || (nexthdr == IP_PROTOCOL_##x) foreach_ext_hdr_type; #undef _ #endif } typedef CLIB_PACKED (struct { u8 next_hdr; /* Length of this header plus option data in 8 byte units. */ u8 n_data_u64s; u8 data[0]; }) ip6_hop_by_hop_ext_t; typedef CLIB_PACKED (struct { u8 next_hdr; u8 rsv; u16 fragment_offset_and_more; u32 identification; }) ip6_frag_hdr_t; #define ip6_frag_hdr_offset(hdr) \ (clib_net_to_host_u16 ((hdr)->fragment_offset_and_more) >> 3) #define ip6_frag_hdr_offset_bytes(hdr) (8 * ip6_frag_hdr_offset (hdr)) #define ip6_frag_hdr_more(hdr) \ (clib_net_to_host_u16 ((hdr)->fragment_offset_and_more) & 0x1) #define ip6_frag_hdr_offset_and_more(offset, more) \ clib_host_to_net_u16 (((offset) << 3) + !!(more)) #define ip6_ext_header_len(p) ((((ip6_ext_header_t *)(p))->n_data_u64s+1) << 3) #define ip6_ext_authhdr_len(p) ((((ip6_ext_header_t *)(p))->n_data_u64s+2) << 2) static inline int ip6_ext_header_len_s (ip_protocol_t nh, void *p) { if (ip6_ext_hdr (nh)) return ip6_ext_header_len (p); switch (nh) { case IP_PROTOCOL_IPSEC_AH: return ip6_ext_authhdr_len (p); case IP_PROTOCOL_IPV6_FRAGMENTATION: return sizeof (ip6_frag_hdr_t); case IP_PROTOCOL_ICMP6: return 4; case IP_PROTOCOL_UDP: return 8; case IP_PROTOCOL_TCP: return 20; default: /* Caller is responsible for validating the length of terminating protocols */ ; } return 0; } always_inline void * ip6_ext_next_header (ip6_ext_header_t * ext_hdr) { return (void *) ((u8 *) ext_hdr + ip6_ext_header_len (ext_hdr)); } always_inline void * ip6_ext_next_header_offset (void *hdr, u16 offset) { return (hdr + offset); } always_inline int vlib_object_within_buffer_data (vlib_main_t * vm, vlib_buffer_t * b, void *obj, size_t len) { u8 *o = obj; if (o < b->data || o + len > b->data + vlib_buffer_get_default_data_size (vm)) return 0; return 1; } /* Returns the number of bytes left in buffer from p. */ static inline u32 vlib_bytes_left_in_buffer (vlib_buffer_t *b, void *obj) { return b->current_length - (((u8 *) obj - b->data) - b->current_data); } always_inline void * ip6_ext_next_header_s (ip_protocol_t cur_nh, void *hdr, u32 max_offset, u32 *offset, int *res_nh, bool *last) { u16 hdrlen = 0; int new_nh = -1; void *res = 0; if (ip6_ext_hdr (cur_nh)) { hdrlen = ip6_ext_header_len (hdr); new_nh = ((ip6_ext_header_t *) hdr)->next_hdr; res = hdr + hdrlen; } else if (cur_nh == IP_PROTOCOL_IPV6_FRAGMENTATION) { ip6_frag_hdr_t *frag_hdr = (ip6_frag_hdr_t *) hdr; if (ip6_frag_hdr_offset (frag_hdr) > 0) *last = true; new_nh = frag_hdr->next_hdr; hdrlen = sizeof (ip6_frag_hdr_t); res = hdr + hdrlen; } else if (cur_nh == IP_PROTOCOL_IPSEC_AH) { new_nh = ((ip6_ext_header_t *) hdr)->next_hdr; hdrlen = ip6_ext_authhdr_len (hdr); res = hdr + hdrlen; } else { ; } if (res && (*offset + hdrlen) >= max_offset) { return 0; } *res_nh = new_nh; *offset += hdrlen; return res; } #define IP6_EXT_HDR_MAX (4) /* Maximum number of headers */ #define IP6_EXT_HDR_MAX_DEPTH (256) /* Maximum header depth */ typedef struct { int length; struct { u16 protocol; u16 offset; } eh[IP6_EXT_HDR_MAX]; } ip6_ext_hdr_chain_t; /* * find ipv6 extension header within ipv6 header within * whichever is smallest of buffer or IP6_EXT_HDR_MAX_DEPTH. * The complete header chain must be in first buffer. * * The complete header chain (up to the terminating header) is * returned in res. * Returns the index of the find_hdr_type if > 0. Otherwise * it returns the index of the last header. */ always_inline int ip6_ext_header_walk (vlib_buffer_t *b, ip6_header_t *ip, int find_hdr_type, ip6_ext_hdr_chain_t *res) { int i = 0; int found = -1; void *next_header = ip6_next_header (ip); int next_proto = ip->protocol; res->length = 0; u32 n_bytes_this_buffer = clib_min (vlib_bytes_left_in_buffer (b, ip), IP6_EXT_HDR_MAX_DEPTH); u32 max_offset = clib_min (n_bytes_this_buffer, sizeof (ip6_header_t) + clib_net_to_host_u16 (ip->payload_length)); u32 offset = sizeof (ip6_header_t); if ((ip6_ext_header_len_s (ip->protocol, next_header) + offset) > max_offset) { return -1; } bool last = false; while (next_header) { /* Move on to next header */ res->eh[i].offset = offset; res->eh[i].protocol = next_proto; if (next_proto == find_hdr_type) found = i; i++; if (last) break; if (i > IP6_EXT_HDR_MAX) break; next_header = ip6_ext_next_header_s (next_proto, next_header, max_offset, &offset, &next_proto, &last); } if (ip6_ext_hdr (res->eh[i].protocol)) { /* Header chain is not terminated */ ; } res->length = i; if (find_hdr_type < 0) { return i - 1; } return found != -1 ? found : i - 1; } always_inline void * ip6_ext_header_find (vlib_main_t *vm, vlib_buffer_t *b, ip6_header_t *ip, int find_hdr_type, ip6_ext_header_t **prev_ext_header) { ip6_ext_hdr_chain_t hdr_chain; int res = ip6_ext_header_walk (b, ip, find_hdr_type, &hdr_chain); if (res < 0) return 0; if (prev_ext_header) { if (res > 0) { *prev_ext_header = ip6_ext_next_header_offset (ip, hdr_chain.eh[res - 1].offset); } else { *prev_ext_header = 0; } } if (find_hdr_type == hdr_chain.eh[res].protocol) return ip6_ext_next_header_offset (ip, hdr_chain.eh[res].offset); return 0; } #endif /* included_ip6_packet_h */ /* * fd.io coding-style-patch-verification: ON * * Local Variables: * eval: (c-set-style "gnu") * End: */ <|start_filename|>src/vnet/pg/stream.c<|end_filename|> /* * Copyright (c) 2015 Cisco and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * pg_stream.c: packet generator streams * * Copyright (c) 2008 <NAME> * * 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. */ #include <vnet/vnet.h> #include <vnet/pg/pg.h> #include <vnet/ethernet/ethernet.h> #include <vnet/ip/ip.h> #include <vnet/mpls/mpls.h> #include <vnet/devices/devices.h> /* Mark stream active or inactive. */ void pg_stream_enable_disable (pg_main_t * pg, pg_stream_t * s, int want_enabled) { vlib_main_t *vm; vnet_main_t *vnm = vnet_get_main (); pg_interface_t *pi = pool_elt_at_index (pg->interfaces, s->pg_if_index); want_enabled = want_enabled != 0; if (pg_stream_is_enabled (s) == want_enabled) /* No change necessary. */ return; if (want_enabled) s->n_packets_generated = 0; /* Toggle enabled flag. */ s->flags ^= PG_STREAM_FLAGS_IS_ENABLED; ASSERT (!pool_is_free (pg->streams, s)); vec_validate (pg->enabled_streams, s->worker_index); pg->enabled_streams[s->worker_index] = clib_bitmap_set (pg->enabled_streams[s->worker_index], s - pg->streams, want_enabled); if (want_enabled) { vnet_hw_interface_set_flags (vnm, pi->hw_if_index, VNET_HW_INTERFACE_FLAG_LINK_UP); vnet_sw_interface_set_flags (vnm, pi->sw_if_index, VNET_SW_INTERFACE_FLAG_ADMIN_UP); } if (vlib_num_workers ()) vm = vlib_get_worker_vlib_main (s->worker_index); else vm = vlib_get_main (); vlib_node_set_state (vm, pg_input_node.index, (clib_bitmap_is_zero (pg->enabled_streams[s->worker_index]) ? VLIB_NODE_STATE_DISABLED : VLIB_NODE_STATE_POLLING)); s->packet_accumulator = 0; s->time_last_generate = 0; } static u8 * format_pg_output_trace (u8 * s, va_list * va) { CLIB_UNUSED (vlib_main_t * vm) = va_arg (*va, vlib_main_t *); CLIB_UNUSED (vlib_node_t * node) = va_arg (*va, vlib_node_t *); pg_output_trace_t *t = va_arg (*va, pg_output_trace_t *); u32 indent = format_get_indent (s); s = format (s, "%Ubuffer 0x%x: %U", format_white_space, indent, t->buffer_index, format_vnet_buffer_no_chain, &t->buffer); s = format (s, "\n%U%U", format_white_space, indent, format_ethernet_header_with_length, t->buffer.pre_data, sizeof (t->buffer.pre_data)); return s; } static u8 * format_pg_interface_name (u8 * s, va_list * args) { pg_main_t *pg = &pg_main; u32 if_index = va_arg (*args, u32); pg_interface_t *pi; pi = pool_elt_at_index (pg->interfaces, if_index); s = format (s, "pg%d", pi->id); return s; } static clib_error_t * pg_interface_admin_up_down (vnet_main_t * vnm, u32 hw_if_index, u32 flags) { u32 hw_flags = 0; if (flags & VNET_SW_INTERFACE_FLAG_ADMIN_UP) hw_flags = VNET_HW_INTERFACE_FLAG_LINK_UP; vnet_hw_interface_set_flags (vnm, hw_if_index, hw_flags); return 0; } static int pg_mac_address_cmp (const mac_address_t * m1, const mac_address_t * m2) { return (!mac_address_cmp (m1, m2)); } static clib_error_t * pg_add_del_mac_address (vnet_hw_interface_t * hi, const u8 * address, u8 is_add) { pg_main_t *pg = &pg_main; if (ethernet_address_cast (address)) { mac_address_t mac; pg_interface_t *pi; pi = pool_elt_at_index (pg->interfaces, hi->dev_instance); mac_address_from_bytes (&mac, address); if (is_add) vec_add1 (pi->allowed_mcast_macs, mac); else { u32 pos = vec_search_with_function (pi->allowed_mcast_macs, &mac, pg_mac_address_cmp); if (~0 != pos) vec_del1 (pi->allowed_mcast_macs, pos); } } return (NULL); } /* *INDENT-OFF* */ VNET_DEVICE_CLASS (pg_dev_class) = { .name = "pg", .tx_function = pg_output, .format_device_name = format_pg_interface_name, .format_tx_trace = format_pg_output_trace, .admin_up_down_function = pg_interface_admin_up_down, .mac_addr_add_del_function = pg_add_del_mac_address, }; /* *INDENT-ON* */ static u8 * pg_build_rewrite (vnet_main_t * vnm, u32 sw_if_index, vnet_link_t link_type, const void *dst_address) { u8 *rewrite = NULL; u16 *h; vec_validate (rewrite, sizeof (*h) - 1); h = (u16 *) rewrite; h[0] = clib_host_to_net_u16 (vnet_link_to_l3_proto (link_type)); return (rewrite); } /* *INDENT-OFF* */ VNET_HW_INTERFACE_CLASS (pg_interface_class,static) = { .name = "Packet generator", .build_rewrite = pg_build_rewrite, }; /* *INDENT-ON* */ static u32 pg_eth_flag_change (vnet_main_t * vnm, vnet_hw_interface_t * hi, u32 flags) { /* nothing for now */ return 0; } void pg_interface_enable_disable_coalesce (pg_interface_t * pi, u8 enable, u32 tx_node_index) { if (enable) { gro_flow_table_init (&pi->flow_table, 1 /* is_l2 */ , tx_node_index); pi->coalesce_enabled = 1; } else { pi->coalesce_enabled = 0; gro_flow_table_free (pi->flow_table); } } u8 * format_pg_tun_tx_trace (u8 *s, va_list *args) { CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *); CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *); s = format (s, "PG: tunnel (no-encap)"); return s; } VNET_HW_INTERFACE_CLASS (pg_tun_hw_interface_class) = { .name = "PG-tun", //.format_header = format_gre_header_with_length, //.unformat_header = unformat_gre_header, .build_rewrite = NULL, //.update_adjacency = gre_update_adj, .flags = VNET_HW_INTERFACE_CLASS_FLAG_P2P, .tx_hash_fn_type = VNET_HASH_FN_TYPE_IP, }; u32 pg_interface_add_or_get (pg_main_t *pg, uword if_id, u8 gso_enabled, u32 gso_size, u8 coalesce_enabled, pg_interface_mode_t mode) { vnet_main_t *vnm = vnet_get_main (); vlib_main_t *vm = vlib_get_main (); pg_interface_t *pi; vnet_hw_interface_t *hi; uword *p; u32 i; p = hash_get (pg->if_index_by_if_id, if_id); if (p) { return p[0]; } else { u8 hw_addr[6]; f64 now = vlib_time_now (vm); u32 rnd; pool_get (pg->interfaces, pi); i = pi - pg->interfaces; rnd = (u32) (now * 1e6); rnd = random_u32 (&rnd); clib_memcpy_fast (hw_addr + 2, &rnd, sizeof (rnd)); hw_addr[0] = 2; hw_addr[1] = 0xfe; pi->id = if_id; pi->mode = mode; switch (pi->mode) { case PG_MODE_ETHERNET: ethernet_register_interface (vnm, pg_dev_class.index, i, hw_addr, &pi->hw_if_index, pg_eth_flag_change); break; case PG_MODE_IP4: case PG_MODE_IP6: pi->hw_if_index = vnet_register_interface ( vnm, pg_dev_class.index, i, pg_tun_hw_interface_class.index, i); break; } hi = vnet_get_hw_interface (vnm, pi->hw_if_index); if (gso_enabled) { hi->caps |= VNET_HW_INTERFACE_CAP_SUPPORTS_TCP_GSO; pi->gso_enabled = 1; pi->gso_size = gso_size; if (coalesce_enabled) { pg_interface_enable_disable_coalesce (pi, 1, hi->tx_node_index); } } pi->sw_if_index = hi->sw_if_index; hash_set (pg->if_index_by_if_id, if_id, i); vec_validate (pg->if_id_by_sw_if_index, hi->sw_if_index); pg->if_id_by_sw_if_index[hi->sw_if_index] = i; if (vlib_num_workers ()) { pi->lockp = clib_mem_alloc_aligned (CLIB_CACHE_LINE_BYTES, CLIB_CACHE_LINE_BYTES); *pi->lockp = 0; } } return i; } static void do_edit (pg_stream_t * stream, pg_edit_group_t * g, pg_edit_t * e, uword want_commit) { u32 i, i0, i1, mask, n_bits_left; u8 *v, *s, *m; i0 = e->lsb_bit_offset / BITS (u8); /* Make space for edit in value and mask. */ vec_validate (g->fixed_packet_data, i0); vec_validate (g->fixed_packet_data_mask, i0); if (e->type != PG_EDIT_FIXED) { switch (e->type) { case PG_EDIT_RANDOM: case PG_EDIT_INCREMENT: e->last_increment_value = pg_edit_get_value (e, PG_EDIT_LO); break; default: break; } if (want_commit) { ASSERT (e->type != PG_EDIT_INVALID_TYPE); vec_add1 (g->non_fixed_edits, e[0]); } return; } s = g->fixed_packet_data; m = g->fixed_packet_data_mask; n_bits_left = e->n_bits; i0 = e->lsb_bit_offset / BITS (u8); i1 = e->lsb_bit_offset % BITS (u8); v = e->values[PG_EDIT_LO]; i = pg_edit_n_alloc_bytes (e) - 1; /* Odd low order bits?. */ if (i1 != 0 && n_bits_left > 0) { u32 n = clib_min (n_bits_left, BITS (u8) - i1); mask = pow2_mask (n) << i1; ASSERT (i0 < vec_len (s)); ASSERT (i < vec_len (v)); ASSERT ((v[i] & ~mask) == 0); s[i0] |= v[i] & mask; m[i0] |= mask; i0--; i--; n_bits_left -= n; } /* Even bytes. */ while (n_bits_left >= 8) { ASSERT (i0 < vec_len (s)); ASSERT (i < vec_len (v)); s[i0] = v[i]; m[i0] = ~0; i0--; i--; n_bits_left -= 8; } /* Odd high order bits. */ if (n_bits_left > 0) { mask = pow2_mask (n_bits_left); ASSERT (i0 < vec_len (s)); ASSERT (i < vec_len (v)); ASSERT ((v[i] & ~mask) == 0); s[i0] |= v[i] & mask; m[i0] |= mask; } if (want_commit) pg_edit_free (e); } void pg_edit_group_get_fixed_packet_data (pg_stream_t * s, u32 group_index, void *packet_data, void *packet_data_mask) { pg_edit_group_t *g = pg_stream_get_group (s, group_index); pg_edit_t *e; vec_foreach (e, g->edits) do_edit (s, g, e, /* want_commit */ 0); clib_memcpy_fast (packet_data, g->fixed_packet_data, vec_len (g->fixed_packet_data)); clib_memcpy_fast (packet_data_mask, g->fixed_packet_data_mask, vec_len (g->fixed_packet_data_mask)); } static void perform_fixed_edits (pg_stream_t * s) { pg_edit_group_t *g; pg_edit_t *e; word i; for (i = vec_len (s->edit_groups) - 1; i >= 0; i--) { g = vec_elt_at_index (s->edit_groups, i); vec_foreach (e, g->edits) do_edit (s, g, e, /* want_commit */ 1); /* All edits have either been performed or added to g->non_fixed_edits. So, we can delete the vector. */ vec_free (g->edits); } vec_free (s->fixed_packet_data_mask); vec_free (s->fixed_packet_data); vec_foreach (g, s->edit_groups) { int i; g->start_byte_offset = vec_len (s->fixed_packet_data); /* Relocate and copy non-fixed edits from group to stream. */ vec_foreach (e, g->non_fixed_edits) e->lsb_bit_offset += g->start_byte_offset * BITS (u8); for (i = 0; i < vec_len (g->non_fixed_edits); i++) ASSERT (g->non_fixed_edits[i].type != PG_EDIT_INVALID_TYPE); vec_add (s->non_fixed_edits, g->non_fixed_edits, vec_len (g->non_fixed_edits)); vec_free (g->non_fixed_edits); vec_add (s->fixed_packet_data, g->fixed_packet_data, vec_len (g->fixed_packet_data)); vec_add (s->fixed_packet_data_mask, g->fixed_packet_data_mask, vec_len (g->fixed_packet_data_mask)); } } void pg_stream_add (pg_main_t * pg, pg_stream_t * s_init) { vlib_main_t *vm = vlib_get_main (); pg_stream_t *s; uword *p; if (!pg->stream_index_by_name) pg->stream_index_by_name = hash_create_vec (0, sizeof (s->name[0]), sizeof (uword)); /* Delete any old stream with the same name. */ if (s_init->name && (p = hash_get_mem (pg->stream_index_by_name, s_init->name))) { pg_stream_del (pg, p[0]); } pool_get (pg->streams, s); s[0] = s_init[0]; /* Give it a name. */ if (!s->name) s->name = format (0, "stream%d", s - pg->streams); else s->name = vec_dup (s->name); hash_set_mem (pg->stream_index_by_name, s->name, s - pg->streams); /* Get fixed part of buffer data. */ if (s->edit_groups) perform_fixed_edits (s); /* Determine packet size. */ switch (s->packet_size_edit_type) { case PG_EDIT_INCREMENT: case PG_EDIT_RANDOM: if (s->min_packet_bytes == s->max_packet_bytes) s->packet_size_edit_type = PG_EDIT_FIXED; break; default: /* Get packet size from fixed edits. */ s->packet_size_edit_type = PG_EDIT_FIXED; if (!s->replay_packet_templates) s->min_packet_bytes = s->max_packet_bytes = vec_len (s->fixed_packet_data); break; } s->last_increment_packet_size = s->min_packet_bytes; { int n; s->buffer_bytes = vlib_buffer_get_default_data_size (vm); n = s->max_packet_bytes / s->buffer_bytes; n += (s->max_packet_bytes % s->buffer_bytes) != 0; vec_resize (s->buffer_indices, n); } /* Find an interface to use. */ s->pg_if_index = pg_interface_add_or_get ( pg, s->if_id, 0 /* gso_enabled */, 0 /* gso_size */, 0 /* coalesce_enabled */, PG_MODE_ETHERNET); if (s->sw_if_index[VLIB_RX] == ~0) { pg_interface_t *pi = pool_elt_at_index (pg->interfaces, s->pg_if_index); /* * Default the RX interface if unset. It's a bad mistake to * set [VLIB_TX] prior to ip lookup, since the ip lookup code * interprets [VLIB_TX] as a fib index... */ s->sw_if_index[VLIB_RX] = pi->sw_if_index; } /* Connect the graph. */ s->next_index = vlib_node_add_next (vm, device_input_node.index, s->node_index); } void pg_stream_del (pg_main_t * pg, uword index) { pg_stream_t *s; pg_buffer_index_t *bi; s = pool_elt_at_index (pg->streams, index); pg_stream_enable_disable (pg, s, /* want_enabled */ 0); hash_unset_mem (pg->stream_index_by_name, s->name); vec_foreach (bi, s->buffer_indices) { clib_fifo_free (bi->buffer_fifo); } pg_stream_free (s); pool_put (pg->streams, s); } void pg_stream_change (pg_main_t * pg, pg_stream_t * s) { /* Determine packet size. */ switch (s->packet_size_edit_type) { case PG_EDIT_INCREMENT: case PG_EDIT_RANDOM: if (s->min_packet_bytes == s->max_packet_bytes) s->packet_size_edit_type = PG_EDIT_FIXED; case PG_EDIT_FIXED: break; default: /* Get packet size from fixed edits. */ s->packet_size_edit_type = PG_EDIT_FIXED; if (!s->replay_packet_templates) s->min_packet_bytes = s->max_packet_bytes = vec_len (s->fixed_packet_data); break; } s->last_increment_packet_size = s->min_packet_bytes; } /* * fd.io coding-style-patch-verification: ON * * Local Variables: * eval: (c-set-style "gnu") * End: */ <|start_filename|>src/plugins/perfmon/intel/bundle/topdown_metrics.c<|end_filename|> /* * Copyright (c) 2021 Intel and/or its affiliates. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <vnet/vnet.h> #include <vppinfra/math.h> #include <perfmon/perfmon.h> #include <perfmon/intel/core.h> #define GET_METRIC(m, i) (((m) >> (i * 8)) & 0xff) #define GET_RATIO(m, i) (((m) >> (i * 32)) & 0xffffffff) #define RDPMC_SLOTS (1 << 30) /* fixed slots */ #define RDPMC_METRICS (1 << 29) /* l1 & l2 metric counters */ #define FIXED_COUNTER_SLOTS 3 #define METRIC_COUNTER_TOPDOWN_L1_L2 0 typedef enum { TOPDOWN_E_RETIRING = 0, TOPDOWN_E_BAD_SPEC, TOPDOWN_E_FE_BOUND, TOPDOWN_E_BE_BOUND, TOPDOWN_E_HEAVYOPS, TOPDOWN_E_LIGHTOPS, TOPDOWN_E_BMISPRED, TOPDOWN_E_MCHCLEAR, TOPDOWN_E_FETCHLAT, TOPDOWN_E_FETCH_BW, TOPDOWN_E_MEMBOUND, TOPDOWN_E_CORBOUND, TOPDOWN_E_MAX, } topdown_e_t; enum { TOPDOWN_E_RDPMC_SLOTS = 0, TOPDOWN_E_RDPMC_METRICS, }; typedef f64 (topdown_lvl1_parse_fn_t) (void *, topdown_e_t); /* Parse thread level states from perfmon_reading */ static_always_inline f64 topdown_lvl1_perf_reading (void *ps, topdown_e_t e) { perfmon_reading_t *ss = (perfmon_reading_t *) ps; /* slots are at value[0], everthing else follows at +1 */ return ((f64) ss->value[e + 1] / ss->value[0]) * 100; } static_always_inline f64 topdown_lvl1_rdpmc_metric (void *ps, topdown_e_t e) { perfmon_node_stats_t *ss = (perfmon_node_stats_t *) ps; f64 slots_t0 = ss->t[0].value[TOPDOWN_E_RDPMC_SLOTS] * ((f64) GET_METRIC (ss->t[0].value[TOPDOWN_E_RDPMC_METRICS], e) / 0xff); f64 slots_t1 = ss->t[1].value[TOPDOWN_E_RDPMC_SLOTS] * ((f64) GET_METRIC (ss->t[1].value[TOPDOWN_E_RDPMC_METRICS], e) / 0xff); u64 slots_delta = ss->t[1].value[TOPDOWN_E_RDPMC_SLOTS] - ss->t[0].value[TOPDOWN_E_RDPMC_SLOTS]; slots_t1 = slots_t1 - slots_t0; return (slots_t1 / slots_delta) * 100; } static u8 * format_topdown_lvl1 (u8 *s, va_list *args) { void *ps = va_arg (*args, void *); u64 idx = va_arg (*args, int); perfmon_bundle_type_t type = va_arg (*args, perfmon_bundle_type_t); f64 sv = 0; topdown_lvl1_parse_fn_t *parse_fn, *parse_fns[PERFMON_BUNDLE_TYPE_MAX] = { 0, topdown_lvl1_rdpmc_metric, topdown_lvl1_perf_reading, 0 }; parse_fn = parse_fns[type]; ASSERT (parse_fn); switch (idx) { case 0: sv = parse_fn (ps, TOPDOWN_E_BAD_SPEC) + parse_fn (ps, TOPDOWN_E_RETIRING); break; case 1: sv = parse_fn (ps, TOPDOWN_E_BE_BOUND) + parse_fn (ps, TOPDOWN_E_FE_BOUND); break; default: sv = parse_fn (ps, (topdown_e_t) idx - 2); break; } s = format (s, "%f", sv); return s; } static perfmon_cpu_supports_t topdown_lvl1_cpu_supports[] = { /* Intel ICX supports papi/thread or rdpmc/node */ { clib_cpu_supports_avx512_bitalg, PERFMON_BUNDLE_TYPE_NODE_OR_THREAD } }; PERFMON_REGISTER_BUNDLE (topdown_lvl1_metric) = { .name = "topdown-level1", .description = "Top-down Microarchitecture Analysis Level 1", .source = "intel-core", .events[0] = INTEL_CORE_E_TOPDOWN_SLOTS, .events[1] = INTEL_CORE_E_TOPDOWN_L1_RETIRING_METRIC, .events[2] = INTEL_CORE_E_TOPDOWN_L1_BAD_SPEC_METRIC, .events[3] = INTEL_CORE_E_TOPDOWN_L1_FE_BOUND_METRIC, .events[4] = INTEL_CORE_E_TOPDOWN_L1_BE_BOUND_METRIC, .n_events = 5, .preserve_samples = 0x1F, .cpu_supports = topdown_lvl1_cpu_supports, .n_cpu_supports = ARRAY_LEN (topdown_lvl1_cpu_supports), .format_fn = format_topdown_lvl1, .column_headers = PERFMON_STRINGS ("% NS", "% ST", "% NS.RT", "% NS.BS", "% ST.FE", "% ST.BE"), .footer = "Not Stalled (NS),STalled (ST),\n" " Retiring (RT), Bad Speculation (BS),\n" " FrontEnd bound (FE), BackEnd bound (BE)", }; /* Convert the TopDown enum to the perf reading index */ #define TO_LVL2_PERF_IDX(e) \ ({ \ u8 to_idx[TOPDOWN_E_MAX] = { 0, 0, 0, 0, 5, 5, 6, 6, 7, 7, 8, 8 }; \ to_idx[e]; \ }) /* Parse thread level stats from perfmon_reading */ static_always_inline f64 topdown_lvl2_perf_reading (void *ps, topdown_e_t e) { perfmon_reading_t *ss = (perfmon_reading_t *) ps; u64 value = ss->value[TO_LVL2_PERF_IDX (e)]; /* If it is an L1 metric, call L1 format */ if (TOPDOWN_E_BE_BOUND >= e) { return topdown_lvl1_perf_reading (ps, e); } /* all the odd metrics, are inferred from even and L1 metrics */ if (e & 0x1) { topdown_e_t e1 = TO_LVL2_PERF_IDX (e) - 4; value = ss->value[e1] - value; } return (f64) value / ss->value[0] * 100; } /* Convert the TopDown enum to the rdpmc metric byte position */ #define TO_LVL2_METRIC_BYTE(e) \ ({ \ u8 to_metric[TOPDOWN_E_MAX] = { 0, 0, 0, 0, 4, 4, 5, 5, 6, 6, 7, 7 }; \ to_metric[e]; \ }) /* Convert the TopDown L2 enum to the reference TopDown L1 enum */ #define TO_LVL1_REF(e) \ ({ \ u8 to_lvl1[TOPDOWN_E_MAX] = { -1, \ -1, \ -1, \ -1, \ TOPDOWN_E_RETIRING, \ TOPDOWN_E_RETIRING, \ TOPDOWN_E_BAD_SPEC, \ TOPDOWN_E_BAD_SPEC, \ TOPDOWN_E_FE_BOUND, \ TOPDOWN_E_FE_BOUND, \ TOPDOWN_E_BE_BOUND, \ TOPDOWN_E_BE_BOUND }; \ to_lvl1[e]; \ }) static_always_inline f64 topdown_lvl2_rdpmc_metric (void *ps, topdown_e_t e) { f64 r, l1_value = 0; /* If it is an L1 metric, call L1 format */ if (TOPDOWN_E_BE_BOUND >= e) { return topdown_lvl1_rdpmc_metric (ps, e); } /* all the odd metrics, are inferred from even and L1 metrics */ if (e & 0x1) { /* get the L1 reference metric */ l1_value = topdown_lvl1_rdpmc_metric (ps, TO_LVL1_REF (e)); } /* calculate the l2 metric */ r = fabs (l1_value - topdown_lvl1_rdpmc_metric (ps, TO_LVL2_METRIC_BYTE (e))); return r; } static u8 * format_topdown_lvl2 (u8 *s, va_list *args) { void *ps = va_arg (*args, void *); u64 idx = va_arg (*args, int); perfmon_bundle_type_t type = va_arg (*args, perfmon_bundle_type_t); f64 sv = 0; topdown_lvl1_parse_fn_t *parse_fn, *parse_fns[PERFMON_BUNDLE_TYPE_MAX] = { 0, topdown_lvl2_rdpmc_metric, topdown_lvl2_perf_reading, 0 }; parse_fn = parse_fns[type]; ASSERT (parse_fn); sv = parse_fn (ps, (topdown_e_t) idx); s = format (s, "%f", sv); return s; } static perfmon_cpu_supports_t topdown_lvl2_cpu_supports[] = { /* Intel SPR supports papi/thread or rdpmc/node */ { clib_cpu_supports_avx512_fp16, PERFMON_BUNDLE_TYPE_NODE_OR_THREAD } }; PERFMON_REGISTER_BUNDLE (topdown_lvl2_metric) = { .name = "topdown-level2", .description = "Top-down Microarchitecture Analysis Level 2", .source = "intel-core", .events[0] = INTEL_CORE_E_TOPDOWN_SLOTS, .events[1] = INTEL_CORE_E_TOPDOWN_L1_RETIRING_METRIC, .events[2] = INTEL_CORE_E_TOPDOWN_L1_BAD_SPEC_METRIC, .events[3] = INTEL_CORE_E_TOPDOWN_L1_FE_BOUND_METRIC, .events[4] = INTEL_CORE_E_TOPDOWN_L1_BE_BOUND_METRIC, .events[5] = INTEL_CORE_E_TOPDOWN_L2_HEAVYOPS_METRIC, .events[6] = INTEL_CORE_E_TOPDOWN_L2_BMISPRED_METRIC, .events[7] = INTEL_CORE_E_TOPDOWN_L2_FETCHLAT_METRIC, .events[8] = INTEL_CORE_E_TOPDOWN_L2_MEMBOUND_METRIC, .n_events = 9, .preserve_samples = 0x1FF, .cpu_supports = topdown_lvl2_cpu_supports, .n_cpu_supports = ARRAY_LEN (topdown_lvl2_cpu_supports), .format_fn = format_topdown_lvl2, .column_headers = PERFMON_STRINGS ("% RT", "% BS", "% FE", "% BE", "% RT.HO", "% RT.LO", "% BS.BM", "% BS.MC", "% FE.FL", "% FE.FB", "% BE.MB", "% BE.CB"), .footer = "Retiring (RT), Bad Speculation (BS),\n" " FrontEnd bound (1FE), BackEnd bound (BE),\n" " Light Operations (LO), Heavy Operations (HO),\n" " Branch Misprediction (BM), Machine Clears (MC),\n" " Fetch Latency (FL), Fetch Bandwidth (FB),\n" " Memory Bound (MB), Core Bound (CB)", };
LoganathanNallusamy/vpp-1
<|start_filename|>release/songPathRnn/eval/.ipynb_checkpoints/test_from_checkpoint-checkpoint.lua<|end_filename|> require 'torch' require 'nn' require 'optim' require 'rnn' require 'os' --require 'cunn' package.path = package.path ..';./model/batcher/?.lua' package.path = package.path ..';../model/batcher/?.lua' package.path = package.path ..';./model/module/?.lua' package.path = package.path ..';../model/module/?.lua' require 'MapReduce' require 'BatcherFileList' require 'SplitTableNoGrad' require "ConcatTableNoGrad" require "TopK" require "LogSumExp" cmd = torch.CmdLine() cmd:option('-input_dir','','input dir which contains the list files for train/dev/test') cmd:option('-out_file','','output dir for outputing score files') cmd:option('-predicate_name','','output dir for outputing score files') cmd:option('-meanModel',0,'to take the mean of scores of each path. Default is max (0)') cmd:option('-model_path','','model name') cmd:option('-test_list', '', 'file list for test') cmd:option('-gpu_id',-1,'use gpu') cmd:option('-top_k', 2, '0 is max, 1 is top K , 2 is LogSumExp') cmd:option('-k', 5) cmd:text() local params = cmd:parse(arg) local out_file = params.out_file local input_dir = params.input_dir local predicate_name = params.predicate_name local model_path = params.model_path assert(input_dir~='','input_dir isnt set. Point to the dir where train/dev/test.list files reside') data_files={input_dir} local topK = params.top_k local shuffle = false local maxBatches = 1000 local minibatch = 512 local useCuda = (params.gpu_id ~= -1) print("use cuda:", useCuda) if useCuda then require 'cutorch' require 'cunn' end local test_list_file = params.test_list local testBatcher = BatcherFileList(data_files[1], minibatch, shuffle, maxBatches, useCuda, test_list_file) --local labs,inputs,count,classId = testBatcher:getBatch() --print(labs) --print(inputs) print("using model:", model_path) local start_time = os.time() local total_batch_count = 0 local check_file = io.open(model_path) if check_file ~= nil then print("load model...") local predictor_net = torch.load(model_path).predictor_net local reducer = nil if topK == 0 then print('Reducer is max pool') reducer = nn.Max(2) elseif topK == 2 then print('Reducer is log sum') reducer = nn.Sequential():add(nn.LogSumExp(2)):add(nn.Squeeze(2)) else print('Reducer is topK') reducer = nn.Sequential():add(nn.TopK(params.k,2)):add(nn.Mean(2)) end local training_net = nn.Sequential():add(nn.MapReduce(predictor_net,reducer)):add(nn.Sigmoid()) local model = nn.Sequential():add(training_net):add(nn.Select(2,1)) if useCuda then model = model:cuda() end print('start predicting...') -- local totalBatchCounter local batcher = testBatcher -- totalBatchCounter = testBatchCounter -- batcher:reset() -- local out_file = out_dir_p..'/test.scores' local file = io.open(out_file, "w") local counter=0 local batch_counter = 0 while(true) do local labs,inputs,count,classId = batcher:getBatch() if(inputs == nil) then break end labs = labs inputs = inputs if useCuda then labs = labs:cuda() inputs = inputs:cuda() end batch_counter = batch_counter + 1 local preds = model:forward(inputs) for i=1,count do local score = preds[i] local socre_str = string.format("%.5f",score) -- print(type(score)) -- print() local label = labs[i] file:write(counter..'\t'..socre_str..'\t'..label..'\n') counter = counter + 1 end total_batch_count = total_batch_count+1 if total_batch_count % 100 == 0 then print("batch nums:", total_batch_count, "per 100 batch cost time:", (os.time()-start_time)/(total_batch_count/100)) end -- print("batch number:", total_batch_count) end file:close() end print("total cost time:", os.time()-start_time) <|start_filename|>release/songPathRnn/model/net/FeatureEmbedding.lua<|end_filename|> --******************************************************************** --Source: https://github.com/rajarshd/ChainsofReasoning --See Chains of Reasoning over Entities, Relations, and Text using Recurrent Neural Networks --https://arxiv.org/abs/1607.01426 --********************************************************************** -- package.path = package.path ..';/home/rajarshi/EMNLP/LSTM-KBC/model/?.lua' require "ConcatTableNoGrad" -- require "LookupTableWithGrad" -- require "SplitTableNoGrad" -- require "Sum_nc" local FeatureEmbedding = torch.class('FeatureEmbedding') function FeatureEmbedding:getEntityTypeLookUpTable() return self.entityTypeLookUpTable end function FeatureEmbedding:getRelationLookUpTable() return self.relationLookUpTable end function FeatureEmbedding:getEntityLookUpTable() return self.entityLookUpTable end function FeatureEmbedding:getRelationEmbeddingNetwork(relationVocabSize, relationEmbeddingDim) local network = nn.Sequential() local relationLookUpTable = nn.LookupTable(relationVocabSize,relationEmbeddingDim) self.relationLookUpTable = relationLookUpTable return network:add(nn.SelectTable(-1)):add(relationLookUpTable) -- return network:add(nn.LookupTable(relationVocabSize,relationEmbeddingDim)) end function FeatureEmbedding:getEntityTypeEmbeddingNetwork(entityTypeVocabSize, entityTypeEmbeddingDim, numFeatureTemplates, numEntityTypes, isEntityPresent) local network = nn.Sequential() --create the parallel table network local par = nn.ParallelTable() local lookupTable1 = nn.LookupTable(entityTypeVocabSize, entityTypeEmbeddingDim) self.entityTypeLookUpTable = lookupTable1 par:add(lookupTable1) for i = 1,numEntityTypes-1 -- -1 because we have already added for the first feature and one of tne feature is relation which will be added later do local lookupTable = nn.LookupTable(entityTypeVocabSize, entityTypeEmbeddingDim) lookupTable:share(lookupTable1,'weight', 'gradWeight', 'bias', 'gradBias') par:add(lookupTable) end local startIndex = numFeatureTemplates - numEntityTypes - 1 -- -1 because the last and the second last are entity and relation -- if isEntityPresent then -- startIndex = startIndex - 1 --because the second last position is for entities -- end return network:add(nn.NarrowTable(startIndex,numEntityTypes)):add(par):add(nn.CAddTable())--:add(nn.MulConstant(1/numEntityTypes)) end function FeatureEmbedding:getEntityTypeEmbeddingNetworkFeedFwd(typeLookupTable, entityTypeVocabSize, entityTypeEmbeddingDim, numFeatureTemplates, numEntityTypes, isEntityPresent) local network = nn.Sequential() --create the parallel table network local par = nn.ParallelTable() -- local lookupTable1 = nn.LookupTable(entityTypeVocabSize, entityTypeEmbeddingDim) local lookupTable1 = typeLookupTable -- self.entityTypeLookUpTable = lookupTable1 par:add(lookupTable1) for i = 1,numEntityTypes-1 -- -1 because we have already added for the first feature and one of tne feature is relation which will be added later do local lookupTable = nn.LookupTable(entityTypeVocabSize, entityTypeEmbeddingDim) lookupTable:share(lookupTable1,'weight', 'gradWeight', 'bias', 'gradBias') par:add(lookupTable) end local startIndex = numFeatureTemplates - numEntityTypes - 1 -- -1 because the last and the second last are entity and relation -- if isEntityPresent then -- startIndex = startIndex - 1 --because the second last position is for entities -- end return network:add(nn.SplitTableNoGrad(3)):add(nn.NarrowTable(startIndex,numEntityTypes)):add(par):add(nn.CAddTable())--:add(nn.MulConstant(1/numEntityTypes)) end function FeatureEmbedding:getEntityEmbeddingNetwork(entityVocabSize, entityEmbeddingDim, numFeatureTemplates) local network = nn.Sequential() entityLookUpTable = nn.LookupTable(entityVocabSize,entityEmbeddingDim) self.entityLookUpTable = entityLookUpTable return network:add(nn.SelectTable(numFeatureTemplates-1)):add(entityLookUpTable) end function FeatureEmbedding:getEmbeddingNetwork(relationVocabSize, relationEmbeddingDim, entityTypeVocabSize, entityTypeEmbeddingDim, numFeatureTemplates, numEntityTypes) local cat = nn.ConcatTableNoGrad() local relationEmbeddingNetwork = self:getRelationEmbeddingNetwork(relationVocabSize, relationEmbeddingDim) local entityTypeEmbeddingNetwork = self:getEntityTypeEmbeddingNetwork(entityTypeVocabSize, entityTypeEmbeddingDim, numFeatureTemplates, numEntityTypes, false) cat:add(entityTypeEmbeddingNetwork):add(relationEmbeddingNetwork) return nn.Sequential():add(cat):add(nn.JoinTable(3)) -- return relationEmbeddingNetwork end function FeatureEmbedding:getEmbeddingNetworkOnlyEntities(relationVocabSize, relationEmbeddingDim, entityVocabSize, entityEmbeddingDim, numFeatureTemplates) local cat = nn.ConcatTableNoGrad() local relationEmbeddingNetwork = self:getRelationEmbeddingNetwork(relationVocabSize, relationEmbeddingDim) local entityEmbeddingNetwork = self:getEntityEmbeddingNetwork(entityVocabSize, entityEmbeddingDim, numFeatureTemplates) cat:add(entityEmbeddingNetwork):add(relationEmbeddingNetwork) return nn.Sequential():add(cat):add(nn.JoinTable(3)) -- return relationEmbeddingNetwork end function FeatureEmbedding:getEmbeddingNetworkBothEntitiesAndTypes(relationVocabSize, relationEmbeddingDim, entityVocabSize, entityEmbeddingDim, entityTypeVocabSize, entityTypeEmbeddingDim, numFeatureTemplates,numEntityTypes) local cat = nn.ConcatTableNoGrad() local relationEmbeddingNetwork = self:getRelationEmbeddingNetwork(relationVocabSize, relationEmbeddingDim) local entityEmbeddingNetwork = self:getEntityEmbeddingNetwork(entityVocabSize, entityEmbeddingDim, numFeatureTemplates) local entityTypeEmbeddingNetwork = self:getEntityTypeEmbeddingNetwork(entityTypeVocabSize, entityTypeEmbeddingDim, numFeatureTemplates, numEntityTypes, true) cat:add(entityTypeEmbeddingNetwork):add(entityEmbeddingNetwork):add(relationEmbeddingNetwork) return nn.Sequential():add(cat):add(nn.JoinTable(3)) -- return relationEmbeddingNetwork end ---------New faster implementation--------- function FeatureEmbedding:getEmbeddingNetworkFast(relationVocabSize, relationEmbeddingDim, entityTypeVocabSize, entityTypeEmbeddingDim, numFeatureTemplates) local cat = nn.Concat(3) local relationEmbeddingNetwork = self:getRelationEmbeddingNetworkFast(relationVocabSize, relationEmbeddingDim, numFeatureTemplates) local entityTypeEmbeddingNetwork = self:getEntityTypeEmbeddingNetworkFast(entityTypeVocabSize, entityTypeEmbeddingDim, numFeatureTemplates) cat:add(entityTypeEmbeddingNetwork):add(relationEmbeddingNetwork) return nn.Sequential():add(cat) end function FeatureEmbedding:getEntityTypeEmbeddingNetworkFast(entityTypeVocabSize, entityTypeEmbeddingDim, numFeatureTemplates) local network = nn.Sequential() local lookupTable = nn.LookupTableWithGrad(entityTypeVocabSize, entityTypeEmbeddingDim) local mapper = nn.Sequential():add(lookupTable):add(nn.Copy(false,false,true)) local mr1 = nn.MapReduce(mapper,nn.Sum_nc(3)) return network:add(nn.Narrow(3,1,numFeatureTemplates-1)):add(mr1) end function FeatureEmbedding:getRelationEmbeddingNetworkFast(relationVocabSize, relationEmbeddingDim, numFeatureTemplates) local network = nn.Sequential() return network:add(nn.Select(3,numFeatureTemplates)):add(nn.LookupTableWithGrad(relationVocabSize,relationEmbeddingDim)):add(nn.Copy(false,false,true)) end <|start_filename|>release/songPathRnn/model/batcher/BatcherFileList.lua<|end_filename|> --******************************************************************** --Source: https://github.com/rajarshd/ChainsofReasoning --See Chains of Reasoning over Entities, Relations, and Text using Recurrent Neural Networks --https://arxiv.org/abs/1607.01426 --********************************************************************** require 'Batcher' require 'os' local BatcherFileList = torch.class('BatcherFileList') function BatcherFileList:__init(dataDir, batchSize, shuffle, maxBatches, useCuda, filelist) local fileList = dataDir..'/'..filelist self.doShuffle = shuffle self.batchSize = batchSize self.useCuda = useCuda self.gpuLabelsTable = {} -- tables to hold preallocated gpu tensors self.gpuDataTable = {} self.gpuClassIdTable = {} self.emptyBatcherIndex = {} -- table to hold index of batchers which are already empty. When all of them are empty we have to call reset self.numEmptyBatchers = 0 if useCuda then require 'cunn' end self.batchers = {} self.numBatchers = 0 print(string.format('reading file list from %s',fileList)) local file_counter = 0 for file in io.lines(fileList) do -- concatenate with the path to the data directory local batcher = Batcher(dataDir..'/'..file, batchSize, self.doShuffle) table.insert(self.batchers, batcher) self.numBatchers = self.numBatchers + 1 file_counter = file_counter + 1 if file_counter % 1000 == 0 then print(file_counter..' files read!') end end print((string.format(' Done reading file list from %s',fileList))) -- self.maxBatches = math.min(maxBatches, self.numBatchers) self.maxBatches = self.numBatchers self.startIndex = 1 self.endIndex = self.maxBatches self.index = nil if self.doShuffle then self.index = torch.randperm(self.numBatchers) else self.index = torch.Tensor(self.numBatchers) for i=1, self.numBatchers do self.index[i] = i end end self.currentIndex = 1 if useCuda then self:preallocateTensorToGPU() end end function BatcherFileList:preallocateTensorToGPU() -- for k,v in pairs(self.gpuLabelsTable) do --getting the tensors out of the gpu manually probably is more space efficient? -- self.gpuLabelsTable[k]:double() -- self.gpuDataTable[k]:double() -- end self.gpuLabelsTable = {} self.gpuDataTable = {} self.gpuClassIdTable = {} for i=self.startIndex, self.endIndex do local batchIndex = self.index[i] local batcher = self.batchers[batchIndex] local labelDimension, numPaths, numTokensInPath, numFeatureTemplates = batcher:getSizes() local classId = batcher:getClassId() --preallocate batchSize X numPaths X numTokensInPath X numFeatureTemplates tensors; the first dimension batchSize is the max size of the first dimension; so tensor:resize operation wont create any havoc. local labelTensor = torch.CudaTensor(self.batchSize, labelDimension) local dataTensor = torch.CudaTensor(self.batchSize, numPaths, numTokensInPath, numFeatureTemplates) self.gpuLabelsTable[batchIndex] = labelTensor self.gpuDataTable[batchIndex] = dataTensor self.gpuClassIdTable[batchIndex] = classId end self:populateGPUTensor() --populate it here for the first time end --populate the gpu tensors with the next batches from each batcher. If the batcher has been used up, put it in the map. function BatcherFileList:populateGPUTensor() --populate tensors with data for i=self.startIndex, self.endIndex do local batchIndex = self.index[i] local batcher = self.batchers[batchIndex] local labels, data = batcher:getBatch() if labels ~= nil then local labelTensor = self.gpuLabelsTable[batchIndex] local dataTensor = self.gpuDataTable[batchIndex] labelTensor:resize(labels:size()):copy(labels) dataTensor:resize(data:size()):copy(data) else if self.emptyBatcherIndex[batchIndex] == nil then self.numEmptyBatchers = self.numEmptyBatchers + 1 self.emptyBatcherIndex[batchIndex] = 0 --adding to the table with a dummy value. end end end end --to be called when we have gone over every example of training set function BatcherFileList:reset() self.currentIndex = 1 self.emptyBatcherIndex = {} self.numEmptyBatchers = 0 self.startIndex = 1 self.endIndex = self.maxBatches if self.doShuffle then self.index = torch.randperm(self.numBatchers) else self.index = torch.Tensor(self.numBatchers) for i=1, self.numBatchers do self.index[i] = i end end --finally reset all batchers for i=1, self.numBatchers do self.batchers[i]:reset() end if self.useCuda then self:preallocateTensorToGPU() end end --gets all batches present in batchers[startIndex] to batchers[endIndex] function BatcherFileList:getBatchInternal() if self.useCuda then local numBatchesInGPU = self.endIndex - self.startIndex + 1 while self.numEmptyBatchers < numBatchesInGPU do for i = self.currentIndex, self.endIndex do local batchIndex = self.index[i] if self.emptyBatcherIndex[batchIndex] == nil then -- the batcher isnt empty self.currentIndex = i + 1 return self.gpuLabelsTable[batchIndex], self.gpuDataTable[batchIndex], self.gpuClassIdTable[batchIndex] end end self:populateGPUTensor() self.currentIndex = self.startIndex end else if self.currentIndex >= self.numBatchers then self.currentIndex = 1 end for i = self.currentIndex, self.numBatchers do local batchIndex = self.index[i] local batcher = self.batchers[batchIndex] local labels, data = batcher:getBatch() if labels ~= nil then self.currentIndex = i -- print("batcher:getClassId()",batcher:getClassId()) return labels, data, batcher:getClassId() end end end return nil -- end of epoch end function BatcherFileList:getBatch() if self.useCuda then while self.startIndex <= self.numBatchers do local labels, data, classId = self:getBatchInternal() if labels == nil then --all batches in batchers[startIndex] to batchers[endIndex] have been returned self.startIndex = self.endIndex + 1 self.endIndex = math.min(self.startIndex + self.maxBatches - 1, self.numBatchers) self.emptyBatcherIndex = {} self.numEmptyBatchers = 0 self.currentIndex = self.startIndex if self.startIndex <= self.numBatchers then self:preallocateTensorToGPU() end else return labels, data, labels:size(1), classId end end return nil else while self.startIndex <= self.numBatchers do local labels, data, classId = self:getBatchInternal() -- print("BatcherFileList:", classId) if labels == nil then --all batches in batchers[startIndex] to batchers[endIndex] have been returned self.startIndex = self.endIndex + 1 self.endIndex = math.min(self.startIndex + self.maxBatches - 1, self.numBatchers) self.emptyBatcherIndex = {} self.numEmptyBatchers = 0 self.currentIndex = self.startIndex -- if self.startIndex <= self.numBatchers then -- self:preallocateTensorToGPU() -- end else return labels, data, labels:size(1), classId end end return nil end end <|start_filename|>release/songPathRnn/model/module/LookupTableWithGrad.lua<|end_filename|> --******************************************************************** --Source: https://github.com/rajarshd/ChainsofReasoning --See Chains of Reasoning over Entities, Relations, and Text using Recurrent Neural Networks --https://arxiv.org/abs/1607.01426 --********************************************************************** local LookupTableWithGrad, parent = torch.class('nn.LookupTableWithGrad', 'nn.LookupTable') function LookupTableWithGrad:__init(nIndex, nOutput) parent.__init(self,nIndex,nOutput) end function LookupTableWithGrad:updateGradInput(input,gradInput) self.gradInput:resizeAs(input) self.gradInput:zero() return self.gradInput end <|start_filename|>release/songPathRnn/model/OneModel.lua<|end_filename|> --******************************************************************** --Source: https://github.com/rajarshd/ChainsofReasoning --See Chains of Reasoning over Entities, Relations, and Text using Recurrent Neural Networks --https://arxiv.org/abs/1607.01426 --********************************************************************** package.path = package.path ..';../model/batcher/?.lua' package.path = package.path ..';../model/net/?.lua' package.path = package.path ..';../model/model/?.lua' package.path = package.path ..';../model/module/?.lua' package.path = package.path ..';../model/optimizer/?.lua' package.path = package.path ..';../model/criterion/?.lua' require 'torch' require 'nn' require 'optim' require 'rnn' --Dependencies from this package require 'MyOptimizer' require 'OptimizerCallback' require 'BatcherFileList' require 'FeatureEmbedding' require 'MapReduce' require 'TopK' require 'Print' require 'LogSumExp' cmd = torch.CmdLine() -- cmd:option('-trainList','','torch format train file list') cmd:option('-dataDir','','path to the folder containing the dataset') cmd:option('-minibatch',32,'minibatch size') cmd:option('-testTimeMinibatch',32,'minibatch size') cmd:option('-numRowsToGPU',1,'Num of rows to be loaded to GPU from each input file in the file list') cmd:option('-gpuid',-1,'which gpu to use. -1 = use CPU') cmd:option('-lazyCuda',0,'put limited number of batches to gpu. 0 is false') cmd:option('-relationVocabSize',51503,'vocabulary size of relations') cmd:option('-entityTypeVocabSize',2267,'vocabulary size of entity types') cmd:option('-entityVocabSize',1540261,'vocabulary size of entities') cmd:option('-relationEmbeddingDim',50,'embedding dim for relations') cmd:option('-entityTypeEmbeddingDim',50,'embedding dim for entity types') cmd:option('-entityEmbeddingDim',50,'embedding dim for entity types') cmd:option('-numFeatureTemplates',-1,'Number of feature templates') cmd:option('-numEntityTypes',-1,'Number of entity types') cmd:option('-learningRate',0.001,'init learning rate') cmd:option('-learningRateDecay',0,'learning rate decay') cmd:option('-tokenFeatures',1,'whether to embed features') cmd:option('-evaluationFrequency',10,'how often to evaluation on test data') cmd:option('-model',"",'where to save the model. If not specified, does not save') cmd:option('-exptDir',"",'Output directory') cmd:option('-initModel',"",'model checkpoint to initialize from') cmd:option('-paramInit',0.1,'paramInit') cmd:option('-startIteration',1,'Iteration number of starting iteration. Defaults to 1, but for example if you preload model-15, you want the next iteration to be 16') cmd:option('-saveFrequency',50,'how often to save a model checkpoint') cmd:option('-embeddingL2',0.0001,'extra l2 regularization term on the embedding weights') cmd:option('-l2',0.0001,'l2 regularization term on all weights') cmd:option('-architecture',"rnn",'only support rnn') cmd:option('-numEpochs',300,'Number of epochs to run. Please note the way the framework is set up, it doesnt necessarily mean a pass over the data. Set batchesPerEpoch accordingly') cmd:option('-batchesPerEpoch',500,'Number of minibatches in an epoch.') --RNN-specific options cmd:option('-rnnType',"rnn",'lstm or rnn') cmd:option('-rnnDepth',1,'rnn depth') cmd:option('-rnnHidSize',50,'rnn hidsize') cmd:option('-useAdam',0,'use adam') cmd:option('-epsilon',0.00000001,'epsilon for adam') cmd:option('-useGradClip',1,'use gradClip') cmd:option('-gradClipNorm',5,'gradClipNorm') cmd:option('-gradientStepCounter',100,'gradientStepCounter') --option for running just the beaseline model with relations and ignoring the entity types cmd:option('-includeEntityTypes',1,'include entity types') cmd:option('-includeEntity',-1,'include entity') --consider top-k instead of maxpooling cmd:option('-topK',0,'consider top K paths') cmd:option('-K',5,'number of paths to consider') cmd:option('-package_path','','package_path') cmd:option('-createExptDir',1,'createExptDir') cmd:option('-useReLU',1,'ReLU is 1; Sigmoid otherwise') cmd:option('-rnnInitialization',1,'Initialize RNN') cmd:option('-regularize',1,'Regularize?') cmd:option('-numLayers',1,'num layers') cmd:option('-useDropout',0,'to use dropout or not') cmd:option('-dropout',0,'dropout rate') local params = cmd:parse(arg) local tokenFeatures = params.tokenFeatures local debugMode = false local isBinaryClassification = true local numRowsToGPU = params.numRowsToGPU local lazyCuda = params.lazyCuda == 1 local useCuda = params.gpuid ~= -1 local minibatch = params.minibatch local dataDir = params.dataDir local testList = params.testList local relationVocabSize = params.relationVocabSize local relationEmbeddingDim = params.relationEmbeddingDim local entityTypeVocabSize = params.entityTypeVocabSize local entityTypeEmbeddingDim = params.entityTypeEmbeddingDim local entityVocabSize = params.entityVocabSize local entityEmbeddingDim = params.entityEmbeddingDim local numFeatureTemplates = params.numFeatureTemplates local numEntityTypes = params.numEntityTypes assert(numEntityTypes <= numFeatureTemplates) local rnnHidSize = params.rnnHidSize local useAdam = params.useAdam == 1 local includeEntityTypes = params.includeEntityTypes == 1 local includeEntity = params.includeEntity == 1 local isTopK = params.topK == 1 local k = params.K local useGradClip = params.useGradClip == 1 local seed = 12345 local createExptDir = params.createExptDir == 1 local useReLU = params.useReLU == 1 local rnnInitialization = params.rnnInitialization == 1 local labelDimension = 46 local numLayers = params.numLayers local useDropout = params.useDropout local dropout = params.dropout --torch.manualSeed(seed) local exptDir = nil local configFileName = nil local configFile = nil if createExptDir then exptDir = params.exptDir configFileName = exptDir..'/config.txt' configFile = io.open(configFileName,'w') configFile:write('gpu_id\t'..params.gpuid..'\n') configFile:write('model\t'..params.rnnType..'\n') configFile:write('rnnHidSize\t'..params.rnnHidSize..'\n') configFile:write('relationEmbeddingDim\t'..params.relationEmbeddingDim..'\n') configFile:write('entityTypeEmbeddingDim\t'..params.entityTypeEmbeddingDim..'\n') configFile:write('Learning Rate\t'..params.learningRate..'\n') configFile:write('Learning Rate Decay\t'..params.learningRateDecay..'\n') configFile:write('L2\t'..params.l2..'\n') configFile:write('Minibatch\t'..params.minibatch..'\n') configFile:write('numEpochs\t'..params.numEpochs..'\n') configFile:write('numFeatureTemplates\t'..params.numFeatureTemplates..'\n') configFile:write('isTopK\t'..params.topK..'\n') configFile:write('K\t'..params.K..'\n') configFile:write('epsilon\t'..params.epsilon..'\n') configFile:write('useGradClip\t'..params.useGradClip..'\n') configFile:write('gradClipNorm\t'..params.gradClipNorm..'\n') configFile:write('gradientStepCounter\t'..params.gradientStepCounter..'\n') configFile:write('paramInit\t'..params.paramInit..'\n') configFile:write('useReLU\t'..params.useReLU..'\n') if (includeEntityTypes) then configFile:write('includeEntityTypes\t'..'true'..'\n') else configFile:write('includeEntityTypes\t'..'false'..'\n') end if (includeEntity) then configFile:write('includeEntity\t'..'true'..'\n') else configFile:write('includeEntity\t'..'false'..'\n') end configFile:write('numEntityTypes\t'..params.numEntityTypes..'\n') if params.initModel ~= "" then configFile:write('initModel\t'..params.initModel..'\n') end configFile:write('rnnInitialization\t'..params.rnnInitialization..'\n') configFile:write('Regularize\t'..params.regularize..'\n') configFile:write('numLayers\t'..params.numLayers..'\n') configFile:write('useDropout\t'..params.useDropout..'\n') configFile:write('Dropout\t'..params.dropout..'\n') end local gpuid = params.gpuid if(useCuda or lazyCuda) then print('USING GPU') require 'cutorch' require('cunn') cutorch.setDevice(gpuid + 1) cutorch.manualSeed(seed) end tokenprocessor = function (x) return x end labelprocessor = function (x) return x end if(tokenLabels or tokenFeatures)then preprocess = function(a,b,c) return labelprocessor(a),tokenprocessor(b),c end end local shuffle = true local maxBatches = 100 local loadModel = params.initModel ~= "" local predictor_net = nil local embeddingLayer = nil local reducer = nil local training_net = nil local criterion = nil local totalInputEmbeddingDim = 0 local input2hidden = nil local hidden2hidden = nil local input2hiddens = {} local hidden2hiddens = {} -- table to store the params so that I can initialize them apppropriately. -----Define the Architecture----- if(not loadModel) then predictor_net = nn.Sequential() -- now create the embedding layer if includeEntityTypes and includeEntity then embeddingLayer = FeatureEmbedding:getEmbeddingNetworkBothEntitiesAndTypes(relationVocabSize, relationEmbeddingDim, entityVocabSize, entityEmbeddingDim, entityTypeVocabSize, entityTypeEmbeddingDim, numFeatureTemplates,numEntityTypes) totalInputEmbeddingDim = relationEmbeddingDim + entityTypeEmbeddingDim + entityEmbeddingDim elseif includeEntityTypes then embeddingLayer = FeatureEmbedding:getEmbeddingNetwork(relationVocabSize, relationEmbeddingDim, entityTypeVocabSize, entityTypeEmbeddingDim, numFeatureTemplates, numEntityTypes) totalInputEmbeddingDim = relationEmbeddingDim + entityTypeEmbeddingDim elseif includeEntity then embeddingLayer = FeatureEmbedding:getEmbeddingNetworkOnlyEntities(relationVocabSize, relationEmbeddingDim, entityVocabSize, entityEmbeddingDim, numFeatureTemplates) totalInputEmbeddingDim = relationEmbeddingDim + entityEmbeddingDim else embeddingLayer = FeatureEmbedding:getRelationEmbeddingNetwork(relationVocabSize, relationEmbeddingDim) totalInputEmbeddingDim = relationEmbeddingDim end assert(embeddingLayer ~= nil) assert(totalInputEmbeddingDim ~= 0) predictor_net:add(nn.SplitTable(3)):add(embeddingLayer) local nonLinear = nil if useReLU then nonLinear = function() return nn.ReLU() end else nonLinear = function() return nn.Tanh() end end input2hidden = function() return nn.Linear(totalInputEmbeddingDim, rnnHidSize) end hidden2hidden = function() return nn.Linear(rnnHidSize, rnnHidSize) end if(params.rnnType == "lstm") then rnn = function() return nn.FastLSTM(totalInputEmbeddingDim, rnnHidSize) end --todo: add depth elseif (params.rnnType == "gru") then rnn = function() return nn.GRU(totalInputEmbeddingDim, rnnHidSize) end else rnn = function() -- recurrent module local input2hidden = input2hidden() local hidden2hidden = hidden2hidden() table.insert(input2hiddens, input2hidden) table.insert(hidden2hiddens, hidden2hidden) if params.useDropout == 0 then local rm = nn.Sequential() :add(nn.ParallelTable() :add(input2hidden) :add(hidden2hidden)) :add(nn.CAddTable()) :add(nonLinear()) rm = nn.MaskZero(rm,1) --to take care of padding return nn.Recurrence(rm, rnnHidSize, 1) else local i2hNet = nn.Sequential():add(nn.Dropout(params.dropout)):add(input2hidden) -- local h2hNet = nn.Sequential():add(nn.Dropout()):add(hidden2hidden) local h2hNet = nn.Sequential():add(hidden2hidden) local par = nn.ParallelTable() :add(i2hNet) :add(h2hNet) local rm = nn.Sequential():add(par):add(nn.CAddTable()):add(nonLinear()) rm = nn.MaskZero(rm,1) --to take care of padding return nn.Recurrence(rm, rnnHidSize, 1) end end end predictor_net:add(nn.SplitTable(2)) for l=1,params.numLayers do rnn_layer = nn.Sequencer(rnn()) predictor_net:add(rnn_layer) end predictor_net:add(nn.SelectTable(-1)) --select the last state predictor_net:add(nn.Linear(rnnHidSize,labelDimension)) print(predictor_net) else print('initializing model from '..params.initModel) local checkpoint = torch.load(params.initModel) predictor_net = checkpoint.predictor_net embeddingLayer = checkpoint.embeddingLayer end if params.topK == 1 then print('Reducer is topK') reducer = nn.Sequential():add(nn.TopK(k,2)):add(nn.Mean(2)) elseif params.topK == 2 then print('Reducer is LogSumExp') reducer = nn.Sequential():add(nn.LogSumExp(2)):add(nn.Squeeze(2)) else print('Reducer is max pool') reducer = nn.Max(2) end training_net = nn.Sequential():add(nn.MapReduce(predictor_net,reducer)):add(nn.Sigmoid()) -- test code here -- end of test code local classId = 1 criterion = nn.BCECriterion() -- criterion = nn.MaskZeroCriterion(criterion,1) if(useCuda or lazyCuda) then criterion:cuda() training_net:cuda() end if (not loadModel) then for k,param in ipairs(training_net:parameters()) do param:uniform(-1*params.paramInit, params.paramInit) end if rnnInitialization then --initialize the recurrent matrix to identity and bias to zero for _,input2hidden in pairs(input2hiddens) do local params, gradParams = input2hidden:parameters() params[1]:copy(torch.eye(totalInputEmbeddingDim, rnnHidSize)) params[2]:copy(torch.zeros(rnnHidSize)) end for _,hidden2hidden in pairs(hidden2hiddens) do local params, gradParams = hidden2hidden:parameters() params[1]:copy(torch.eye(rnnHidSize)) params[2]:copy(torch.zeros(rnnHidSize)) end end end print("use cuda:",useCuda) local trainBatcher = BatcherFileList(dataDir, minibatch, shuffle, maxBatches, useCuda, 'train.list') --------Initialize Optimizer------- local regularization = { l2 = {}, params = {} } local embeddingL2 = params.embeddingL2 table.insert(regularization.l2,params.l2) table.insert(regularization.params,embeddingLayer) local momentum = 1.0 local dampening = 0.95 local beta1 = 0.9 local beta2 = 0.999 local epsilon = params.epsilon local optConfig = {} local optimMethod = nil if(useAdam) then optimMethod = optim.adam print('Using Adam!') if createExptDir then configFile:write('epsilon\t'..epsilon..'\n') configFile:write('beta1\t'..beta1..'\n') configFile:write('beta2\t'..beta2..'\n') end optConfig = {learningRate = params.learningRate,beta1 = beta1,beta2 = beta2,epsilon = epsilon} else print('Using adagrad!') optimMethod = optim.adagrad optConfig = {learningRate = params.learningRate, learningRateDecay=params.learningRateDecay} end if createExptDir then configFile:close() end optInfo = { optimMethod = optimMethod, optConfig = optConfig, optState = {}, regularization = regularization, cuda = useCuda, learningRate = params.learningRate, converged = false, startIteration = params.startIteration, entityTypePadToken = entityTypeVocabSize, relationPadToken = relationVocabSize, entityPadToken = entityVocabSize, gradClipNorm = params.gradClipNorm, gradientStepCounter = params.gradientStepCounter, useGradClip = useGradClip, l2 = params.l2, createExptDir = createExptDir, regularize = params.regularize -- recurrence = recur } --------Callbacks------- callbacks = {} local evaluator = nil -- evaluator = BinaryEvaluation(testBatcher,training_net,exptDir) -- local evaluationCallback = OptimizerCallback(params.evaluationFrequency,function(i) evaluator:evaluate(i) end,'evaluation') -- table.insert(callbacks,evaluationCallback) if(params.model ~= "") then local saver = function(i) local file = params.model.."-".."latest" print('saving to '..file) local toSave = { embeddingLayer = embeddingLayer, predictor_net = predictor_net, } torch.save(file,toSave) end if createExptDir then local savingCallback = OptimizerCallback(params.saveFrequency,saver,'saving') table.insert(callbacks,savingCallback) else print('WARNING! - createExptDir is NOT set!') end end --------Training Options------- local trainingOptions = { numEpochs = params.numEpochs, epochHooks = callbacks, minibatchsize = params.minibatch, } ----------------------------------- params.learningRate = params.pretrainLearningRate optimizer = MyOptimizer(training_net,training_net,criterion,trainingOptions,optInfo,params.rnnType) optimizer:train(trainBatcher) <|start_filename|>release/songPathRnn/model/optimizer/TypeOptimizer.lua<|end_filename|> --******************************************************************** --Source: https://github.com/rajarshd/ChainsofReasoning --See Chains of Reasoning over Entities, Relations, and Text using Recurrent Neural Networks --https://arxiv.org/abs/1607.01426 --********************************************************************** local TypeOptimizer = torch.class('TypeOptimizer') function TypeOptimizer:__init(type_net, type_criterion, type_opt_config) self.typeNet = type_net self.typeCriterion = type_criterion self.typeRegularize = type_opt_config.typeRegularize self.typeGradClip = type_opt_config.typeGradClip self.typeParameters, self.typeGradParameters = type_net:getParameters() self.typeGradClipNorm = type_opt_config.typeGradClipNorm self.typeL2 = type_opt_config.typeL2 self.numEpochs = type_opt_config.numEpochs self.useCuda = type_opt_config.useCuda self.totalTypeError = torch.Tensor(1):zero() self.optConfig = type_opt_config.optConfig self.optState = type_opt_config.optState self.typeOptimMethod = type_opt_config.optimMethod self.saveFileName = type_opt_config.saveFileName end function TypeOptimizer:toCuda(x) return self.useCuda and x:cuda() or x:double() end function TypeOptimizer:train(typeBatcher) self.typeNet:training() local prevTime = sys.clock() local numProcessed = 0 --count the total number of batches once. This is for displpaying the progress bar; helps to track time local totalBatches = 0 print('Making a pass of the data to count the batches') while(true) do local ret = typeBatcher:getBatch() if ret == nil then break end totalBatches = totalBatches + 1 end print('Total num batches '..totalBatches) local i = 1 while i <= self.numEpochs do typeBatcher:reset() self.totalTypeError:zero() local batch_counter = 0 while(true) do local ret = typeBatcher:getBatch() if ret == nil then break end pos, types, neg = self:toCuda(ret[1]), self:toCuda(ret[2]), self:toCuda(ret[3]) local data = {pos, types, neg} local labels = self:toCuda(torch.ones(pos:size())) -- its a dummy label, since in BPR criterion there isnt any label local batch = {data = data,labels = labels} self:trainBatch(batch) batch_counter = batch_counter + 1 xlua.progress(batch_counter, totalBatches) end local avgError = self.totalTypeError[1]/batch_counter local currTime = sys.clock() local ElapsedTime = currTime - prevTime local rate = numProcessed/ElapsedTime numProcessed = 0 prevTime = currTime print(string.format('\nIter: %d\navg loss in epoch = %f\ntotal elapsed = %f\ntime per batch = %f',i,avgError, ElapsedTime,ElapsedTime/batch_counter)) print(string.format('examples/sec = %f',rate)) if i%1 == 0 then local file = self.saveFileName.."-"..i print('Saving to '..file) torch.save(file,self.typeNet:clone():float()) end i = i + 1 end end function TypeOptimizer:trainBatch(batch) -- body assert(batch) local parameters = self.typeParameters local gradParameters = self.typeGradParameters local function fEval(x) if parameters ~= x then parameters:copy(x) end self.typeNet:zeroGradParameters() local data = batch.data local labels = batch.labels local pred = self.typeNet:forward(data) local err = self.typeCriterion:forward(pred, labels) local df_do = self.typeCriterion:backward(pred, labels) self.typeNet:backward(data, df_do) if self.typeRegularize == 1 then if self.typeGradClip == 1 then local norm = gradParameters:norm() if norm > self.typeGradClipNorm then gradParameters:mul(self.typeGradClipNorm/norm) end --Also do L2 after clipping gradParameters:add(self.typeL2, parameters) else gradParameters:add(self.typeL2, parameters) end end self.totalTypeError[1] = self.totalTypeError[1] + err return err, gradParameters end self.typeOptimMethod(fEval, parameters, self.optConfig, self.optState) return err end <|start_filename|>release/songPathRnn/data/int2torch.lua<|end_filename|> package.path = package.path ..';../util/?.lua' require 'torch' require 'Util' require 'os' cmd = torch.CmdLine() cmd:option('-input','','input file') cmd:option('-output','','out') cmd:option('-tokenLabels',0,'whether the labels are at the token level (alternative: a single label for the whole sequence)') cmd:option('-tokenFeatures',1,'whether each token has features (alternative: just a single int index into vocab)') cmd:option('-addOne',0,'whether to add 1 to every input (torch is 1-indexed and the preprocessing may be 0-indexed)') local params = cmd:parse(arg) local expectedLen = params.len local outFile = params.output local useTokenLabels = params.tokenLabels == 1 local useTokenFeats = params.tokenFeatures == 1 local multiPaths = true local intLabels = {} local intInputs = {} shift = params.addOne assert(shift == 0 or shift == 1) for line in io.lines(params.input) do local fields = Util:splitByDelim(line,"\t",false) local labelString = fields[1] local inputString = fields[2] local labels = nil if(useTokenLabels) then labels = Util:splitByDelim(labelString," ",true) else labels = tonumber(labelString) end local all_paths = {} if(multiPaths) then local inputs = Util:splitByDelim(inputString,";") for i = 1,#inputs do tokens_in_a_path = Util:splitByDelim(inputs[i]," ") path_table = {} if(useTokenFeats) then for i = 1,#tokens_in_a_path do token_feats = Util:splitByDelim(tokens_in_a_path[i],",") table.insert(path_table,token_feats) end table.insert(all_paths,path_table) else table.insert(all_paths,tokens_in_a_path) end end end table.insert(intLabels,labels) table.insert(intInputs,all_paths) end local labels = Util:table2tensor(intLabels) local data = Util:table2tensor(intInputs) --internally, this asserts that every input sentence is of the same length and there are the same # of features per token if(shift == 1) then -- labels:add(1) data:add(1) end local out = { labels = labels, data = data } torch.save(outFile,out) <|start_filename|>release/songPathRnn/model/batcher/test/testBatcher.lua<|end_filename|> --******************************************************************** --Source: https://github.com/rajarshd/ChainsofReasoning --See Chains of Reasoning over Entities, Relations, and Text using Recurrent Neural Networks --https://arxiv.org/abs/1607.01426 --********************************************************************** --test cases for batcher.lua package.path = package.path ..';../?.lua' require 'Batcher' local fileName = '/iesl/local/rajarshi/data_arvind_original/_music_artist_genre/train/train.txt.25.torch' local batchSize = 32 local shuffle = true local batcher = Batcher(fileName, batchSize, shuffle) local test_counter = 0 -----see if getBatch() works-------------- local labels, data = batcher:getBatch() print('Labels size') print(labels:size()) print('data size') print(data:size()) assert(labels ~= nil and data ~= nil) print(string.format('test %d passed!',test_counter)) test_counter = test_counter + 1 --------see if getClassId() works----------- local classId = batcher:getClassId() print('classId\t'..classId) assert(classId ~= nil) print(string.format('test %d passed!',test_counter)) test_counter = test_counter + 1 ------call getBatch till it returns nil-------- local count = 1 --starting from 1, because already counted 1 in the previous call to getBacther() while(true) do local labels, data = batcher:getBatch() if labels == nil then break end -- print(labels:size()) -- print(data:size()) count = count + 1 end assert(count == 6) --count is the number of batches print(string.format('test %d passed!',test_counter)) test_counter = test_counter + 1 --------------test reset----------------- batcher:reset() local count1 = 0 while(true) do local labels, data = batcher:getBatch() if labels == nil then break end -- print(labels:size()) -- print(data:size()) count1 = count1 + 1 end assert(count1 == 6) print(string.format('test %d passed!',test_counter)) test_counter = test_counter + 1 <|start_filename|>release/songPathRnn/model/batcher/test/testTypeBatcher.lua<|end_filename|> --******************************************************************** --Source: https://github.com/rajarshd/ChainsofReasoning --See Chains of Reasoning over Entities, Relations, and Text using Recurrent Neural Networks --https://arxiv.org/abs/1607.01426 --********************************************************************** package.path = package.path ..';../?.lua' require 'TypeBatcher' local input_file = '/iesl/canvas/rajarshi/emnlp_entity_types_data/train/train.torch' local batchSize = 128 local shuffle = true local vocabSize = 10000 local genNeg = true local typeBatcher = TypeBatcher(input_file, batchSize, shuffle, genNeg, vocabSize) -----see if getBatch() works-------------- print('####################Test 1 - Check if getBatch works####################') local count = 0 local ret = typeBatcher:getBatch() local pos, types, neg = ret[1], ret[2], ret[3] print(pos:size()) print(types:size()) assert(pos ~= nil and types ~= nil) print('Success!') count = count + 1 -- ------call getBatch till it returns nil and reset and then go over it again and check if counts are same-------- print('####################Test 2 - Check if reset works ####################') while(true) do local ret = typeBatcher:getBatch() if ret == nil then break end count = count + 1 end print('Total number of batches are '..count) typeBatcher:reset() local count1 = 0 while(true) do local ret = typeBatcher:getBatch() if ret == nil then break end count1 = count1 + 1 end assert(count1 == count) print('Success!') --Check if genNeg flag works----- print('####################Check if genNeg flag works####################') local genNeg = true typeBatcher = TypeBatcher(input_file, batchSize, shuffle, genNeg, vocabSize) local ret = typeBatcher:getBatch() local pos, types, neg = ret[1], ret[2], ret[3] assert(neg ~= nil) assert(pos:size(1) == neg:size(1)) local max = torch.max(neg) assert(max <= vocabSize) local genNeg = false typeBatcher = TypeBatcher(input_file, batchSize, shuffle, genNeg, vocabSize) local ret = typeBatcher:getBatch() local pos, types, neg = ret[1], ret[2], ret[3] assert(neg == nil) print('Success!') <|start_filename|>release/songPathRnn/model/module/Print.lua<|end_filename|> --******************************************************************** --Source: https://github.com/rajarshd/ChainsofReasoning --See Chains of Reasoning over Entities, Relations, and Text using Recurrent Neural Networks --https://arxiv.org/abs/1607.01426 --********************************************************************** local Print, parent = torch.class('nn.Print', 'nn.Module') function Print:__init(printInput,printGradOutput,msg) self.msg = msg or '' self.printInput = printInput self.printGradOutput = printGradOutput end function Print:updateOutput(input) self.output = input if(self.printInput) then print(self.msg) print('Input:') self:prettyPrint(input) end return self.output end function Print:updateGradInput(input, gradOutput) self.gradInput = gradOutput if(self.printGradOutput) then print(self.msg) print('Grad Input:') self:prettyPrint(gradOutput) end return self.gradInput end function Print:prettyPrint(data) if(torch.isTensor(data) or torch.isStorage(data)) then print(data:size()) else print('Its a table') for k,v in ipairs(data) do self:prettyPrint(v) end end end <|start_filename|>release/songPathRnn/model/net/TypeNetwork.lua<|end_filename|> --******************************************************************** --Source: https://github.com/rajarshd/ChainsofReasoning --See Chains of Reasoning over Entities, Relations, and Text using Recurrent Neural Networks --https://arxiv.org/abs/1607.01426 --********************************************************************** --Most of the code has been (shamelessly) taken from Pat's repo (https://github.com/patverga/torch-relation-extraction) local TypeNetwork = torch.class('TypeNetwork') function TypeNetwork:__init(useCuda) -- body self.useCuda = useCuda or false end function TypeNetwork:to_cuda(x) return self.useCuda and x:cuda() or x:double() end --[[ a function that takes the the output of {pos_row_encoder, col_encoder, neg_row_encoder} and returns {pos score, neg score} ]]-- -- layers to compute the dot prduct of the positive and negative samples function TypeNetwork:build_scorer() local pos_score = nn.Sequential() :add(nn.NarrowTable(1, 2)):add(nn.CMulTable()):add(nn.Sum(2)) local neg_score = nn.Sequential() :add(nn.NarrowTable(2, 2)):add(nn.CMulTable()):add(nn.Sum(2)) local score_table = nn.ConcatTable() :add(pos_score):add(neg_score) return score_table end function TypeNetwork:build_network(pos_row_encoder, col_encoder) local neg_row_encoder = pos_row_encoder:clone() local loading_par_table = nn.ParallelTable() loading_par_table:add(pos_row_encoder) loading_par_table:add(col_encoder) loading_par_table:add(neg_row_encoder) -- add the parallel dot products together into one sequential network local net = nn.Sequential() :add(loading_par_table) :add(self:build_scorer()) -- need to do param sharing after tocuda pos_row_encoder:share(neg_row_encoder, 'weight', 'bias', 'gradWeight', 'gradBias') return net end <|start_filename|>release/songPathRnn/model/criterion/test/TestCriterion.lua<|end_filename|> --******************************************************************** --Source: https://github.com/rajarshd/ChainsofReasoning --See Chains of Reasoning over Entities, Relations, and Text using Recurrent Neural Networks --https://arxiv.org/abs/1607.01426 --********************************************************************** require 'nn'; require '../MyBCECriterion'; batch = 32 labelDim = 6 data = torch.randn(batch, labelDim):clamp(0,1) -- this should be the output of my network I think for i=1,batch do data[i][5] = 1 end labels = torch.zeros(batch,1) -- labels are all zeros; so loss should be high. criterion = nn.MyBCECriterion(5) -- 5 is the id of the target label local err = criterion:forward(data, labels) print(err) local grad = criterion:backward(data, labels) print(grad:size()) print(grad) <|start_filename|>release/songPathRnn/util/Util.lua<|end_filename|> #******************************************************************** #Source: https://github.com/rajarshd/ChainsofReasoning #See Chains of Reasoning over Entities, Relations, and Text using Recurrent Neural Networks #https://arxiv.org/abs/1607.01426 #********************************************************************** -- Shamelessly copying script by <NAME>. require 'os' local Util = torch.class('Util') function Util:splitByDelim(str,delim,convertFromString) local convertFromString = convertFromString or false local function convert(input) if(convertFromString) then return tonumber(input) else return input end end local t = {} local pattern = '([^'..delim..']+)' for word in string.gmatch(str, pattern) do table.insert(t,convert(word)) end return t end function Util:printRow(t) assert(t:dim() == 1) local num = t:size(1) for i = 1,num do io.write(t[i].." ") end io.write('\n') end function Util:printMatMatlab(t) assert(t:dim() == 2) io.write('[') for i = 1,t:size(1) do for j = 1,(t:size(2)-1) do io.write(t[i][j]..",") end io.write(t[i][t:size(2)]) if(i < t:size(1) ) then io.write(';') end end io.write(']\n') end function Util:printRow(t) assert(t:dim() == 1) local num = t:size(1) for i = 1,num do io.write(t[i].." ") end io.write('\n') end function Util:printMat(t) assert(t:dim() == 2) for i = 1,t:size(1) do Util:printRow(t[i]) end end function Util:loadMap(file) print(string.format('reading from %s',file)) local map = {} for s in io.lines(file) do table.insert(map,s) end return map end function Util:loadReverseMap(file) print(string.format('reading from %s',file)) local map = {} local cnt = 1 for s in io.lines(file) do map[s] = cnt cnt = cnt+1 end return map end function Util:CopyTable(table) copy = {} for j,x in pairs(table) do copy[j] = x end return copy end function Util:deepcopy(orig) local orig_type = type(orig) local copy if orig_type == 'table' then copy = {} for orig_key, orig_value in next, orig, nil do copy[Util:deepcopy(orig_key)] = Util:deepcopy(orig_value) end setmetatable(copy, Util:deepcopy(getmetatable(orig))) elseif torch.isTensor(orig) then copy = orig:clone() else -- number, string, boolean, etc copy = orig end return copy end function Util:assertNan(x,msg) if(torch.isTensor(x))then assert(x:eq(x):all(),msg) else assert( x == x, msg) end end --This assumes that the inputs are regularly sized. It accepts inputs of dimension 1,2, or 3 --TODO: it's possible that there's a more efficient way to do this using something in torch function Util:table2tensor(tab) local function fourDtable2tensor(tab) local s1 = #tab local s2 = #tab[1] local s3 = #tab[1][1] local s4 = #tab[1][1][1] local tensor = torch.Tensor(s1,s2,s3,s4) for i = 1,s1 do assert(#tab[i] == s2,"input tensor is expected to have the same number of elements in each dim. issue in dim 2.") for j = 1,s2 do assert(#tab[i][j] == s3,"input tensor is expected to have the same number of elements in each dim. isssue in dim 3.") for k = 1,s3 do assert(#tab[i][j][k] == s4,"input tensor is expected to have the same number of elements in each dim. isssue in dim 4.") for l = 1,s4 do tensor[i][j][k][l] = tab[i][j][k][l] end end end end return tensor end local function threeDtable2tensor(tab) local s1 = #tab local s2 = #tab[1] local s3 = #tab[1][1] local tensor = torch.Tensor(s1,s2,s3) for i = 1,s1 do assert(#tab[i] == s2,"input tensor is expected to have the same number of elements in each dim. issue in dim 2.") for j = 1,s2 do assert(#tab[i][j] == s3,"input tensor is expected to have the same number of elements in each dim. isssue in dim 3.") for k = 1,s3 do tensor[i][j][k] = tab[i][j][k] end end end return tensor end local function twoDtable2tensor(tab) local s1 = #tab local s2 = #tab[1] local tensor = torch.Tensor(s1,s2) for i = 1,s1 do assert(#tab[s1] == s2,"input tensor is expected to have the same number of elements in each row") for j = 1,s2 do tensor[i][j] = tab[i][j] end end return tensor end local function oneDtable2tensor(tab) local s1 = #tab local tensor = torch.Tensor(s1) for i = 1,s1 do tensor[i] = tab[i] end return tensor end local function isTable(elem) return type(elem) == "table" end if(isTable(tab[1])) then if(isTable(tab[1][1])) then if(isTable(tab[1][1][1])) then return fourDtable2tensor(tab) else return threeDtable2tensor(tab) end else return twoDtable2tensor(tab) end else return oneDtable2tensor(tab) end end function Util:mapLookup(ints,map) local out = {} for s in io.lines(ints:size(2)) do table.insert(out,s) end return map end --TODO: could this be improved by allocating ti11 on as a cuda tensor at the beginning? function Util:sparse2dense(tl,labelDim,useCuda,shift) --the second arg is for the common use case that we pass it zero-indexed values local ti11 local shift = shift or false if(useCuda) then ti11 = torch.CudaTensor(tl:size(1),tl:size(2),labelDim) else ti11 = torch.Tensor(tl:size(1),tl:size(2),labelDim) end ti11:zero() for i = 1,tl:size(1) do for j = 1,tl:size(2) do local v = tl[i][j] if(shift) then v = v+1 end ti11[i][j][v] = 1 end end return ti11 end --this is copied from http://ericjmritz.name/2014/02/26/lua-is_array/ function Util:isArray(t) local i = 0 for _ in pairs(t) do i = i + 1 if t[i] == nil then return false end end return true end <|start_filename|>release/songPathRnn/data/insertClassLabels.lua<|end_filename|> require 'torch' cmd = torch.CmdLine() cmd:option('-input','','input file') cmd:option('-classLabel',-1,'input file') local params = cmd:parse(arg) local input_file = params.input local classLabel = params.classLabel t = torch.load(input_file) --print("classLabel", classLabel) t['classId'] = classLabel --print(t) torch.save(input_file,t) --saving with the same name <|start_filename|>release/songPathRnn/model/batcher/TypeBatcher.lua<|end_filename|> --******************************************************************** --Source: https://github.com/rajarshd/ChainsofReasoning --See Chains of Reasoning over Entities, Relations, and Text using Recurrent Neural Networks --https://arxiv.org/abs/1607.01426 --********************************************************************** local TypeBatcher = torch.class('TypeBatcher') function TypeBatcher:__init(fileName, batchSize, shuffle, genNeg, vocabSize) print('Loading data from '..fileName) local loadedData = torch.load(fileName) self.entities = loadedData.entities self.types = loadedData.types self.batchSize = batchSize self.doShuffle = shuffle or false self.curStart = 1 self.dataSize = self.entities:size(1) self.genNeg = genNeg self.vocabSize = vocabSize self:shuffle() end function TypeBatcher:shuffle() if self.doShuffle then local inds = torch.randperm(self.types:size(1)):long() self.entities = self.entities:index(1,inds) self.types = self.types:index(1,inds) end end function TypeBatcher:genNegExamples(posEntities) if posEntities == nil then return nil end local negCount = posEntities:size(1) --number of positive examples local negBatch = torch.rand(negCount):mul(self.vocabSize):floor():add(1):view(posEntities:size()) return negBatch end function TypeBatcher:get_batch(batcher, vocabSize) local pos_entities, types = batcher:getBatch() if pos_entities == nil then return nil end local neg_entities = gen_neg(pos_entities, vocabSize) print(neg_entities:size()) return {pos_entities, types, neg_entities} end function TypeBatcher:getBatch() local startIndex = self.curStart if startIndex > self.dataSize then return nil end local endIndex = math.min(startIndex+self.batchSize-1, self.dataSize) local currBatchSize = endIndex - startIndex + 1 local batchEntities = self.entities:narrow(1, startIndex, currBatchSize) local batchTypes = self.types:narrow(1, startIndex, currBatchSize) local batchNegEntities = nil if self.genNeg then batchNegEntities = self:genNegExamples(batchEntities) end self.curStart = endIndex + 1 return {batchEntities, batchTypes, batchNegEntities} end function TypeBatcher:reset() self.curStart = 1 if self.doShuffle then self:shuffle() end end <|start_filename|>release/songPathRnn/model/batcher/Batcher.lua<|end_filename|> --******************************************************************** --Source: https://github.com/rajarshd/ChainsofReasoning --See Chains of Reasoning over Entities, Relations, and Text using Recurrent Neural Networks --https://arxiv.org/abs/1607.01426 --********************************************************************** --takes in a data file and implements logic for returning batches from it. local Batcher = torch.class('Batcher') function Batcher:__init(filePath, batchSize, shuffle) print(filePath) local loadedData = torch.load(filePath) print(loadedData) self.labels = loadedData.labels self.data = loadedData.data self.classId = loadedData.classId self.doShuffle = shuffle if (self.labels:dim() == 1) then -- print("in batch") -- print(self.labels) self.labelDimension = 1 -- self.labels = self.labels:mul(-1):add(2) -- print(self.labels) else self.labelDimension = self.labels:size(2) end self.numPaths = self.data:size(2) self.numTokensInPath = self.data:size(3) self.numFeatureTemplates = self.data:size(4) if self.doShuffle then self:shuffle() end --first shuffle self.batchSize = batchSize self.curStart = 1 end function Batcher:shuffle() if(self.doShuffle) then local inds = torch.randperm(self.labels:size(1)):long() self.labels = self.labels:index(1,inds) self.data = self.data:index(1,inds) end end function Batcher:getBatch() local dataSize = self.labels:size(1) local startIndex = self.curStart if startIndex > dataSize then return nil end local endIndex = math.min(startIndex+self.batchSize-1, dataSize) local currBatchSize = endIndex - startIndex + 1 local batchLabels = self.labels:narrow(1, startIndex, currBatchSize) local batchData = self.data:narrow(1, startIndex, currBatchSize) self.curStart = endIndex + 1 return batchLabels, batchData end function Batcher:reset() self.curStart = 1 if self.doShuffle then self:shuffle() end end --return all the dimensions except the first dimension of the data because they are fixed and will be used to preallocate tensors in gpu. function Batcher:getSizes() return self.labelDimension, self.numPaths, self.numTokensInPath, self.numFeatureTemplates end --return the classId associated with this batcher function Batcher:getClassId() return self.classId end <|start_filename|>release/songPathRnn/model/module/TopK.lua<|end_filename|> --******************************************************************** --Source: https://github.com/rajarshd/ChainsofReasoning --See Chains of Reasoning over Entities, Relations, and Text using Recurrent Neural Networks --https://arxiv.org/abs/1607.01426 --********************************************************************** -- -- This was implemented by Pat. -- Date: 2/17/16 -- local TopK, parent = torch.class('nn.TopK', 'nn.Max') function TopK:__init(K, dimension, nInputDims) parent.__init(self, dimension, nInputDims) self.K = K end function TopK:updateOutput(input) self:_lazyInit() local dimension = self:_getPositiveDimension(input) local k = math.min (self.K, input:size(dimension)) torch.topk(self._output, self._indices, input, k, dimension, true) self.output = self._output return self.output end function TopK:_lazyInit() -- parent:_lazyInit() self._output = self._output or self.output.new() self._indices = self._indices or (torch.type(self.output) == 'torch.CudaTensor' and torch.CudaTensor() or torch.LongTensor()) self.gradInput = self._output.new() end function TopK:updateGradInput(input, gradOutput) self:_lazyInit() local dimension = self:_getPositiveDimension(input) self.gradInput:resizeAs(input):zero():scatter(dimension, self._indices, gradOutput) return self.gradInput end <|start_filename|>release/songPathRnn/model/optimizer/MyOptimizer.lua<|end_filename|> --******************************************************************** --Source: https://github.com/rajarshd/ChainsofReasoning --See Chains of Reasoning over Entities, Relations, and Text using Recurrent Neural Networks --https://arxiv.org/abs/1607.01426 --********************************************************************** require 'FeatureEmbedding' require 'os' local MyOptimizer = torch.class('MyOptimizer') --NOTE: various bits of this code were inspired by fbnn Optim.lua 3/5/2015 function MyOptimizer:__init(model,modules_to_update,criterion, trainingOptions,optInfo,rnnType) assert(trainingOptions) assert(optInfo) self.structured = structured or false self.model = model self.origModel = model self.optState = optInfo.optState self.optConfig = optInfo.optConfig self.optimMethod = optInfo.optimMethod self.regularization = optInfo.regularization self.trainingOptions = trainingOptions self.totalError = torch.Tensor(1):zero() self.checkForConvergence = optInfo.converged ~= nil self.startIteration = optInfo.startIteration self.optInfo = optInfo self.minibatchsize = trainingOptions.minibatchsize self.rnnType = rnnType self.entityTypePadToken = optInfo.entityTypePadToken self.relationPadToken = optInfo.relationPadToken self.entityPadToken = optInfo.entityPadToken self.gradClipNorm = optInfo.gradClipNorm self.gradientStepCounter = optInfo.gradientStepCounter self.useGradClip = optInfo.useGradClip self.l2 = optInfo.l2 self.regularize = optInfo.regularize self.createExptDir = optInfo.createExptDir -- self.recurrence = optInfo.recurrence local parameters local gradParameters parameters, gradParameters = modules_to_update:getParameters() self.parameters = parameters self.gradParameters = gradParameters self.l2s = {} self.params = {} self.grads = {} for i = 1,#self.regularization.params do local params,grad = self.regularization.params[i]:parameters() local l2 = self.regularization.l2[i] table.insert(self.params,params) table.insert(self.grads,grad) table.insert(self.l2s,l2) end self.numRegularizers = #self.l2s self.cuda = optInfo.cuda if(optInfo.useCuda) then self.totalError:cuda() end self.criterion = criterion for hookIdx = 1,#self.trainingOptions.epochHooks do local hook = self.trainingOptions.epochHooks[hookIdx] if( hook.epochHookFreq == 1) then hook.hook(0) end end end function MyOptimizer:zeroPadTokens() local entityTypeLookUpTable = FeatureEmbedding:getEntityTypeLookUpTable() if entityTypeLookUpTable ~= nil then local params, gradParams = entityTypeLookUpTable:parameters() params[1][self.entityTypePadToken]:zero() end local relationLookUpTable = FeatureEmbedding:getRelationLookUpTable() if relationLookUpTable ~= nil then local params, gradParams = relationLookUpTable:parameters() params[1][self.relationPadToken]:zero() end local entityLookUpTable = FeatureEmbedding:getEntityLookUpTable() if entityLookUpTable ~= nil then local params, gradParams = entityLookUpTable:parameters() params[1][self.entityPadToken]:zero() end end function MyOptimizer:train(trainBatcher) self.model:training() -- turn on the training flag; especially imp when using dropout local prevTime = sys.clock() local numProcessed = 0 --count the total number of batches once. This is for displpaying the progress bar; helps to track time local totalBatches = 0 -- I computed this manually. This is for all the dataset combined print('Making a pass of the data to count the batches') while(true) do local minibatch_targets,minibatch_inputs,num, classId = trainBatcher:getBatch() if minibatch_targets == nil then break --end of a batch end totalBatches = totalBatches + 1 end print('Total num batches '..totalBatches) trainBatcher:reset() local i = self.startIteration while i <= self.trainingOptions.numEpochs and (not self.checkForConvergence or not self.optInfo.converged) do self.totalError:zero() num_data = 0 batch_counter = 0 local gradientStepCounter = 0 count = 0 while(true) do local minibatch_targets,minibatch_inputs,num, classId = trainBatcher:getBatch() if self.cuda then self.model = nn.Sequential():add(self.origModel):add(nn.Select(2,classId)):cuda() else -- print("opitimizer:",classId) self.model = nn.Sequential():add(self.origModel):add(nn.Select(2,classId)) end if minibatch_targets == nil then break --end of a batch end batch_counter = batch_counter + 1 if(minibatch_targets) then numProcessed = numProcessed + minibatch_targets:nElement() --this reports the number of 'training examples.' If doing sequence tagging, it's the number of total timesteps, not the number of sequences. else --in some cases, the targets are actually part of the inputs with some weird table structure. Need to account for this. numProcessed = numProcessed + self.minibatchsize end self:trainBatch(minibatch_inputs,minibatch_targets) gradientStepCounter = gradientStepCounter + 1 if(gradientStepCounter % self.gradientStepCounter == 0) then local avgError = self.totalError[1]/gradientStepCounter print(string.format('Printing after %d gradient steps\navg loss in epoch = %f\n',self.gradientStepCounter, avgError)) end count = count + 1 xlua.progress(count, totalBatches) end local avgError = self.totalError[1]/batch_counter local currTime = sys.clock() local ElapsedTime = currTime - prevTime local rate = numProcessed/ElapsedTime numProcessed = 0 prevTime = currTime print(string.format('\nIter: %d\navg loss in epoch = %f\ntotal elapsed = %f\ntime per batch = %f',i,avgError, ElapsedTime,ElapsedTime/batch_counter)) --print(string.format('cur learning rate = %f',self.optConfig.learningRate)) print(string.format('examples/sec = %f',rate)) if(not self.createExptDir) then print('WARNING! - createExptDir is NOT set!') end self:postEpoch() for hookIdx = 1,#self.trainingOptions.epochHooks do local hook = self.trainingOptions.epochHooks[hookIdx] if( i % hook.epochHookFreq == 0) then hook.hook(i) end end trainBatcher:reset() i = i + 1 end end function MyOptimizer:postEpoch() --this is to be overriden by children of MyOptimizer end -- function zeroPadTokenEmbeddings() function MyOptimizer:trainBatch(inputs, targets) assert(inputs) assert(targets) --print(targets) self:zeroPadTokens() local parameters = self.parameters local gradParameters = self.gradParameters local function fEval(x) if parameters ~= x then parameters:copy(x) end self.model:zeroGradParameters() -- print("before forward") -- print(inputs) local output = self.model:forward(inputs) -- print("after forward") local df_do = nil local err = nil err = self.criterion:forward(output, targets) df_do = self.criterion:backward(output, targets) self.model:backward(inputs, df_do) if self.regularize == 1 then if self.useGradClip then local norm = gradParameters:norm() if(norm > self.gradClipNorm) then gradParameters:mul(self.gradClipNorm/norm) end --Also do L2 after clipping gradParameters:add(self.l2, parameters) else -- for i = 1,self.numRegularizers do -- local l2 = self.l2s[i] -- for j = 1,#self.params[i] do -- self.grads[i][j]:add(l2,self.params[i][j]) -- end -- end -- gradParameters:clamp(-5,5) gradParameters:add(self.l2, parameters) end end self.totalError[1] = self.totalError[1] + err return err, gradParameters end self.optimMethod(fEval, parameters, self.optConfig, self.optState) self:zeroPadTokens() return err end <|start_filename|>release/songPathRnn/model/batcher/test/testBatcherFilelist.lua<|end_filename|> --******************************************************************** --Source: https://github.com/rajarshd/ChainsofReasoning --See Chains of Reasoning over Entities, Relations, and Text using Recurrent Neural Networks --https://arxiv.org/abs/1607.01426 --********************************************************************** --testcases for BatcherFileList package.path = package.path ..';../?.lua' require 'BatcherFileList' local fileList = '/iesl/local/rajarshi/data_full_max_length_8_small//combined_train_list/train.list' batchSize = 128 shuffle = true useCuda = true maxBatches = 250 local count = 0 local batcherFileList = BatcherFileList(fileList, batchSize, shuffle, maxBatches, useCuda) local test_counter = 0 -----see if getBatch() works-------------- local labels, data, size, classId = batcherFileList:getBatch() count = count + 1 print(labels:size()) print(data:size()) print(classId) assert(labels ~= nil and data ~= nil and classId ~= nil) print(string.format('test %d passed!',test_counter)) test_counter = test_counter + 1 -- ------call getBatch till it returns nil-------- while(true) do local labels, data = batcherFileList:getBatch() if labels == nil then break end -- print(labels:size()) -- print(data:size()) count = count + 1 -- print(count) end batcherFileList:reset() local count1 = 0 while(true) do local labels, data = batcherFileList:getBatch() if labels == nil then break end -- print(labels:size()) -- print(data:size()) count1 = count1 + 1 xlua.progress(count1, count) -- print(count1) end assert(count == count1) print(string.format('test %d passed!',test_counter)) test_counter = test_counter + 1 ----- Now set shuffle to false and check the sequence of classId's it should be the same shuffle = false batcherFileList = BatcherFileList(fileList, batchSize, shuffle, maxBatches, useCuda) local classIdTable1 = {} while(true) do local labels, data,size, classId = batcherFileList:getBatch() table.insert(classIdTable1, classId) if labels == nil then break end end batcherFileList:reset() local classIdTable2 = {} while(true) do local labels, data,size, classId = batcherFileList:getBatch() table.insert(classIdTable2, classId) if labels == nil then break end end --check if the sizes are same assert(#classIdTable1 == #classIdTable2) for i=1, #classIdTable1 do assert(classIdTable1[i] == classIdTable2[i]) end print(string.format('test %d passed!',test_counter)) test_counter = test_counter + 1 <|start_filename|>release/songPathRnn/model/optimizer/MyOptimizerMultiTask.lua<|end_filename|> --******************************************************************** --Source: https://github.com/rajarshd/ChainsofReasoning --See Chains of Reasoning over Entities, Relations, and Text using Recurrent Neural Networks --https://arxiv.org/abs/1607.01426 --********************************************************************** require 'FeatureEmbedding' require 'os' local MyOptimizerMultiTask = torch.class('MyOptimizerMultiTask') --NOTE: various bits of this code were inspired by fbnn Optim.lua 3/5/2015 function MyOptimizerMultiTask:__init(model, modules_to_update, typeNet, criterion, typeCriterion, trainingOptions, optInfo, rnnType, colEncoder, entityTypeLookupTable) assert(trainingOptions) assert(optInfo) self.structured = structured or false self.model = model self.typeNet = typeNet self.typeCriterion = typeCriterion self.origModel = model self.optState = optInfo.optState self.optConfig = optInfo.optConfig self.optimMethod = optInfo.optimMethod self.regularization = optInfo.regularization self.trainingOptions = trainingOptions self.totalError = torch.Tensor(1):zero() self.checkForConvergence = optInfo.converged ~= nil self.startIteration = optInfo.startIteration self.optInfo = optInfo self.minibatchsize = trainingOptions.minibatchsize self.rnnType = rnnType self.entityTypePadToken = optInfo.entityTypePadToken self.relationPadToken = optInfo.relationPadToken self.entityPadToken = optInfo.entityPadToken self.gradClipNorm = optInfo.gradClipNorm self.gradientStepCounter = optInfo.gradientStepCounter self.useGradClip = optInfo.useGradClip self.l2 = optInfo.l2 self.typeL2 = optInfo.typeL2 self.regularize = optInfo.regularize self.createExptDir = optInfo.createExptDir self.typeRegularize = optInfo.typeRegularize self.typeGradClip = optInfo.typeGradClip self.typeGradClipNorm = optInfo.typeGradClipNorm self.totalTypeError = torch.Tensor(1):zero() self.typeOptConfig = optInfo.typeOptConfig self.typeOptState = optInfo.typeOptState self.typeOptimMethod = optInfo.typeOptimMethod self.saveFileNameTypes = optInfo.saveFileNameTypes local parameters local gradParameters -- so to share params across the net you have to do make them a combined network -- https://groups.google.com/forum/#!topic/torch7/_AW4T98-t0s local combined_net = nn.Sequential():add(self.model):add(self.typeNet) parameters, gradParameters = combined_net:getParameters() self.parameters = parameters self.gradParameters = gradParameters self.cuda = optInfo.cuda if(optInfo.useCuda) then self.totalError:cuda() self.totalTypeError:cuda() end self.criterion = criterion for hookIdx = 1,#self.trainingOptions.epochHooks do local hook = self.trainingOptions.epochHooks[hookIdx] if( hook.epochHookFreq == 1) then hook.hook(0) end end end function MyOptimizerMultiTask:toCuda(x) return self.useCuda and x:cuda() or x:double() end function MyOptimizerMultiTask:zeroPadTokens() local entityTypeLookUpTable = FeatureEmbedding:getEntityTypeLookUpTable() if entityTypeLookUpTable ~= nil then local params, gradParams = entityTypeLookUpTable:parameters() params[1][self.entityTypePadToken]:zero() end local relationLookUpTable = FeatureEmbedding:getRelationLookUpTable() if relationLookUpTable ~= nil then local params, gradParams = relationLookUpTable:parameters() params[1][self.relationPadToken]:zero() end local entityLookUpTable = FeatureEmbedding:getEntityLookUpTable() if entityLookUpTable ~= nil then local params, gradParams = entityLookUpTable:parameters() params[1][self.entityPadToken]:zero() end end function MyOptimizerMultiTask:train(trainBatcher, typeBatcher) self.model:training() -- turn on the training flag; especially imp when using dropout self.typeNet:training() local prevTime = sys.clock() local numProcessed = 0 --count the total number of batches once. This is for displpaying the progress bar; helps to track time local totalBatches = 0 local totalTypeBatches = 0 print('Making a pass of the relations data to count the batches') while(true) do local minibatch_targets,minibatch_inputs,num, classId = trainBatcher:getBatch() if minibatch_targets == nil then break --end of a batch end totalBatches = totalBatches + 1 end print('Total num batches for relation extraction tasks'..totalBatches) print('Making a pass of the types data to count the batches') while(true) do local ret = typeBatcher:getBatch() if ret == nil then break end totalTypeBatches = totalTypeBatches + 1 end print('Total number of batches ') trainBatcher:reset() typeBatcher:reset() local p = 0 if totalBatches > totalTypeBatches then p = totalTypeBatches / totalBatches else p = totalBatches / totalTypeBatches end print('Total batches for relation prediction '..totalBatches) print('Total batches for type prediction '..totalTypeBatches) print('p = '..p) local numEpochsRelationPred = self.trainingOptions.numEpochs local numEpochsTypePred = self.trainingOptions.typeNumEpochs local numEpochs = math.min(numEpochsRelationPred, numEpochsTypePred) print('Number of iterations to train both '..numEpochs) local i = 1 while i <= numEpochs do local countBatches = 1 local countTypeBatches = 1 self.totalError:zero() self.totalTypeError:zero() while(true) do rand = torch.bernoulli(p) if rand == 1 then --do training for type prediction if countTypeBatches <= totalTypeBatches then -- print('countTypeBatches '..countTypeBatches) local ret = typeBatcher:getBatch() pos, types, neg = self:toCuda(ret[1]), self:toCuda(ret[2]), self:toCuda(ret[3]) local data = {pos, types, neg} local labels = self:toCuda(torch.ones(pos:size())) -- its a dummy label, since in BPR criterion there isnt any label local batch = {data = data,labels = labels} self:trainTypeBatch(batch) countTypeBatches = countTypeBatches + 1 -- xlua.progress(countTypeBatches, totalTypeBatches) else --type prediction training is over if countBatches <= totalBatches then --but relation prediction is still left p = 0 --make p =0, so it doesnt come here anymore else --both are over; time to break out of the loop break end end else -- do training for relation prediction if countBatches <= totalBatches then local minibatch_targets,minibatch_inputs,num, classId = trainBatcher:getBatch() self.model = nn.Sequential():add(self.origModel):add(nn.Select(2,classId)):cuda() if minibatch_targets == nil then break --end of a batch end if(minibatch_targets) then numProcessed = numProcessed + minibatch_targets:nElement() --this reports the number of 'training examples.' If doing sequence tagging, it's the number of total timesteps, not the number of sequences. else --in some cases, the targets are actually part of the inputs with some weird table structure. Need to account for this. numProcessed = numProcessed + self.minibatchsize end self:trainBatch(minibatch_inputs,minibatch_targets) countBatches = countBatches + 1 xlua.progress(countBatches, totalBatches) else if countTypeBatches <= totalTypeBatches then p = 1 else --both are over; time to break out of the loop break end end end end local avgError = self.totalError[1]/totalBatches local avgErrorTypes = self.totalTypeError[1]/totalTypeBatches local currTime = sys.clock() local ElapsedTime = currTime - prevTime prevTime = currTime print(string.format('\nIter: %d\navg loss in epoch = %f\navg loss in epoch (type_prediction) = %f\ntotal elapsed = %f\ntime per batch = %f',i,avgError, avgErrorTypes, ElapsedTime,ElapsedTime/totalBatches)) for hookIdx = 1,#self.trainingOptions.epochHooks do local hook = self.trainingOptions.epochHooks[hookIdx] if( i % hook.epochHookFreq == 0) then hook.hook(i) end end if(self.createExptDir) then if i%1 == 0 then local file = self.saveFileNameTypes..i print('Saving to '..file) torch.save(file,self.typeNet) end end trainBatcher:reset() typeBatcher:reset() i = i + 1 end if numEpochsTypePred > numEpochs then print('Now training only for type prediction') self:trainTypePrediction(typeBatcher, i) else print('Now training only for relation prediction') self:trainRelationPrediction(trainBatcher, i) end end function MyOptimizerMultiTask:trainTypePrediction(typeBatcher, startIter) self.typeNet:training() local prevTime = sys.clock() local numProcessed = 0 --count the total number of batches once. This is for displpaying the progress bar; helps to track time local totalBatches = 0 print('Making a pass of the data to count the batches') while(true) do local ret = typeBatcher:getBatch() if ret == nil then break end totalBatches = totalBatches + 1 end print('Total num batches '..totalBatches) local i = startIter while i <= self.trainingOptions.typeNumEpochs do typeBatcher:reset() self.totalTypeError:zero() local batch_counter = 0 while(true) do local ret = typeBatcher:getBatch() if ret == nil then break end pos, types, neg = self:toCuda(ret[1]), self:toCuda(ret[2]), self:toCuda(ret[3]) local data = {pos, types, neg} local labels = self:toCuda(torch.ones(pos:size())) -- its a dummy label, since in BPR criterion there isnt any label local batch = {data = data,labels = labels} self:trainTypeBatch(batch) batch_counter = batch_counter + 1 xlua.progress(batch_counter, totalBatches) end local avgError = self.totalTypeError[1]/batch_counter local currTime = sys.clock() local ElapsedTime = currTime - prevTime local rate = numProcessed/ElapsedTime numProcessed = 0 prevTime = currTime print(string.format('\nIter: %d\navg loss in epoch = %f\ntotal elapsed = %f\ntime per batch = %f',i,avgError, ElapsedTime,ElapsedTime/batch_counter)) print(string.format('examples/sec = %f',rate)) if (self.createExptDir) then if i%1 == 0 then local file = self.saveFileNameTypes..i print('Saving to '..file) torch.save(file,self.typeNet) end end i = i + 1 end end function MyOptimizerMultiTask:trainRelationPrediction(trainBatcher, startIter) self.model:training() -- turn on the training flag; especially imp when using dropout local prevTime = sys.clock() local numProcessed = 0 --count the total number of batches once. This is for displpaying the progress bar; helps to track time local totalBatches = 0 -- I computed this manually. This is for all the dataset combined print('Making a pass of the data to count the batches') while(true) do local minibatch_targets,minibatch_inputs,num, classId = trainBatcher:getBatch() if minibatch_targets == nil then break --end of a batch end totalBatches = totalBatches + 1 end print('Total num batches '..totalBatches) trainBatcher:reset() local i = startIter while i <= self.trainingOptions.numEpochs do self.totalError:zero() num_data = 0 batch_counter = 0 local gradientStepCounter = 0 count = 0 while(true) do local minibatch_targets,minibatch_inputs,num, classId = trainBatcher:getBatch() self.model = nn.Sequential():add(self.origModel):add(nn.Select(2,classId)):cuda() if minibatch_targets == nil then break --end of a batch end batch_counter = batch_counter + 1 if(minibatch_targets) then numProcessed = numProcessed + minibatch_targets:nElement() --this reports the number of 'training examples.' If doing sequence tagging, it's the number of total timesteps, not the number of sequences. else --in some cases, the targets are actually part of the inputs with some weird table structure. Need to account for this. numProcessed = numProcessed + self.minibatchsize end self:trainBatch(minibatch_inputs,minibatch_targets) gradientStepCounter = gradientStepCounter + 1 if(gradientStepCounter % self.gradientStepCounter == 0) then local avgError = self.totalError[1]/gradientStepCounter print(string.format('Printing after %d gradient steps\navg loss in epoch = %f\n',self.gradientStepCounter, avgError)) end count = count + 1 xlua.progress(count, totalBatches) end local avgError = self.totalError[1]/batch_counter local currTime = sys.clock() local ElapsedTime = currTime - prevTime local rate = numProcessed/ElapsedTime numProcessed = 0 prevTime = currTime print(string.format('\nIter: %d\navg loss in epoch = %f\ntotal elapsed = %f\ntime per batch = %f',i,avgError, ElapsedTime,ElapsedTime/batch_counter)) --print(string.format('cur learning rate = %f',self.optConfig.learningRate)) print(string.format('examples/sec = %f',rate)) if(not self.createExptDir) then print('WARNING! - createExptDir is NOT set!') end self:postEpoch() for hookIdx = 1,#self.trainingOptions.epochHooks do local hook = self.trainingOptions.epochHooks[hookIdx] if( i % hook.epochHookFreq == 0) then hook.hook(i) end end trainBatcher:reset() i = i + 1 end end function MyOptimizerMultiTask:trainBatch(inputs, targets) assert(inputs) assert(targets) --print(targets) self:zeroPadTokens() local parameters = self.parameters local gradParameters = self.gradParameters local function fEval(x) if parameters ~= x then parameters:copy(x) end self.model:zeroGradParameters() local output = self.model:forward(inputs) local df_do = nil local err = nil err = self.criterion:forward(output, targets) df_do = self.criterion:backward(output, targets) self.model:backward(inputs, df_do) if self.regularize == 1 then if self.useGradClip then local norm = gradParameters:norm() if(norm > self.gradClipNorm) then gradParameters:mul(self.gradClipNorm/norm) end --Also do L2 after clipping gradParameters:add(self.l2, parameters) else gradParameters:add(self.l2, parameters) end end self.totalError[1] = self.totalError[1] + err return err, gradParameters end self.optimMethod(fEval, parameters, self.optConfig, self.optState) self:zeroPadTokens() return err end function MyOptimizerMultiTask:trainTypeBatch(batch) -- body assert(batch) -- local parameters = self.typeParams -- local gradParameters = self.typeGradParams local parameters = self.parameters local gradParameters = self.gradParameters local function fEval(x) if parameters ~= x then parameters:copy(x) end self.typeNet:zeroGradParameters() local data = batch.data local labels = batch.labels local pred = self.typeNet:forward(data) local err = self.typeCriterion:forward(pred, labels) local df_do = self.typeCriterion:backward(pred, labels) self.typeNet:backward(data, df_do) if self.typeRegularize == 1 then if self.typeGradClip == 1 then local norm = gradParameters:norm() if norm > self.typeGradClipNorm then gradParameters:mul(self.typeGradClipNorm/norm) end --Also do L2 after clipping gradParameters:add(self.typeL2, parameters) else gradParameters:add(self.typeL2, parameters) end end self.totalTypeError[1] = self.totalTypeError[1] + err return err, gradParameters end self.typeOptimMethod(fEval, parameters, self.typeOptConfig, self.typeOptState) return err end <|start_filename|>release/songPathRnn/model/module/Sum_nc.lua<|end_filename|> --******************************************************************** --Source: https://github.com/rajarshd/ChainsofReasoning --See Chains of Reasoning over Entities, Relations, and Text using Recurrent Neural Networks --https://arxiv.org/abs/1607.01426 --********************************************************************** Sum_nc, _ = torch.class('nn.Sum_nc', 'nn.Sum') -- function Sum_nc:updateGradInput(input, gradOutput) -- local size = input:size() -- size[self.dimension] = 1 -- -- modified code: -- if gradOutput:isContiguous() then -- gradOutput = gradOutput:view(size) -- doesn't work with non-contiguous tensors -- else -- gradOutput = gradOutput:resize(size) -- slower because of memory reallocation and changes gradOutput -- -- gradOutput = gradOutput:clone():resize(size) -- doesn't change gradOutput; safer and even slower -- end -- -- -- self.gradInput:resizeAs(input) -- self.gradInput:copy(gradOutput:expandAs(input)) -- return self.gradInput -- end function Sum_nc:updateGradInput(input, gradOutput) local dimension = self:_getPositiveDimension(input) -- zero-strides dont work with MKL/BLAS, so -- dont set self.gradInput to zero-stride tensor. -- Instead, do a deepcopy local size = input:size() size[dimension] = 1 if gradOutput:isContiguous() then gradOutput = gradOutput:view(size) -- doesn't work with non-contiguous tensors else gradOutput = gradOutput:resize(size) -- slower because of memory reallocation and changes gradOutput -- gradOutput = gradOutput:clone():resize(size) -- doesn't change gradOutput; safer and even slower\ end self.gradInput:resizeAs(input) self.gradInput:copy(gradOutput:expandAs(input)) if self.sizeAverage then self.gradInput:div(input:size(dimension)) end return self.gradInput end <|start_filename|>release/songPathRnn/model/module/LogSumExp.lua<|end_filename|> --******************************************************************** --Source: https://github.com/rajarshd/ChainsofReasoning --See Chains of Reasoning over Entities, Relations, and Text using Recurrent Neural Networks --https://arxiv.org/abs/1607.01426 --********************************************************************** local LogSumExp, parent = torch.class('nn.LogSumExp', 'nn.Module') function LogSumExp:__init(dim) self.dim = dim end function LogSumExp:updateOutput(input) self.dim = self.dim or input:dim() --default is the last dim if self.maxes == nil then self.maxes = torch.max(input, self.dim) --max scores along the dim self.score_minus_max = torch.add(input, -1, self.maxes:expandAs(input)) self.exp_score_minus_max = torch.exp(self.score_minus_max) self.sum_exp_score_minus_max = torch.sum(self.exp_score_minus_max, self.dim) self.output = torch.log(self.sum_exp_score_minus_max) else torch.max(self.maxes,input, self.dim) self.score_minus_max:add(input, -1, self.maxes:expandAs(input)) self.exp_score_minus_max:exp(self.score_minus_max) self.sum_exp_score_minus_max:sum(self.exp_score_minus_max, self.dim) self.output:log(self.sum_exp_score_minus_max) end self.output:add(self.maxes) return self.output end function LogSumExp:updateGradInput(input, gradOutput) self.gradInput = input:clone() self.gradInput:cdiv(self.exp_score_minus_max, self.sum_exp_score_minus_max:expandAs(input)) self.gradInput:cmul(gradOutput:expandAs(input)) return self.gradInput end <|start_filename|>release/songPathRnn/model/module/MapReduce.lua<|end_filename|> --******************************************************************** --Source: https://github.com/rajarshd/ChainsofReasoning --See Chains of Reasoning over Entities, Relations, and Text using Recurrent Neural Networks --https://arxiv.org/abs/1607.01426 --********************************************************************** local MapReduce, parent = torch.class('nn.MapReduce', 'nn.Container') function MapReduce:__init(mapper,reducer) parent.__init(self) self.mapper = mapper self.reducer = reducer self.modules = {} table.insert(self.modules,mapper) table.insert(self.modules,reducer) end function MapReduce:updateOutput(input) --first, reshape the data by pulling the second dimension into the first -- print('inputs size') -- print (input:size()) self.inputSize = input:size() local numPerExample = self.inputSize[2] local minibatchSize = self.inputSize[1] self.sizes = self.sizes or torch.LongStorage(self.inputSize:size() -1) self.sizes[1] = minibatchSize*numPerExample for i = 2,self.sizes:size() do self.sizes[i] = self.inputSize[i+1] end self.reshapedInput = input:view(self.sizes) self.mapped = self.mapper:updateOutput(self.reshapedInput) self.sizes3 = self.mapped:size() self.sizes2 = self.sizes2 or torch.LongStorage(self.mapped:dim() + 1) self.sizes2[1] = minibatchSize self.sizes2[2] = numPerExample for i = 2,self.mapped:dim() do self.sizes2[i+1] = self.mapped:size(i) end -- print('size after reducing') -- print(self.sizes2) self.mappedAndReshaped = self.mapped:view(self.sizes2) self.output = self.reducer:updateOutput(self.mappedAndReshaped) return self.output end function MapReduce:backward(input,gradOutput) local function operator(module,input,gradOutput) return module:backward(input,gradOutput) end return self:genericBackward(operator,input,gradOutput) end function MapReduce:updateGradInput(input,gradOutput) local function operator(module,input,gradOutput) return module:updateGradInput(input,gradOutput) end return self:genericBackward(operator,input,gradOutput) end function MapReduce:accUpdateGradParameters(input,gradOutput,lr) local function operator(module,input,gradOutput) return module:accUpdateGradParameters(input,gradOutput,lr) end return self:genericBackward(operator,input,gradOutput) end function MapReduce:accGradParameters(input,gradOutput,lr) local function operator(module,input,gradOutput) return module:accGradParameters(input,gradOutput,lr) end return self:genericBackward(operator,input,gradOutput) end function MapReduce:genericBackward(operator,input, gradOutput) operator(self.reducer,self.mappedAndReshaped,gradOutput) local reducerGrad = self.reducer.gradInput local reshapedReducerGrad = reducerGrad:view(self.sizes3) operator(self.mapper,self.reshapedInput,reshapedReducerGrad) local mapperGrad = self.mapper.gradInput self.gradInput = (mapperGrad:dim() > 0) and mapperGrad:view(self.inputSize) or nil --some modules return nil from backwards, such as the lookup table return self.gradInput end <|start_filename|>release/songPathRnn/model/optimizer/OptimizerCallback.lua<|end_filename|> --******************************************************************** --Source: https://github.com/rajarshd/ChainsofReasoning --See Chains of Reasoning over Entities, Relations, and Text using Recurrent Neural Networks --https://arxiv.org/abs/1607.01426 --********************************************************************** local OptimizerCallback = torch.class('OptimizerCallback') --here, 'hook' is a function (i), where is is the epoch that the optimizer is currently at. --This is useful, for example, for saving models with different names depending on the epoch function OptimizerCallback:__init(epochHookFreq,hook,name) self.epochHookFreq = epochHookFreq self.hook = hook self.name = name end
plataKwon/KPRN
<|start_filename|>tests/integration/data/EnumGetValuesReturnType-7.json<|end_filename|> [ { "message": "Method MabeEnum\\PHPStan\\tests\\integration\\data\\EnumGetValuesReturnType\\MyEnum::staticGetValuesFail() should return array<int, null> but returns array<int, array|bool|float|int|string|null>.", "line": 60, "ignorable": true }, { "message": "Method MabeEnum\\PHPStan\\tests\\integration\\data\\EnumGetValuesReturnType\\MyInheritedEnum::inheritStaticGetValuesFail() should return array<int, null> but returns array<int, array|bool|float|int|string|null>.", "line": 83, "ignorable": true } ] <|start_filename|>tests/integration/data/EnumGetValuesReturnType-3.json<|end_filename|> [ { "message": "Method MabeEnum\\PHPStan\\tests\\integration\\data\\EnumGetValuesReturnType\\Example::staticMethodFail() should return array<int, null> but returns array<int, float|int|string>.", "line": 24, "ignorable": true }, { "message": "Method MabeEnum\\PHPStan\\tests\\integration\\data\\EnumGetValuesReturnType\\Example::objectMethodFail() should return array<int, null> but returns array<int, float|int|string>.", "line": 36, "ignorable": true }, { "message": "Method MabeEnum\\PHPStan\\tests\\integration\\data\\EnumGetValuesReturnType\\MyEnum::selfGetValuesFail() should return array<int, null> but returns array<int, int|string>.", "line": 54, "ignorable": true }, { "message": "Method MabeEnum\\PHPStan\\tests\\integration\\data\\EnumGetValuesReturnType\\MyInheritedEnum::inheritSelfGetValuesFail() should return array<int, null> but returns array<int, float|int|string>.", "line": 77, "ignorable": true } ]
marc-mabe/php-enum-phpstan
<|start_filename|>test/data/badly-formed.js<|end_filename|> ()*$UY)(CJKY)V!(&H%V)%^!)*&)!@($VH^&%!(YODFAOFAFAYFAUAF&&&*&*(&*FA*FA*FA*FE&*F&*&*F&T# <|start_filename|>lib/text.js<|end_filename|> // Generated by LiveScript 1.5.0 (function(){ var pad; pad = function(str, num){ var len, padAmount; len = str.length; padAmount = num - len; return str + "" + repeatString$(' ', padAmount > 0 ? padAmount : 0); }; module.exports = { pad: pad }; function repeatString$(str, n){ for (var r = ''; n > 0; (n >>= 1) && (str += str)) if (n & 1) r += str; return r; } }).call(this); <|start_filename|>test/data/b.js<|end_filename|> debugger; function foobar(o) { while (o) { return zz + zz; } } <|start_filename|>test/data/dir/c.js<|end_filename|> var moooo = 23; var x = z - moo; 23 - 29; <|start_filename|>test/data/a.js<|end_filename|> function square(x) { return x * x; } var y = function(z) { f.p(z); z++; var obj = { a: 1, b: 2, c: 3 }; } <|start_filename|>lib/help.js<|end_filename|> // Generated by LiveScript 1.5.0 (function(){ var ref$, map, flatten, join, lines, unlines, chars, unchars, syntax, syntaxFlat, aliasMap, attrMapInverse, matchesMap, matchesAliasMap, pad, options, generateSyntaxHelp, generateSyntaxHelpForNode, generateCategoryHelp, generateHelpForCategory; ref$ = require('prelude-ls'), map = ref$.map, flatten = ref$.flatten, join = ref$.join, lines = ref$.lines, unlines = ref$.unlines, chars = ref$.chars, unchars = ref$.unchars; ref$ = require('grasp-syntax-javascript'), syntax = ref$.syntax, syntaxFlat = ref$.syntaxFlat, aliasMap = ref$.aliasMap, attrMapInverse = ref$.attrMapInverse, matchesMap = ref$.matchesMap, matchesAliasMap = ref$.matchesAliasMap; pad = require('./text').pad; options = require('./options').options; generateSyntaxHelp = function(){ var maxNameLen, syntaxInfo, res$, category, ref$, nodesInCat, lresult$, nodeName, ref1$, alias, nodes, ref2$, nodeArrays, primitives, getFieldStrings, fieldStrings, nameString, nameStringLen, syntaxInfoStrings, i$, len$, nodesInfo, nodeStrings, prepend, append; maxNameLen = 0; res$ = []; for (category in ref$ = syntax) { nodesInCat = ref$[category]; lresult$ = []; for (nodeName in nodesInCat) { ref1$ = nodesInCat[nodeName], alias = ref1$.alias, nodes = (ref2$ = ref1$.nodes) != null ? ref2$ : [], nodeArrays = (ref2$ = ref1$.nodeArrays) != null ? ref2$ : [], primitives = (ref2$ = ref1$.primitives) != null ? ref2$ : []; getFieldStrings = fn$; fieldStrings = getFieldStrings('', nodes).concat(getFieldStrings('%', nodeArrays), getFieldStrings('&', primitives)); nameString = alias + " (" + nodeName + ")"; nameStringLen = nameString.length; if (nameStringLen > maxNameLen) { maxNameLen = nameStringLen; } lresult$.push([nameString, fieldStrings.join(', ')]); } res$.push(lresult$); } syntaxInfo = res$; res$ = []; for (i$ = 0, len$ = syntaxInfo.length; i$ < len$; ++i$) { nodesInfo = syntaxInfo[i$]; nodeStrings = map(fn1$, nodesInfo); res$.push("\n" + unlines(nodeStrings)); } syntaxInfoStrings = res$; prepend = 'JavaScript abstract syntax help:\na list of possible node types, and their fields\n`--help node-name` for more information about a node\n`--help categories` for information about categories of nodes\n\nnode-name (FullOfficialName) field1, field2 (alias), field3...\nfield - this field contains another node\n%field - this field contains an array of other nodes\n&field - this field contains a primitive value, such as a boolean or a string\n-----------------------------'; append = 'Based on the Mozilla Parser API <https://developer.mozilla.org/docs/SpiderMonkey/Parser_API>'; return prepend + "" + unlines(syntaxInfoStrings) + "\n\n" + append; function fn$(type, fields){ return map(function(it){ var that; if (that = attrMapInverse[it]) { return type + "" + it + " (" + type + that.join(", " + type) + ")"; } else { return type + "" + it; } }, fields); } function fn1$(it){ return pad(it[0], maxNameLen) + " " + it[1]; } }; generateSyntaxHelpForNode = function(nodeName){ var ref$, alias, nodes, nodeArrays, primitives, syntax, example, note, nameStr, strs, res$, i$, len$, ref1$, type, fields, syntaxStr, exampleStr, examples, ex, line, noteStr; ref$ = syntaxFlat[nodeName], alias = ref$.alias, nodes = ref$.nodes, nodeArrays = ref$.nodeArrays, primitives = ref$.primitives, syntax = ref$.syntax, example = ref$.example, note = ref$.note; nameStr = alias + " (" + nodeName + ")"; res$ = []; for (i$ = 0, len$ = (ref$ = [['node', nodes], ['node array', nodeArrays], ['primitive', primitives]]).length; i$ < len$; ++i$) { ref1$ = ref$[i$], type = ref1$[0], fields = ref1$[1]; if (fields) { res$.push("\n" + type + " fields: " + map(fn$, fields).join(', ')); } } strs = res$; syntaxStr = syntax ? "\nsyntax:\n" + unlines(map(function(it){ return " " + it; }, lines(syntax))) : ''; exampleStr = example ? (examples = (function(){ var i$, ref$, len$, results$ = []; for (i$ = 0, len$ = (ref$ = [].concat(example)).length; i$ < len$; ++i$) { ex = ref$[i$]; results$.push(unlines((fn$()))); } return results$; function fn$(){ var i$, ref$, len$, results$ = []; for (i$ = 0, len$ = (ref$ = lines(ex)).length; i$ < len$; ++i$) { line = ref$[i$]; results$.push(" " + line); } return results$; } }()), "\nexample" + (examples.length > 1 ? 's' : '') + ":\n" + unlines(examples)) : ''; noteStr = note ? "\nnote: " + note : ''; return nameStr + "\n" + repeatString$('=', nameStr.length) + unchars(strs) + syntaxStr + exampleStr + noteStr; function fn$(it){ var that; if (that = attrMapInverse[it]) { return it + " (alias: " + that.join(', ') + ")"; } else { return it; } } }; generateCategoryHelp = function(){ var categories, res$, alias, ref$, category, fullNodeNames, names, prepend, append; res$ = []; for (alias in ref$ = matchesAliasMap) { category = ref$[alias]; fullNodeNames = matchesMap[category]; names = map(fn$, fullNodeNames); res$.push(alias + " (" + category + "): " + names.join(', ')); } categories = res$; prepend = 'Categories of node types:'; append = '`--help syntax` for node information.\n`--help category-name` for further information about a category.'; return prepend + "\n\n" + unlines(categories) + "\n\n" + append; function fn$(it){ return syntaxFlat[it].alias; } }; generateHelpForCategory = function(name){ var invertedAliases, res$, key, ref$, value, alias, fullNodeNames, names, nameStr; res$ = {}; for (key in ref$ = matchesAliasMap) { value = ref$[key]; res$[value] = key; } invertedAliases = res$; alias = invertedAliases[name]; fullNodeNames = matchesMap[name]; names = map(function(it){ return syntaxFlat[it].alias + " (" + it + ")"; }, fullNodeNames); nameStr = alias + " (" + name + ")"; return "A node type category.\n\n" + nameStr + "\n" + repeatString$('=', nameStr.length) + "\n" + unlines(names); }; module.exports = function(generateHelp, generateHelpForOption, positional, interpolate){ var helpStrings, res$, i$, len$, arg, lresult$, that, dashes, optionName, j$, ref$, len1$, o, item, sep, name; if (positional.length) { res$ = []; for (i$ = 0, len$ = positional.length; i$ < len$; ++i$) { arg = positional[i$]; lresult$ = []; if (arg === 'advanced') { lresult$.push(generateHelp({ showHidden: true, interpolate: interpolate })); } else if (that = /^(--?)(\S+)/.exec(arg)) { dashes = that[1], optionName = that[2]; if (dashes.length === 2) { lresult$.push(generateHelpForOption(optionName)); } else { for (j$ = 0, len1$ = (ref$ = chars(optionName)).length; j$ < len1$; ++j$) { o = ref$[j$]; lresult$.push(generateHelpForOption(o)); } } } else if (arg === 'more') { lresult$.push(generateHelpForOption('help')); } else if (arg === 'verbose') { for (j$ = 0, len1$ = (ref$ = options).length; j$ < len1$; ++j$) { item = ref$[j$]; if (that = item.heading) { sep = repeatString$('#', that.length + 4); lresult$.push(sep + "\n# " + that + " #\n" + sep); } else { lresult$.push(generateHelpForOption(item.option)); } } } else if (arg === 'syntax') { lresult$.push(generateSyntaxHelp()); } else if (arg === 'categories') { lresult$.push(generateCategoryHelp()); } else { if (aliasMap[arg] || syntaxFlat[arg]) { name = aliasMap[arg] || arg; lresult$.push(generateSyntaxHelpForNode(name)); } else if (matchesMap[arg] || matchesAliasMap[arg]) { name = matchesAliasMap[arg] || arg; lresult$.push(generateHelpForCategory(name)); } else { lresult$.push("No such help option: " + arg + "."); } } res$.push(lresult$); } helpStrings = res$; return join('\n\n')( flatten( helpStrings)); } else { return generateHelp({ interpolate: interpolate }); } }; function repeatString$(str, n){ for (var r = ''; n > 0; (n >>= 1) && (str += str)) if (n & 1) r += str; return r; } }).call(this);
GerHobbelt/grasp
<|start_filename|>averpil_com.html<|end_filename|> <body> <br><br><br><br> <center> <a href="http://susanna.averpil.com"><NAME></a><br> – Interaction Designer, Valtech, Stockholm <br><br> <a href="https://fredrikaverpil.github.io"><NAME></a><br> – Embedded Software Integration Engineer, Volvo Group, Göteborg </center> </body>
fredrikaverpil/fredrikaverpil.github.io
<|start_filename|>lib/helpers/chunk-string.coffee<|end_filename|> module.exports = chunkString = (str, len) -> _size = Math.ceil(str.length / len) _ret = new Array(_size) _offset = undefined _i = 0 while _i < _size _offset = _i * len _ret[_i] = str.substring(_offset, _offset + len) _i++ _ret <|start_filename|>lib/helpers/colour-list.coffee<|end_filename|> module.exports = [ "red" "blue" "pink" "yellow" "orange" "purple" "green" "brown" "skyblue" "olive" "salmon" "white" "lime" "maroon" "beige" "darkgoldenrod" "blanchedalmond" "tan" "violet" "navy" "gold" "black" ]
mingsai/atom-supercopair
<|start_filename|>codehandler/Makefile<|end_filename|> PATH := $(DEVKITPPC)/bin:$(PATH) PREFIX ?= powerpc-eabi- LD := $(PREFIX)ld AS := $(PREFIX)as CC := $(PREFIX)gcc OBJDUMP ?= $(PREFIX)objdump OBJCOPY ?= $(PREFIX)objcopy SFLAGS := -mgekko -mregnames # -O2: optimise lots # -Wall: generate lots of warnings # -x c: compile as C code # -std=gnu99: use the C99 standard with GNU extensions # -ffreestanding: we don't have libc; don't expect we do # -mrvl: enable wii/gamecube compilation # -mcpu=750: enable processor specific compilation # -meabi: enable eabi specific compilation # -mhard-float: enable hardware floating point instructions # -fshort-wchar: use 16 bit whcar_t type in keeping with Wii executables # -msdata-none: do not use r2 or r13 as small data areas # -memb: enable embedded application specific compilation # -ffunction-sections: split up functions so linker can garbage collect # -fdata-sections: split up data so linker can garbage collect CFLAGS := -O2 -Wall -x c -std=gnu99 \ -ffreestanding \ -mrvl -mcpu=750 -meabi -mhard-float -fshort-wchar \ -msdata=none -memb -ffunction-sections -fdata-sections \ -Wno-unknown-pragmas -Wno-strict-aliasing SRC := $(wildcard *.S) $(wildcard *.c) OBJ := $(patsubst %.S,build/%.o,$(patsubst %.c,build/%.o,$(SRC))) # Simulate an order only dependency BUILD_REQ := $(filter-out $(wildcard build),build) BIN_REQ := $(filter-out $(wildcard bin),bin) all: bin/codehandler310.h bin/codehandler400.h bin/codehandler410.h bin/codehandler500.h bin/codehandler532.h bin/codehandler550.h bin/codehandler%.h: build/codehandler%.text.bin $(BIN_REQ) xxd -i $< | sed "s/unsigned/static const unsigned/g;s/ler$*/ler/g;s/build_//g" > $@ build/codehandler%.text.bin: build/codehandler%.elf $(BUILD_REQ) $(OBJCOPY) -j .text -O binary $< $@ build/codehandler%.elf: codehandler%.ld $(OBJ) $(BUILD_REQ) $(LD) -T $< $(OBJ) build/%.o: %.c $(BUILD_REQ) $(CC) -c $(CFLAGS) -o $@ $< build/%.o: %.S $(BUILD_REQ) $(AS) $(SFLAGS) -o $@ $< bin: mkdir $@ build: mkdir $@ clean: rm -rf $(wildcard build) $(wildcard bin) <|start_filename|>installer/src/codehandler400.h<|end_filename|> static const unsigned char codehandler_text_bin[] = { 0x94, 0x21, 0xff, 0xe8, 0x7c, 0x08, 0x02, 0xa6, 0x3d, 0x20, 0x10, 0x05, 0x81, 0x29, 0x9c, 0x1c, 0x93, 0x81, 0x00, 0x08, 0x7c, 0x7c, 0x1b, 0x78, 0x38, 0x60, 0x00, 0x00, 0x93, 0xa1, 0x00, 0x0c, 0x93, 0xe1, 0x00, 0x14, 0x7c, 0x9d, 0x23, 0x78, 0x90, 0x01, 0x00, 0x1c, 0x60, 0x63, 0x86, 0xa8, 0x93, 0xc1, 0x00, 0x10, 0x38, 0x80, 0x00, 0x40, 0x7d, 0x29, 0x03, 0xa6, 0x4e, 0x80, 0x04, 0x21, 0x7c, 0x7f, 0x1b, 0x79, 0x41, 0x82, 0x00, 0x50, 0x38, 0xa0, 0x00, 0x00, 0x38, 0x80, 0x00, 0x00, 0x60, 0xa5, 0x86, 0xa8, 0x3b, 0xdf, 0x00, 0x08, 0x4b, 0xe5, 0x3e, 0x2d, 0x3c, 0xff, 0x00, 0x01, 0x3c, 0x80, 0x01, 0x1e, 0x39, 0x00, 0x00, 0x00, 0x7f, 0xc3, 0xf3, 0x78, 0x38, 0x84, 0xdb, 0x28, 0x38, 0xa0, 0x00, 0x00, 0x7f, 0xe6, 0xfb, 0x78, 0x38, 0xe7, 0x86, 0xa8, 0x61, 0x08, 0x80, 0x00, 0x39, 0x20, 0x00, 0x00, 0x39, 0x40, 0x00, 0x0c, 0x4b, 0xe5, 0xe5, 0x49, 0x7f, 0xc3, 0xf3, 0x78, 0x4b, 0xe5, 0xea, 0x25, 0x3d, 0x20, 0x10, 0x06, 0x80, 0x01, 0x00, 0x1c, 0x81, 0x29, 0xa6, 0x00, 0x7f, 0x83, 0xe3, 0x78, 0x83, 0xc1, 0x00, 0x10, 0x7f, 0xa4, 0xeb, 0x78, 0x83, 0x81, 0x00, 0x08, 0x7d, 0x29, 0x03, 0xa6, 0x83, 0xa1, 0x00, 0x0c, 0x83, 0xe1, 0x00, 0x14, 0x7c, 0x08, 0x03, 0xa6, 0x38, 0x21, 0x00, 0x18, 0x4e, 0x80, 0x04, 0x20, 0x94, 0x21, 0xff, 0xe8, 0x7c, 0x08, 0x02, 0xa6, 0x38, 0xa0, 0x00, 0x01, 0x38, 0xc0, 0x00, 0x20, 0x38, 0x81, 0x00, 0x08, 0x90, 0x01, 0x00, 0x1c, 0x4b, 0xed, 0x7b, 0xe1, 0x2c, 0x03, 0x00, 0x00, 0x41, 0x80, 0x00, 0x0c, 0x41, 0x82, 0x00, 0x18, 0x88, 0x61, 0x00, 0x08, 0x80, 0x01, 0x00, 0x1c, 0x38, 0x21, 0x00, 0x18, 0x7c, 0x08, 0x03, 0xa6, 0x4e, 0x80, 0x00, 0x20, 0x38, 0x60, 0xff, 0xff, 0x4b, 0xff, 0xff, 0xec, 0x94, 0x21, 0xff, 0xe0, 0x7c, 0x08, 0x02, 0xa6, 0x93, 0xe1, 0x00, 0x1c, 0x7c, 0xff, 0x3b, 0x79, 0x93, 0x61, 0x00, 0x0c, 0x7c, 0x9b, 0x23, 0x78, 0x93, 0x81, 0x00, 0x10, 0x7c, 0x7c, 0x1b, 0x78, 0x93, 0xa1, 0x00, 0x14, 0x7c, 0xbd, 0x2b, 0x78, 0x93, 0xc1, 0x00, 0x18, 0x7c, 0xde, 0x33, 0x78, 0x90, 0x01, 0x00, 0x24, 0x41, 0xa1, 0x00, 0x0c, 0x48, 0x00, 0x00, 0x64, 0x40, 0x9d, 0x00, 0x60, 0x7f, 0xc4, 0xf3, 0x78, 0x7f, 0xe5, 0xfb, 0x78, 0x7f, 0xa3, 0xeb, 0x78, 0x38, 0xc0, 0x00, 0x00, 0x4b, 0xed, 0x7b, 0x65, 0x7c, 0x69, 0x1b, 0x79, 0x7f, 0xe9, 0xf8, 0x50, 0x7f, 0xde, 0x4a, 0x14, 0x2f, 0x9f, 0x00, 0x00, 0x40, 0x80, 0xff, 0xd8, 0x80, 0x01, 0x00, 0x24, 0x39, 0x40, 0x01, 0x5c, 0x91, 0x5b, 0x00, 0x00, 0x7d, 0x23, 0x4b, 0x78, 0x7c, 0x08, 0x03, 0xa6, 0x91, 0x3c, 0x00, 0x00, 0x83, 0x61, 0x00, 0x0c, 0x83, 0x81, 0x00, 0x10, 0x83, 0xa1, 0x00, 0x14, 0x83, 0xc1, 0x00, 0x18, 0x83, 0xe1, 0x00, 0x1c, 0x38, 0x21, 0x00, 0x20, 0x4e, 0x80, 0x00, 0x20, 0x80, 0x01, 0x00, 0x24, 0x38, 0x60, 0x00, 0x00, 0x83, 0x61, 0x00, 0x0c, 0x7c, 0x08, 0x03, 0xa6, 0x83, 0x81, 0x00, 0x10, 0x83, 0xa1, 0x00, 0x14, 0x83, 0xc1, 0x00, 0x18, 0x83, 0xe1, 0x00, 0x1c, 0x38, 0x21, 0x00, 0x20, 0x4e, 0x80, 0x00, 0x20, 0x94, 0x21, 0xff, 0xe0, 0x7c, 0x08, 0x02, 0xa6, 0x93, 0xe1, 0x00, 0x1c, 0x7c, 0xff, 0x3b, 0x79, 0x93, 0x61, 0x00, 0x0c, 0x7c, 0x9b, 0x23, 0x78, 0x93, 0x81, 0x00, 0x10, 0x7c, 0x7c, 0x1b, 0x78, 0x93, 0xa1, 0x00, 0x14, 0x7c, 0xbd, 0x2b, 0x78, 0x93, 0xc1, 0x00, 0x18, 0x7c, 0xde, 0x33, 0x78, 0x90, 0x01, 0x00, 0x24, 0x41, 0xa1, 0x00, 0x0c, 0x48, 0x00, 0x00, 0x64, 0x40, 0x9d, 0x00, 0x60, 0x7f, 0xc4, 0xf3, 0x78, 0x7f, 0xe5, 0xfb, 0x78, 0x7f, 0xa3, 0xeb, 0x78, 0x38, 0xc0, 0x00, 0x00, 0x4b, 0xed, 0x83, 0x09, 0x7c, 0x69, 0x1b, 0x79, 0x7f, 0xe9, 0xf8, 0x50, 0x7f, 0xde, 0x4a, 0x14, 0x2f, 0x9f, 0x00, 0x00, 0x40, 0x80, 0xff, 0xd8, 0x80, 0x01, 0x00, 0x24, 0x39, 0x40, 0x01, 0x7d, 0x91, 0x5b, 0x00, 0x00, 0x7d, 0x23, 0x4b, 0x78, 0x7c, 0x08, 0x03, 0xa6, 0x91, 0x3c, 0x00, 0x00, 0x83, 0x61, 0x00, 0x0c, 0x83, 0x81, 0x00, 0x10, 0x83, 0xa1, 0x00, 0x14, 0x83, 0xc1, 0x00, 0x18, 0x83, 0xe1, 0x00, 0x1c, 0x38, 0x21, 0x00, 0x20, 0x4e, 0x80, 0x00, 0x20, 0x80, 0x01, 0x00, 0x24, 0x38, 0x60, 0x00, 0x00, 0x83, 0x61, 0x00, 0x0c, 0x7c, 0x08, 0x03, 0xa6, 0x83, 0x81, 0x00, 0x10, 0x83, 0xa1, 0x00, 0x14, 0x83, 0xc1, 0x00, 0x18, 0x83, 0xe1, 0x00, 0x1c, 0x38, 0x21, 0x00, 0x20, 0x4e, 0x80, 0x00, 0x20, 0x7c, 0x08, 0x02, 0xa6, 0x94, 0x21, 0xfb, 0x90, 0x92, 0xe1, 0x04, 0x4c, 0x3e, 0xe0, 0x00, 0x00, 0x90, 0x01, 0x04, 0x74, 0x3a, 0xf7, 0x01, 0x90, 0x92, 0x41, 0x04, 0x38, 0x92, 0x61, 0x04, 0x3c, 0x92, 0x81, 0x04, 0x40, 0x93, 0x61, 0x04, 0x5c, 0x93, 0xc1, 0x04, 0x68, 0x93, 0xe1, 0x04, 0x6c, 0x92, 0xa1, 0x04, 0x44, 0x3a, 0xa0, 0xff, 0xaa, 0x92, 0xc1, 0x04, 0x48, 0x3a, 0xc0, 0xff, 0x82, 0x93, 0x01, 0x04, 0x50, 0x3f, 0x00, 0x40, 0x00, 0x93, 0x21, 0x04, 0x54, 0x3b, 0x21, 0x00, 0x28, 0x93, 0x41, 0x04, 0x58, 0x3b, 0x43, 0x00, 0x04, 0x93, 0x81, 0x04, 0x60, 0x7c, 0x7c, 0x1b, 0x78, 0x93, 0xa1, 0x04, 0x64, 0x7c, 0x9d, 0x23, 0x78, 0x7f, 0xa3, 0xeb, 0x78, 0x4b, 0xff, 0xfd, 0xc9, 0x7c, 0x7f, 0x1b, 0x79, 0x41, 0x80, 0x02, 0x68, 0x2f, 0x9f, 0x00, 0x41, 0x41, 0x9e, 0x06, 0x88, 0x40, 0x9d, 0x00, 0x58, 0x2f, 0x9f, 0x00, 0x72, 0x41, 0x9e, 0x05, 0xbc, 0x41, 0x9d, 0x01, 0x78, 0x2f, 0x9f, 0x00, 0x70, 0x41, 0x9e, 0x02, 0xfc, 0x41, 0x9d, 0x04, 0xe8, 0x2f, 0x9f, 0x00, 0x50, 0x40, 0xbe, 0xff, 0xc8, 0x39, 0x20, 0x00, 0x01, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x38, 0xc1, 0x04, 0x2c, 0x38, 0xe0, 0x00, 0x01, 0x99, 0x21, 0x04, 0x2c, 0x4b, 0xff, 0xfe, 0x7d, 0x7c, 0x7f, 0x1b, 0x79, 0x40, 0x80, 0xff, 0xa0, 0x39, 0x20, 0x00, 0xd1, 0x91, 0x3c, 0x00, 0x04, 0x48, 0x00, 0x02, 0x20, 0x2f, 0x9f, 0x00, 0x03, 0x41, 0x9e, 0x05, 0xec, 0x40, 0x9d, 0x02, 0x64, 0x2f, 0x9f, 0x00, 0x0b, 0x41, 0x9e, 0x03, 0x58, 0x2f, 0x9f, 0x00, 0x0c, 0x41, 0x9e, 0x03, 0xdc, 0x2f, 0x9f, 0x00, 0x04, 0x40, 0x9e, 0xff, 0x70, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78, 0x38, 0xe0, 0x00, 0x08, 0x4b, 0xff, 0xfd, 0x69, 0x7c, 0x7f, 0x1b, 0x79, 0x41, 0x80, 0x07, 0x64, 0x83, 0xc1, 0x00, 0x28, 0x3a, 0x40, 0xff, 0xb0, 0x82, 0x81, 0x00, 0x2c, 0x3a, 0x60, 0xff, 0xbd, 0x7f, 0x9e, 0xa0, 0x40, 0x41, 0xbe, 0xff, 0x38, 0x7f, 0x7e, 0xa0, 0x50, 0x2f, 0x9b, 0x04, 0x00, 0x40, 0x9d, 0x00, 0x7c, 0x3b, 0x60, 0x04, 0x00, 0x89, 0x3e, 0x00, 0x00, 0x2f, 0x89, 0x00, 0x00, 0x40, 0x9e, 0x00, 0x78, 0x7f, 0x69, 0x03, 0xa6, 0x48, 0x00, 0x00, 0x10, 0x7d, 0x5e, 0x48, 0xae, 0x2f, 0x8a, 0x00, 0x00, 0x40, 0x9e, 0x00, 0x64, 0x39, 0x29, 0x00, 0x01, 0x42, 0x00, 0xff, 0xf0, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x38, 0xc1, 0x04, 0x2c, 0x38, 0xe0, 0x00, 0x01, 0x9a, 0x41, 0x04, 0x2c, 0x4b, 0xff, 0xfd, 0xb9, 0x7c, 0x7f, 0x1b, 0x79, 0x41, 0x80, 0x06, 0xfc, 0x7f, 0xa3, 0xeb, 0x78, 0x4b, 0xff, 0xfc, 0xa1, 0x2f, 0x83, 0x00, 0xcc, 0x41, 0xbe, 0xfe, 0xcc, 0x7f, 0xde, 0xda, 0x14, 0x7f, 0x94, 0xf0, 0x40, 0x41, 0xbe, 0xfe, 0xc0, 0x7f, 0x7e, 0xa0, 0x50, 0x2f, 0x9b, 0x04, 0x00, 0x41, 0xbd, 0xff, 0x8c, 0x2f, 0x9b, 0x00, 0x00, 0x41, 0x9d, 0xff, 0x88, 0x41, 0xbe, 0xff, 0xac, 0x7f, 0xc4, 0xf3, 0x78, 0x7f, 0x65, 0xdb, 0x78, 0x38, 0x61, 0x00, 0x29, 0x4b, 0xe5, 0x3a, 0x35, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78, 0x38, 0xfb, 0x00, 0x01, 0x9a, 0x61, 0x00, 0x28, 0x4b, 0xff, 0xfd, 0x51, 0x7c, 0x7f, 0x1b, 0x79, 0x40, 0x80, 0xff, 0x9c, 0x39, 0x20, 0x00, 0x8f, 0x91, 0x3c, 0x00, 0x04, 0x48, 0x00, 0x00, 0xf4, 0x2f, 0x9f, 0x00, 0x99, 0x41, 0x9e, 0x02, 0x08, 0x2f, 0x9f, 0x00, 0x9a, 0x41, 0x9e, 0x02, 0x8c, 0x2f, 0x9f, 0x00, 0x80, 0x40, 0x9e, 0xfe, 0x50, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78, 0x38, 0xe0, 0x00, 0x44, 0x4b, 0xff, 0xfc, 0x49, 0x7c, 0x7f, 0x1b, 0x79, 0x41, 0x80, 0x06, 0x38, 0x80, 0x81, 0x00, 0x4c, 0x81, 0x61, 0x00, 0x28, 0x90, 0x81, 0x00, 0x08, 0x80, 0x81, 0x00, 0x50, 0x7d, 0x69, 0x03, 0xa6, 0x80, 0xa1, 0x00, 0x34, 0x90, 0x81, 0x00, 0x0c, 0x80, 0x81, 0x00, 0x54, 0x80, 0xc1, 0x00, 0x38, 0x90, 0x81, 0x00, 0x10, 0x80, 0x81, 0x00, 0x58, 0x80, 0xe1, 0x00, 0x3c, 0x90, 0x81, 0x00, 0x14, 0x80, 0x81, 0x00, 0x5c, 0x81, 0x01, 0x00, 0x40, 0x90, 0x81, 0x00, 0x18, 0x80, 0x81, 0x00, 0x60, 0x81, 0x21, 0x00, 0x44, 0x90, 0x81, 0x00, 0x1c, 0x80, 0x81, 0x00, 0x64, 0x81, 0x41, 0x00, 0x48, 0x90, 0x81, 0x00, 0x20, 0x80, 0x81, 0x00, 0x68, 0x80, 0x61, 0x00, 0x2c, 0x90, 0x81, 0x00, 0x24, 0x80, 0x81, 0x00, 0x30, 0x4e, 0x80, 0x04, 0x21, 0x7f, 0xa5, 0xeb, 0x78, 0x90, 0x61, 0x00, 0x28, 0x7f, 0x26, 0xcb, 0x78, 0x90, 0x81, 0x00, 0x2c, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x38, 0xe0, 0x00, 0x08, 0x4b, 0xff, 0xfc, 0x79, 0x7c, 0x7f, 0x1b, 0x79, 0x40, 0x80, 0xfd, 0x9c, 0x39, 0x20, 0x01, 0x36, 0x91, 0x3c, 0x00, 0x04, 0x48, 0x00, 0x00, 0x1c, 0x4b, 0xe5, 0xce, 0xc5, 0x81, 0x23, 0x00, 0x00, 0x2f, 0x89, 0x00, 0x06, 0x41, 0x9e, 0x04, 0xf8, 0x39, 0x20, 0x00, 0x54, 0x91, 0x3c, 0x00, 0x04, 0x80, 0x01, 0x04, 0x74, 0x38, 0x60, 0x00, 0x00, 0x93, 0xfc, 0x00, 0x00, 0x7c, 0x08, 0x03, 0xa6, 0x82, 0x41, 0x04, 0x38, 0x82, 0x61, 0x04, 0x3c, 0x82, 0x81, 0x04, 0x40, 0x82, 0xa1, 0x04, 0x44, 0x82, 0xc1, 0x04, 0x48, 0x82, 0xe1, 0x04, 0x4c, 0x83, 0x01, 0x04, 0x50, 0x83, 0x21, 0x04, 0x54, 0x83, 0x41, 0x04, 0x58, 0x83, 0x61, 0x04, 0x5c, 0x83, 0x81, 0x04, 0x60, 0x83, 0xa1, 0x04, 0x64, 0x83, 0xc1, 0x04, 0x68, 0x83, 0xe1, 0x04, 0x6c, 0x38, 0x21, 0x04, 0x70, 0x4e, 0x80, 0x00, 0x20, 0x2f, 0x9f, 0x00, 0x01, 0x41, 0x9e, 0x01, 0xfc, 0x2f, 0x9f, 0x00, 0x02, 0x40, 0xbe, 0xfd, 0x18, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78, 0x38, 0xe0, 0x00, 0x08, 0x4b, 0xff, 0xfb, 0x11, 0x7c, 0x7f, 0x1b, 0x79, 0x41, 0x80, 0x04, 0x90, 0x81, 0x21, 0x00, 0x28, 0x38, 0x80, 0x00, 0x02, 0xa1, 0x41, 0x00, 0x2e, 0x7d, 0x23, 0x4b, 0x78, 0xb1, 0x49, 0x00, 0x00, 0x4b, 0xe4, 0x38, 0x91, 0x4b, 0xff, 0xfc, 0xdc, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78, 0x38, 0xe0, 0x00, 0x24, 0x4b, 0xff, 0xfa, 0xd5, 0x7c, 0x7f, 0x1b, 0x79, 0x41, 0x80, 0x04, 0xa0, 0x81, 0x61, 0x00, 0x28, 0x80, 0xa1, 0x00, 0x34, 0x80, 0xc1, 0x00, 0x38, 0x7d, 0x69, 0x03, 0xa6, 0x80, 0xe1, 0x00, 0x3c, 0x81, 0x01, 0x00, 0x40, 0x81, 0x21, 0x00, 0x44, 0x81, 0x41, 0x00, 0x48, 0x80, 0x61, 0x00, 0x2c, 0x80, 0x81, 0x00, 0x30, 0x4e, 0x80, 0x04, 0x21, 0x7f, 0xa5, 0xeb, 0x78, 0x90, 0x61, 0x00, 0x28, 0x7f, 0x26, 0xcb, 0x78, 0x90, 0x81, 0x00, 0x2c, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x38, 0xe0, 0x00, 0x08, 0x4b, 0xff, 0xfb, 0x45, 0x7c, 0x7f, 0x1b, 0x79, 0x40, 0x80, 0xfc, 0x68, 0x39, 0x20, 0x00, 0xea, 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfe, 0xe8, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x38, 0xc1, 0x04, 0x2c, 0x38, 0xe0, 0x00, 0x01, 0x9a, 0xc1, 0x04, 0x2c, 0x4b, 0xff, 0xfb, 0x15, 0x7c, 0x7f, 0x1b, 0x79, 0x40, 0x80, 0xfc, 0x38, 0x39, 0x20, 0x01, 0x3b, 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfe, 0xb8, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78, 0x38, 0xe0, 0x00, 0x08, 0x4b, 0xff, 0xfa, 0x25, 0x7c, 0x7f, 0x1b, 0x79, 0x41, 0x80, 0x03, 0xd0, 0x83, 0xc1, 0x00, 0x2c, 0x83, 0xe1, 0x00, 0x28, 0x38, 0x60, 0x00, 0x01, 0x38, 0x80, 0x00, 0x00, 0x7f, 0xc5, 0xf3, 0x78, 0x38, 0xc0, 0x00, 0x00, 0x38, 0xe0, 0x00, 0x00, 0x3d, 0x00, 0x00, 0x01, 0x7f, 0xe9, 0xfb, 0x78, 0x7c, 0x3e, 0x0b, 0x78, 0x38, 0x00, 0x35, 0x00, 0x44, 0x00, 0x00, 0x02, 0x60, 0x00, 0x00, 0x00, 0x7f, 0xc1, 0xf3, 0x78, 0x4b, 0xff, 0xfb, 0xd0, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78, 0x38, 0xe0, 0x00, 0x04, 0x92, 0xe1, 0x00, 0x28, 0x4b, 0xff, 0xfa, 0x89, 0x7c, 0x7f, 0x1b, 0x79, 0x40, 0x80, 0xfb, 0xac, 0x39, 0x20, 0x01, 0x44, 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfe, 0x2c, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78, 0x38, 0xe0, 0x00, 0x04, 0x4b, 0xff, 0xf9, 0x99, 0x7c, 0x7f, 0x1b, 0x79, 0x41, 0x80, 0x03, 0x0c, 0x83, 0xe1, 0x00, 0x28, 0x38, 0x60, 0x00, 0x01, 0x38, 0x80, 0x00, 0x00, 0x38, 0xa0, 0x00, 0x00, 0x38, 0xc0, 0x00, 0x00, 0x38, 0xe0, 0x00, 0x00, 0x3d, 0x00, 0x00, 0x01, 0x7f, 0xe9, 0xfb, 0x78, 0x38, 0x00, 0x34, 0x00, 0x7c, 0x3f, 0x0b, 0x78, 0x44, 0x00, 0x00, 0x02, 0x60, 0x00, 0x00, 0x00, 0x7f, 0xe1, 0xfb, 0x78, 0x7c, 0x7f, 0x1b, 0x78, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78, 0x38, 0xe0, 0x00, 0x04, 0x93, 0xe1, 0x00, 0x28, 0x4b, 0xff, 0xfa, 0x01, 0x4b, 0xff, 0xfb, 0x28, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78, 0x38, 0xe0, 0x00, 0x08, 0x4b, 0xff, 0xf9, 0x21, 0x7c, 0x7f, 0x1b, 0x79, 0x41, 0x80, 0x02, 0xac, 0x81, 0x21, 0x00, 0x28, 0x38, 0x80, 0x00, 0x01, 0x89, 0x41, 0x00, 0x2f, 0x7d, 0x23, 0x4b, 0x78, 0x99, 0x49, 0x00, 0x00, 0x4b, 0xe4, 0x36, 0xa1, 0x4b, 0xff, 0xfa, 0xec, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x38, 0xc1, 0x04, 0x2c, 0x38, 0xe0, 0x00, 0x01, 0x4b, 0xff, 0xf8, 0xe5, 0x2c, 0x03, 0x00, 0x00, 0x41, 0x80, 0x02, 0x88, 0x88, 0xe1, 0x04, 0x2c, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78, 0x54, 0xe7, 0x06, 0x3e, 0x4b, 0xff, 0xf8, 0xc1, 0x7c, 0x7f, 0x1b, 0x79, 0x41, 0x80, 0x02, 0x80, 0x38, 0x81, 0x04, 0x30, 0x38, 0x61, 0x00, 0x30, 0x83, 0xe1, 0x00, 0x2c, 0x4b, 0xe4, 0x95, 0xfd, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x38, 0xc1, 0x04, 0x2c, 0x38, 0xe0, 0x00, 0x01, 0x7f, 0xf9, 0xfa, 0x14, 0x4b, 0xff, 0xf8, 0x8d, 0x2c, 0x03, 0x00, 0x00, 0x41, 0x80, 0x02, 0x44, 0x88, 0x81, 0x04, 0x2c, 0x80, 0x61, 0x04, 0x30, 0x7f, 0xe5, 0xfb, 0x78, 0x54, 0x84, 0x06, 0x3e, 0x38, 0xc1, 0x04, 0x2c, 0x4b, 0xe4, 0xab, 0xc1, 0x81, 0x21, 0x04, 0x2c, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78, 0x38, 0xe0, 0x00, 0x04, 0x91, 0x21, 0x00, 0x28, 0x4b, 0xff, 0xf9, 0x11, 0x7c, 0x7f, 0x1b, 0x79, 0x40, 0x80, 0xfa, 0x34, 0x39, 0x20, 0x01, 0x00, 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfc, 0xb4, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78, 0x38, 0xe0, 0x00, 0x0c, 0x4b, 0xff, 0xf8, 0x21, 0x7c, 0x7f, 0x1b, 0x79, 0x41, 0x80, 0x02, 0x04, 0x81, 0x21, 0x00, 0x28, 0x81, 0x01, 0x00, 0x30, 0x80, 0xe1, 0x00, 0x2c, 0x7d, 0x09, 0x42, 0x14, 0x7f, 0x89, 0x40, 0x00, 0x41, 0xbc, 0x00, 0x14, 0x48, 0x00, 0x01, 0x5c, 0x39, 0x29, 0x00, 0x04, 0x7f, 0x89, 0x40, 0x00, 0x40, 0x9c, 0x01, 0x50, 0x81, 0x49, 0x00, 0x00, 0x7f, 0x8a, 0x38, 0x00, 0x40, 0x9e, 0xff, 0xec, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78, 0x38, 0xe0, 0x00, 0x04, 0x91, 0x21, 0x00, 0x28, 0x4b, 0xff, 0xf8, 0x8d, 0x7c, 0x7f, 0x1b, 0x79, 0x40, 0x80, 0xf9, 0xb0, 0x39, 0x20, 0x01, 0x15, 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfc, 0x30, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78, 0x38, 0xe0, 0x00, 0x08, 0x4b, 0xff, 0xf7, 0x9d, 0x7c, 0x7f, 0x1b, 0x79, 0x41, 0x80, 0x01, 0x34, 0x81, 0x21, 0x00, 0x28, 0x38, 0x80, 0x00, 0x04, 0x81, 0x41, 0x00, 0x2c, 0x7d, 0x23, 0x4b, 0x78, 0x91, 0x49, 0x00, 0x00, 0x4b, 0xe4, 0x35, 0x1d, 0x4b, 0xff, 0xf9, 0x68, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78, 0x38, 0xe0, 0x00, 0x08, 0x4b, 0xff, 0xf7, 0x61, 0x7c, 0x7f, 0x1b, 0x79, 0x41, 0x80, 0x01, 0x38, 0x83, 0xc1, 0x00, 0x28, 0x82, 0x81, 0x00, 0x2c, 0x7f, 0x9e, 0xa0, 0x40, 0x41, 0x9e, 0x00, 0x88, 0x7f, 0x7e, 0xa0, 0x50, 0x3d, 0x3e, 0xf0, 0x00, 0x2f, 0x9b, 0x04, 0x00, 0x7f, 0xc6, 0xf3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x09, 0xc0, 0x40, 0x40, 0x9d, 0x00, 0x08, 0x3b, 0x60, 0x04, 0x00, 0x7f, 0x67, 0xdb, 0x78, 0x40, 0x99, 0x00, 0x38, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x7f, 0x26, 0xcb, 0x78, 0x7f, 0x67, 0xdb, 0x78, 0x7f, 0x83, 0xe3, 0x78, 0x4b, 0xff, 0xf7, 0x01, 0x7c, 0x7f, 0x1b, 0x79, 0x41, 0x80, 0x00, 0x68, 0x7f, 0xc3, 0xf3, 0x78, 0x7f, 0x24, 0xcb, 0x78, 0x7f, 0x65, 0xdb, 0x78, 0x4b, 0xe5, 0x34, 0x75, 0x48, 0x00, 0x00, 0x18, 0x4b, 0xff, 0xf6, 0xe1, 0x7f, 0x99, 0xf0, 0x00, 0x7c, 0x7f, 0x1b, 0x79, 0x41, 0x80, 0x00, 0x44, 0x41, 0xbe, 0xff, 0xdc, 0x7f, 0xde, 0xda, 0x14, 0x7f, 0x94, 0xf0, 0x40, 0x40, 0x9e, 0xff, 0x80, 0x7f, 0x83, 0xe3, 0x78, 0x7f, 0x44, 0xd3, 0x78, 0x7f, 0xa5, 0xeb, 0x78, 0x38, 0xc1, 0x04, 0x2c, 0x38, 0xe0, 0x00, 0x01, 0x9a, 0xa1, 0x04, 0x2c, 0x4b, 0xff, 0xf7, 0x6d, 0x4b, 0xff, 0xf8, 0x94, 0x39, 0x20, 0x00, 0x00, 0x4b, 0xff, 0xfe, 0xbc, 0x4b, 0xf6, 0x7a, 0x49, 0x4b, 0xff, 0xf8, 0x84, 0x39, 0x20, 0x00, 0xc4, 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfb, 0x04, 0x39, 0x20, 0x00, 0xa7, 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfa, 0xf8, 0x39, 0x20, 0x00, 0x67, 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfa, 0xec, 0x39, 0x20, 0x00, 0x5d, 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfa, 0xe0, 0x39, 0x20, 0x00, 0x71, 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfa, 0xd4, 0x7c, 0x67, 0x1b, 0x78, 0x4b, 0xff, 0xfd, 0x7c, 0x39, 0x20, 0x00, 0x9c, 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfa, 0xc0, 0x7c, 0x64, 0x1b, 0x78, 0x4b, 0xff, 0xfd, 0xc0, 0x39, 0x20, 0x00, 0xf1, 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfa, 0xac, 0x39, 0x20, 0x00, 0xda, 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfa, 0xa0, 0x39, 0x20, 0x00, 0xb4, 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfa, 0x94, 0x39, 0x20, 0x01, 0x05, 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfa, 0x88, 0x39, 0x20, 0x01, 0x1e, 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfa, 0x7c, 0x39, 0x20, 0x00, 0x7b, 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfa, 0x70, 0x39, 0x20, 0x00, 0x8a, 0x91, 0x3c, 0x00, 0x04, 0x4b, 0xff, 0xfa, 0x64, 0x94, 0x21, 0xff, 0xa0, 0x7c, 0x08, 0x02, 0xa6, 0x7d, 0x80, 0x00, 0x26, 0x93, 0x81, 0x00, 0x50, 0x3b, 0x80, 0xff, 0xff, 0x2d, 0x9c, 0xff, 0xff, 0x92, 0x81, 0x00, 0x30, 0x92, 0xa1, 0x00, 0x34, 0x3a, 0x80, 0x00, 0x3e, 0x92, 0xc1, 0x00, 0x38, 0x3a, 0xa0, 0x00, 0x3a, 0x92, 0xe1, 0x00, 0x3c, 0x3a, 0xc0, 0x00, 0x37, 0x93, 0x01, 0x00, 0x40, 0x3a, 0xe0, 0x00, 0x35, 0x93, 0x21, 0x00, 0x44, 0x3b, 0x00, 0x00, 0x33, 0x93, 0x41, 0x00, 0x48, 0x3b, 0x20, 0x00, 0x02, 0x93, 0x61, 0x00, 0x4c, 0x3b, 0x40, 0x1c, 0xa3, 0x93, 0xa1, 0x00, 0x54, 0x3b, 0x60, 0x00, 0x00, 0x90, 0x01, 0x00, 0x64, 0x7c, 0x9d, 0x23, 0x78, 0x93, 0xc1, 0x00, 0x58, 0x93, 0xe1, 0x00, 0x5c, 0x91, 0x81, 0x00, 0x2c, 0x4b, 0xed, 0x69, 0x3d, 0x38, 0x60, 0x00, 0x02, 0x38, 0x80, 0x00, 0x01, 0x38, 0xa0, 0x00, 0x06, 0xb3, 0x21, 0x00, 0x08, 0xb3, 0x41, 0x00, 0x0a, 0x93, 0x61, 0x00, 0x0c, 0x4b, 0xed, 0x81, 0xed, 0x2e, 0x03, 0xff, 0xff, 0x7c, 0x7f, 0x1b, 0x78, 0x40, 0x92, 0x00, 0x4c, 0x93, 0x1d, 0x00, 0x04, 0x3b, 0xc0, 0xff, 0xff, 0x2f, 0x9c, 0xff, 0xff, 0x41, 0x9e, 0x00, 0x0c, 0x7f, 0x83, 0xe3, 0x78, 0x4b, 0xed, 0x83, 0x15, 0x40, 0x92, 0x00, 0x84, 0x93, 0xdd, 0x00, 0x00, 0x38, 0x60, 0x00, 0x02, 0x38, 0x80, 0x00, 0x01, 0x38, 0xa0, 0x00, 0x06, 0xb3, 0x21, 0x00, 0x08, 0xb3, 0x41, 0x00, 0x0a, 0x93, 0x61, 0x00, 0x0c, 0x4b, 0xed, 0x81, 0xa5, 0x2e, 0x03, 0xff, 0xff, 0x7c, 0x7f, 0x1b, 0x78, 0x41, 0xb2, 0xff, 0xbc, 0x38, 0x81, 0x00, 0x08, 0x38, 0xa0, 0x00, 0x10, 0x4b, 0xed, 0x6c, 0x8d, 0x7c, 0x7e, 0x1b, 0x79, 0x41, 0x80, 0x00, 0x54, 0x7f, 0xe3, 0xfb, 0x78, 0x38, 0x80, 0x00, 0x01, 0x4b, 0xed, 0x6f, 0x79, 0x7c, 0x7e, 0x1b, 0x79, 0x41, 0x80, 0x00, 0x48, 0x39, 0x20, 0x00, 0x10, 0x7f, 0xe3, 0xfb, 0x78, 0x38, 0x81, 0x00, 0x08, 0x38, 0xa1, 0x00, 0x18, 0x91, 0x21, 0x00, 0x18, 0x4b, 0xed, 0x6a, 0xd9, 0x2f, 0x83, 0xff, 0xff, 0x7c, 0x7c, 0x1b, 0x78, 0x40, 0x9e, 0x00, 0x2c, 0x92, 0xbd, 0x00, 0x04, 0x3b, 0xc0, 0xff, 0xff, 0x7f, 0xe3, 0xfb, 0x78, 0x4b, 0xed, 0x82, 0x89, 0x93, 0xdd, 0x00, 0x00, 0x4b, 0xff, 0xff, 0x78, 0x92, 0xfd, 0x00, 0x04, 0x4b, 0xff, 0xff, 0x58, 0x92, 0xdd, 0x00, 0x04, 0x4b, 0xff, 0xff, 0x50, 0x7f, 0xe3, 0xfb, 0x78, 0x4b, 0xed, 0x82, 0x69, 0x7f, 0xa3, 0xeb, 0x78, 0x7f, 0x84, 0xe3, 0x78, 0x4b, 0xff, 0xf6, 0x05, 0x7c, 0x7e, 0x1b, 0x79, 0x41, 0x80, 0x00, 0x14, 0x7f, 0x83, 0xe3, 0x78, 0x3b, 0x80, 0xff, 0xff, 0x4b, 0xed, 0x82, 0x49, 0x4b, 0xff, 0xfe, 0xf4, 0x92, 0x9d, 0x00, 0x04, 0x3b, 0xe0, 0xff, 0xff, 0x4e, 0x0c, 0x00, 0x00, 0x4b, 0xff, 0xff, 0x1c }; static const unsigned int codehandler_text_bin_len = 3260; <|start_filename|>installer/src/loader.c<|end_filename|> #include "loader.h" #define RW_MEM_MAP 0xA0000000 #if VER == 300 #include "codehandler310.h" //TODO ??? #define INSTALL_ADDR 0x011D3000 #define MAIN_JMP_ADDR 0x0101894C #elif VER == 310 #include "codehandler310.h" #define INSTALL_ADDR 0x011D3000 #define MAIN_JMP_ADDR 0x0101894C #elif VER == 400 #include "codehandler400.h" #define INSTALL_ADDR 0x011DD000 #define MAIN_JMP_ADDR 0x0101BD4C #elif VER == 410 #include "codehandler410.h" #define INSTALL_ADDR 0x011DD000 #define MAIN_JMP_ADDR 0x0101C55C #elif VER == 500 #include "codehandler500.h" #define INSTALL_ADDR 0x011DD000 #define MAIN_JMP_ADDR 0x0101C55C #elif VER == 532 #include "codehandler532.h" #define INSTALL_ADDR 0x011DD000 #define MAIN_JMP_ADDR 0x0101C55C #elif VER == 550 #include "codehandler550.h" #define INSTALL_ADDR 0x011DD000 #define MAIN_JMP_ADDR 0x0101C56C #endif #define assert(x) \ do { \ if (!(x)) \ OSFatal("Assertion failed " #x ".\n"); \ } while (0) #define ALIGN_BACKWARD(x,align) \ ((typeof(x))(((unsigned int)(x)) & (~(align-1)))) int doBL( unsigned int dst, unsigned int src ); void doOSScreenInit(unsigned int coreinit_handle); inline void doOSScreenClear(); void doOSScreenPrintPos(char *buf, int pos); void doVPADWait(); void _main(){ /* Get a handle to coreinit.rpl. */ unsigned int coreinit_handle; OSDynLoad_Acquire("coreinit.rpl", &coreinit_handle); /* Get for later socket patch */ unsigned int nsysnet_handle; OSDynLoad_Acquire("nsysnet.rpl", &nsysnet_handle); /* Get for IP address print */ unsigned int nn_ac_handle; OSDynLoad_Acquire("nn_ac.rpl", &nn_ac_handle); /* Load a few useful symbols. */ void*(*OSEffectiveToPhysical)(const void *); void*(*OSAllocFromSystem)(uint32_t size, int align); void (*OSFreeToSystem)(void *ptr); void (*DCFlushRange)(const void *, int); void (*ICInvalidateRange)(const void *, int); void (*_Exit)(void) __attribute__ ((noreturn)); OSDynLoad_FindExport(coreinit_handle, 0, "OSEffectiveToPhysical", &OSEffectiveToPhysical); OSDynLoad_FindExport(coreinit_handle, 0, "OSAllocFromSystem", &OSAllocFromSystem); OSDynLoad_FindExport(coreinit_handle, 0, "OSFreeToSystem", &OSFreeToSystem); OSDynLoad_FindExport(coreinit_handle, 0, "DCFlushRange", &DCFlushRange); OSDynLoad_FindExport(coreinit_handle, 0, "ICInvalidateRange", &ICInvalidateRange); OSDynLoad_FindExport(coreinit_handle, 0, "_Exit", &_Exit); assert(OSEffectiveToPhysical); assert(OSAllocFromSystem); assert(OSFreeToSystem); assert(DCFlushRange); assert(ICInvalidateRange); assert(_Exit); /* Socket functions */ unsigned int *socket_lib_finish; OSDynLoad_FindExport(nsysnet_handle, 0, "socket_lib_finish", &socket_lib_finish); assert(socket_lib_finish); /* AC functions */ int(*ACGetAssignedAddress)(unsigned int *addr); OSDynLoad_FindExport(nn_ac_handle, 0, "ACGetAssignedAddress", &ACGetAssignedAddress); assert(ACGetAssignedAddress); /* IM functions */ int(*IM_SetDeviceState)(int fd, void *mem, int state, int a, int b); int(*IM_Close)(int fd); int(*IM_Open)(); OSDynLoad_FindExport(coreinit_handle, 0, "IM_SetDeviceState", &IM_SetDeviceState); OSDynLoad_FindExport(coreinit_handle, 0, "IM_Close", &IM_Close); OSDynLoad_FindExport(coreinit_handle, 0, "IM_Open", &IM_Open); assert(IM_SetDeviceState); assert(IM_Close); assert(IM_Open); /* Restart system to get lib access */ int fd = IM_Open(); void *mem = OSAllocFromSystem(0x100, 64); memset(mem, 0, 0x100); /* set restart flag to force quit browser */ IM_SetDeviceState(fd, mem, 3, 0, 0); IM_Close(fd); OSFreeToSystem(mem); /* wait a bit for browser end */ unsigned int t1 = 0x1FFFFFFF; while(t1--){}; doOSScreenInit(coreinit_handle); doOSScreenClear(); doOSScreenPrintPos("TCPGecko Installer", 0); /* Make sure the kernel exploit has been run */ if (OSEffectiveToPhysical((void *)0xA0000000) == (void *)0){ doOSScreenPrintPos("You must execute the kernel exploit before installing TCPGecko.", 1); doOSScreenPrintPos("Returning to the home menu...",2); t1 = 0x3FFFFFFF; while(t1--) ; doOSScreenClear(); _Exit(); }else{ doOSScreenPrintPos("Trying to install TCPGecko...", 1); // Make sure everything has kern I/O kern_write((void*)KERN_SYSCALL_TBL_1 + (0x34 * 4), KERN_CODE_READ); kern_write((void*)KERN_SYSCALL_TBL_2 + (0x34 * 4), KERN_CODE_READ); kern_write((void*)KERN_SYSCALL_TBL_3 + (0x34 * 4), KERN_CODE_READ); kern_write((void*)KERN_SYSCALL_TBL_4 + (0x34 * 4), KERN_CODE_READ); kern_write((void*)KERN_SYSCALL_TBL_5 + (0x34 * 4), KERN_CODE_READ); kern_write((void*)KERN_SYSCALL_TBL_1 + (0x35 * 4), KERN_CODE_WRITE); kern_write((void*)KERN_SYSCALL_TBL_2 + (0x35 * 4), KERN_CODE_WRITE); kern_write((void*)KERN_SYSCALL_TBL_3 + (0x35 * 4), KERN_CODE_WRITE); kern_write((void*)KERN_SYSCALL_TBL_4 + (0x35 * 4), KERN_CODE_WRITE); kern_write((void*)KERN_SYSCALL_TBL_5 + (0x35 * 4), KERN_CODE_WRITE); /* Our main writable area */ unsigned int physWriteLoc = (unsigned int)OSEffectiveToPhysical((void*)RW_MEM_MAP); /* Install codehandler */ unsigned int phys_codehandler_loc = (unsigned int)OSEffectiveToPhysical((void*)INSTALL_ADDR); void *codehandler_loc = (unsigned int*)(RW_MEM_MAP + (phys_codehandler_loc - physWriteLoc)); memcpy(codehandler_loc, codehandler_text_bin, codehandler_text_bin_len); DCFlushRange(codehandler_loc, codehandler_text_bin_len); ICInvalidateRange(codehandler_loc, codehandler_text_bin_len); /* Patch coreinit jump */ unsigned int phys_main_jmp_loc = (unsigned int)OSEffectiveToPhysical((void*)MAIN_JMP_ADDR); unsigned int *main_jmp_loc = (unsigned int*)(RW_MEM_MAP + (phys_main_jmp_loc - physWriteLoc)); *main_jmp_loc = doBL(INSTALL_ADDR, MAIN_JMP_ADDR); DCFlushRange(ALIGN_BACKWARD(main_jmp_loc, 32), 0x20); ICInvalidateRange(ALIGN_BACKWARD(main_jmp_loc, 32), 0x20); /* Patch Socket Function */ unsigned int phys_socket_loc = (unsigned int)OSEffectiveToPhysical(socket_lib_finish); unsigned int *socket_loc = (unsigned int*)(RW_MEM_MAP + (phys_socket_loc - physWriteLoc)); socket_loc[0] = 0x38600000; socket_loc[1] = 0x4E800020; DCFlushRange(ALIGN_BACKWARD(socket_loc, 32), 0x40); ICInvalidateRange(ALIGN_BACKWARD(socket_loc, 32), 0x40); /* The fix for Splatoon and such */ kern_write((void*)(KERN_ADDRESS_TBL + (0x12 * 4)), 0x00000000); kern_write((void*)(KERN_ADDRESS_TBL + (0x13 * 4)), 0x14000000); /* All good! */ unsigned int addr; ACGetAssignedAddress(&addr); char buf[64]; __os_snprintf(buf,64,"Success! Your Gecko IP is %i.%i.%i.%i.", (addr>>24)&0xFF,(addr>>16)&0xFF,(addr>>8)&0xFF,addr&0xFF); doOSScreenPrintPos(buf, 2); doOSScreenPrintPos("Press any button to return to the home menu.", 3); doVPADWait(); } doOSScreenClear(); _Exit(); } int doBL( unsigned int dst, unsigned int src ){ unsigned int newval = (dst - src); newval &= 0x03FFFFFC; newval |= 0x48000001; return newval; } /* for internal and gcc usage */ void* memset(void* dst, const uint8_t val, uint32_t size){ uint32_t i; for (i = 0; i < size; i++){ ((uint8_t*) dst)[i] = val; } return dst; } void* memcpy(void* dst, const void* src, uint32_t size){ uint32_t i; for (i = 0; i < size; i++){ ((uint8_t*) dst)[i] = ((const uint8_t*) src)[i]; } return dst; } /* Write a 32-bit word with kernel permissions */ void kern_write(void *addr, uint32_t value){ asm( "li 3,1\n" "li 4,0\n" "mr 5,%1\n" "li 6,0\n" "li 7,0\n" "lis 8,1\n" "mr 9,%0\n" "mr %1,1\n" "li 0,0x3500\n" "sc\n" "nop\n" "mr 1,%1\n" : : "r"(addr), "r"(value) : "memory", "ctr", "lr", "0", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" ); } /* OSScreen helper functions */ void doOSScreenInit(unsigned int coreinit_handle){ /* OSScreen functions */ void(*OSScreenInit)(); unsigned int(*OSScreenGetBufferSizeEx)(unsigned int bufferNum); unsigned int(*OSScreenSetBufferEx)(unsigned int bufferNum, void * addr); OSDynLoad_FindExport(coreinit_handle, 0, "OSScreenInit", &OSScreenInit); OSDynLoad_FindExport(coreinit_handle, 0, "OSScreenGetBufferSizeEx", &OSScreenGetBufferSizeEx); OSDynLoad_FindExport(coreinit_handle, 0, "OSScreenSetBufferEx", &OSScreenSetBufferEx); assert(OSScreenInit); assert(OSScreenGetBufferSizeEx); assert(OSScreenSetBufferEx); /* Call the Screen initilzation function */ OSScreenInit(); /* Grab the buffer size for each screen (TV and gamepad) */ int buf0_size = OSScreenGetBufferSizeEx(0); int buf1_size = OSScreenGetBufferSizeEx(1); /* Set the buffer area */ OSScreenSetBufferEx(0, (void *)0xF4000000); OSScreenSetBufferEx(1, (void *)0xF4000000 + buf0_size); } inline void doOSScreenClear(){ /* Clear both framebuffers */ int ii; for (ii = 0; ii < 2; ii++){ fillScreen(0,0,0,0); flipBuffers(); } } void doOSScreenPrintPos(char *buf, int pos){ int i; for(i=0;i<2;i++){ drawString(0,pos,buf); flipBuffers(); } } void doVPADWait(){ unsigned int vpad_handle; OSDynLoad_Acquire("vpad.rpl", &vpad_handle); /* VPAD functions */ int(*VPADRead)(int controller, VPADData *buffer, unsigned int num, int *error); OSDynLoad_FindExport(vpad_handle, 0, "VPADRead", &VPADRead); assert(VPADRead); int error; VPADData vpad_data; /* Read initial vpad status */ VPADRead(0, &vpad_data, 1, &error); while(1){ VPADRead(0, &vpad_data, 1, &error); if(vpad_data.btn_hold){ break; } } } <|start_filename|>installer/Makefile<|end_filename|> root := . project := $(root)/src build := $(root)/bin libs := $(root)/../../libwiiu/bin www := $(root)/../../www framework := $(root)/../../framework AS=powerpc-eabi-as CC=powerpc-eabi-gcc CFLAGS=-nostdinc -fno-builtin -c LDFLAGS=-T $(project)/link.ld -nostartfiles -nostdlib -s all: clean setup main550 main532 main500 main410 main400 main310 main300 setup: mkdir -p $(root)/bin/ main550: $(AS) $(project)/asm.s -o $(root)/asm.o $(CC) $(CFLAGS) -DVER=550 $(project)/*.c #-Wa,-a,-ad mv -f $(root)/*.o $(build) $(CC) $(LDFLAGS) -o $(build)/code550.bin $(libs)/550/draw.o $(build)/*.o main532: $(AS) $(project)/asm.s -o $(root)/asm.o $(CC) $(CFLAGS) -DVER=532 $(project)/*.c #-Wa,-a,-ad mv -f $(root)/*.o $(build) $(CC) $(LDFLAGS) -o $(build)/code532.bin $(libs)/532/draw.o $(build)/*.o main500: $(AS) $(project)/asm.s -o $(root)/asm.o $(CC) $(CFLAGS) -DVER=500 $(project)/*.c #-Wa,-a,-ad mv -f $(root)/*.o $(build) $(CC) $(LDFLAGS) -o $(build)/code500.bin $(libs)/500/draw.o $(build)/*.o main410: $(AS) $(project)/asm.s -o $(root)/asm.o $(CC) $(CFLAGS) -DVER=410 $(project)/*.c #-Wa,-a,-ad mv -f $(root)/*.o $(build) $(CC) $(LDFLAGS) -o $(build)/code410.bin $(libs)/410/draw.o $(build)/*.o main400: $(AS) $(project)/asm.s -o $(root)/asm.o $(CC) $(CFLAGS) -DVER=400 $(project)/*.c #-Wa,-a,-ad mv -f $(root)/*.o $(build) $(CC) $(LDFLAGS) -o $(build)/code400.bin $(libs)/400/draw.o $(build)/*.o main310: $(AS) $(project)/asm.s -o $(root)/asm.o $(CC) $(CFLAGS) -DVER=400 $(project)/*.c #-Wa,-a,-ad mv -f $(root)/*.o $(build) $(CC) $(LDFLAGS) -o $(build)/code310.bin $(libs)/310/draw.o $(build)/*.o main300: $(AS) $(project)/asm.s -o $(root)/asm.o $(CC) $(CFLAGS) -DVER=300 $(project)/*.c #-Wa,-a,-ad mv -f $(root)/*.o $(build) $(CC) $(LDFLAGS) -o $(build)/code300.bin $(libs)/300/draw.o $(build)/*.o clean: rm -f -r $(build)/* <|start_filename|>installer/src/loader.h<|end_filename|> #ifndef LOADER_H #define LOADER_H #include "../../../libwiiu/src/coreinit.h" #include "../../../libwiiu/src/draw.h" #include "../../../libwiiu/src/socket.h" #include "../../../libwiiu/src/types.h" #include "../../../libwiiu/src/vpad.h" /* Kernel address table */ #if VER == 300 #define KERN_ADDRESS_TBL 0xFFEB66E4 #define KERN_SYSCALL_TBL_1 0xFFE84D50 #define KERN_SYSCALL_TBL_2 0xFFE85150 #define KERN_SYSCALL_TBL_3 0xFFE85D50 #define KERN_SYSCALL_TBL_4 0xFFE85550 #define KERN_SYSCALL_TBL_5 0xFFE85950 #define KERN_CODE_READ 0xFFF02214 #define KERN_CODE_WRITE 0xFFF02234 #elif VER == 310 #define KERN_ADDRESS_TBL 0xFFEB66E4 #define KERN_SYSCALL_TBL_1 0xFFE84D50 #define KERN_SYSCALL_TBL_2 0xFFE85150 #define KERN_SYSCALL_TBL_3 0xFFE85D50 #define KERN_SYSCALL_TBL_4 0xFFE85550 #define KERN_SYSCALL_TBL_5 0xFFE85950 #define KERN_CODE_READ 0xFFF02214 #define KERN_CODE_WRITE 0xFFF02234 #elif VER == 400 #define KERN_ADDRESS_TBL 0xFFEB7E5C #define KERN_SYSCALL_TBL_1 0xFFE84C90 #define KERN_SYSCALL_TBL_2 0xFFE85090 #define KERN_SYSCALL_TBL_3 0xFFE85C90 #define KERN_SYSCALL_TBL_4 0xFFE85490 #define KERN_SYSCALL_TBL_5 0xFFE85890 #define KERN_CODE_READ 0xFFF02214 #define KERN_CODE_WRITE 0xFFF02234 #elif VER == 410 #define KERN_ADDRESS_TBL 0xFFEB902C #define KERN_SYSCALL_TBL_1 0xFFE84C90 #define KERN_SYSCALL_TBL_2 0xFFE85090 #define KERN_SYSCALL_TBL_3 0xFFE85C90 #define KERN_SYSCALL_TBL_4 0xFFE85490 #define KERN_SYSCALL_TBL_5 0xFFE85890 #define KERN_CODE_READ 0xFFF02214 #define KERN_CODE_WRITE 0xFFF02234 #elif VER == 500 #define KERN_ADDRESS_TBL 0xFFEA9E4C #define KERN_SYSCALL_TBL_1 0xFFE84C70 #define KERN_SYSCALL_TBL_2 0xFFE85070 #define KERN_SYSCALL_TBL_3 0xFFE85470 #define KERN_SYSCALL_TBL_4 0xFFEA9120 #define KERN_SYSCALL_TBL_5 0xFFEA9520 #define KERN_CODE_READ 0xFFF021f4 #define KERN_CODE_WRITE 0xFFF02214 #elif VER == 532 #define KERN_ADDRESS_TBL 0xFFEAAA10 #define KERN_SYSCALL_TBL_1 0xFFE84C70 #define KERN_SYSCALL_TBL_2 0xFFE85070 #define KERN_SYSCALL_TBL_3 0xFFE85470 #define KERN_SYSCALL_TBL_4 0xFFEA9CE0 #define KERN_SYSCALL_TBL_5 0xFFEAA0E0 #define KERN_CODE_READ 0xFFF02274 #define KERN_CODE_WRITE 0xFFF02294 #elif VER == 550 #define KERN_ADDRESS_TBL 0xFFEAB7A0 #define KERN_SYSCALL_TBL_1 0xFFE84C70 #define KERN_SYSCALL_TBL_2 0xFFE85070 #define KERN_SYSCALL_TBL_3 0xFFE85470 #define KERN_SYSCALL_TBL_4 0xFFEAAA60 #define KERN_SYSCALL_TBL_5 0xFFEAAE60 #define KERN_CODE_READ 0xFFF023D4 #define KERN_CODE_WRITE 0xFFF023F4 #else #error "Unsupported Wii U software version" #endif void _main(); void kern_write(void *addr, uint32_t value); void* memset(void* dst, const uint8_t val, uint32_t size); void* memcpy(void* dst, const void* src, uint32_t size); #endif /* LOADER_H */ <|start_filename|>codehandler/main.c<|end_filename|> #include "main.h" static void start(int argc, void *argv); static int rungecko(struct bss_t *bss, int clientfd); static int recvwait(struct bss_t *bss, int sock, void *buffer, int len); static int recvbyte(struct bss_t *bss, int sock); static int checkbyte(struct bss_t *bss, int sock); static int sendwait(struct bss_t *bss, int sock, const void *buffer, int len); static int sendbyte(struct bss_t *bss, int sock, unsigned char byte); static void *kern_read(const void *addr); static void kern_write(void *addr, void *value); int _start(int argc, char *argv[]) { struct bss_t *bss; bss = memalign(sizeof(struct bss_t), 0x40); if (bss == 0) goto error; memset(bss, 0, sizeof(struct bss_t)); OSCreateThread( &bss->thread, start, 0, bss, bss->stack + sizeof(bss->stack), sizeof(bss->stack), 0, 0xc ); OSResumeThread(&bss->thread); error: return main(argc, argv); } #define CHECK_ERROR(cond) if (cond) { bss->line = __LINE__; goto error; } static void start(int argc, void *argv) { int sockfd = -1, clientfd = -1, ret, len; struct sockaddr_in addr; struct bss_t *bss = argv; socket_lib_init(); while (1) { addr.sin_family = AF_INET; addr.sin_port = 7331; addr.sin_addr.s_addr = 0; sockfd = ret = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); CHECK_ERROR(ret == -1); ret = bind(sockfd, (void *)&addr, 16); CHECK_ERROR(ret < 0); ret = listen(sockfd, 1); CHECK_ERROR(ret < 0); len = 16; clientfd = ret = accept(sockfd, (void *)&addr, &len); CHECK_ERROR(ret == -1); socketclose(sockfd); sockfd = -1; ret = rungecko(bss, clientfd); CHECK_ERROR(ret < 0); socketclose(clientfd); clientfd = -1; continue; error: if (clientfd != -1) socketclose(clientfd); if (sockfd != -1) socketclose(sockfd); bss->error = ret; } } static int rungecko(struct bss_t *bss, int clientfd) { int ret; unsigned char buffer[0x401]; while (1) { ret = checkbyte(bss, clientfd); if (ret < 0) { CHECK_ERROR(errno != EWOULDBLOCK); GX2WaitForVsync(); continue; } switch (ret) { case 0x01: { /* cmd_poke08 */ char *ptr; ret = recvwait(bss, clientfd, buffer, 8); CHECK_ERROR(ret < 0); ptr = ((char **)buffer)[0]; *ptr = buffer[7]; DCFlushRange(ptr, 1); break; } case 0x02: { /* cmd_poke16 */ short *ptr; ret = recvwait(bss, clientfd, buffer, 8); CHECK_ERROR(ret < 0); ptr = ((short **)buffer)[0]; *ptr = ((short *)buffer)[3]; DCFlushRange(ptr, 2); break; } case 0x03: { /* cmd_pokemem */ int *ptr; ret = recvwait(bss, clientfd, buffer, 8); CHECK_ERROR(ret < 0); ptr = ((int **)buffer)[0]; *ptr = ((int *)buffer)[1]; DCFlushRange(ptr, 4); break; } case 0x04: { /* cmd_readmem */ const unsigned char *ptr, *end; ret = recvwait(bss, clientfd, buffer, 8); CHECK_ERROR(ret < 0); ptr = ((const unsigned char **)buffer)[0]; end = ((const unsigned char **)buffer)[1]; while (ptr != end) { int len, i; len = end - ptr; if (len > 0x400) len = 0x400; for (i = 0; i < len; i++) if (ptr[i] != 0) break; if (i == len) { // all zero! ret = sendbyte(bss, clientfd, 0xb0); CHECK_ERROR(ret < 0); } else { memcpy(buffer + 1, ptr, len); buffer[0] = 0xbd; ret = sendwait(bss, clientfd, buffer, len + 1); CHECK_ERROR(ret < 0); } ret = checkbyte(bss, clientfd); if (ret == 0xcc) /* GCFAIL */ goto next_cmd; ptr += len; } break; } case 0x0b: { /* cmd_writekern */ void *ptr, * value; ret = recvwait(bss, clientfd, buffer, 8); CHECK_ERROR(ret < 0); ptr = ((void **)buffer)[0]; value = ((void **)buffer)[1]; kern_write(ptr, value); break; } case 0x0c: { /* cmd_readkern */ void *ptr, *value; ret = recvwait(bss, clientfd, buffer, 4); CHECK_ERROR(ret < 0); ptr = ((void **)buffer)[0]; value = kern_read(ptr); *(void **)buffer = value; sendwait(bss, clientfd, buffer, 4); break; } case 0x41: { /* cmd_upload */ unsigned char *ptr, *end, *dst; ret = recvwait(bss, clientfd, buffer, 8); CHECK_ERROR(ret < 0); ptr = ((unsigned char **)buffer)[0]; end = ((unsigned char **)buffer)[1]; while (ptr != end) { int len; len = end - ptr; if (len > 0x400) len = 0x400; if ((int)ptr >= 0x10000000 && (int)ptr <= 0x50000000) { dst = ptr; } else { dst = buffer; } ret = recvwait(bss, clientfd, dst, len); CHECK_ERROR(ret < 0); if (dst == buffer) { memcpy(ptr, buffer, len); } ptr += len; } sendbyte(bss, clientfd, 0xaa); /* GCACK */ break; } case 0x50: { /* cmd_status */ ret = sendbyte(bss, clientfd, 1); /* running */ CHECK_ERROR(ret < 0); break; } case 0x70: { /* cmd_rpc */ long long (*fun)(int, int, int, int, int, int, int, int); int r3, r4, r5, r6, r7, r8, r9, r10; long long result; ret = recvwait(bss, clientfd, buffer, 4 + 8 * 4); CHECK_ERROR(ret < 0); fun = ((void **)buffer)[0]; r3 = ((int *)buffer)[1]; r4 = ((int *)buffer)[2]; r5 = ((int *)buffer)[3]; r6 = ((int *)buffer)[4]; r7 = ((int *)buffer)[5]; r8 = ((int *)buffer)[6]; r9 = ((int *)buffer)[7]; r10 = ((int *)buffer)[8]; result = fun(r3, r4, r5, r6, r7, r8, r9, r10); ((long long *)buffer)[0] = result; ret = sendwait(bss, clientfd, buffer, 8); CHECK_ERROR(ret < 0); break; } case 0x71: { /* cmd_getsymbol */ char size = recvbyte(bss, clientfd); CHECK_ERROR(size < 0); ret = recvwait(bss, clientfd, buffer, size); CHECK_ERROR(ret < 0); /* Identify the RPL name and symbol name */ char *rplname = (char*) &((int*)buffer)[2]; char *symname = (char*) (&buffer[0] + ((int*)buffer)[1]); /* Get the symbol and store it in the buffer */ unsigned int module_handle, function_address; OSDynLoad_Acquire(rplname, &module_handle); char data = recvbyte(bss, clientfd); OSDynLoad_FindExport(module_handle, data, symname, &function_address); ((int*)buffer)[0] = (int)function_address; ret = sendwait(bss, clientfd, buffer, 4); CHECK_ERROR(ret < 0); break; } case 0x72: { /* cmd_search32 */ ret = recvwait(bss, clientfd, buffer, 12); CHECK_ERROR(ret < 0); int addr = ((int *) buffer)[0]; int val = ((int *) buffer)[1]; int size = ((int *) buffer)[2]; int i; int resaddr = 0; for(i = addr; i < (addr+size); i+=4) { if(*(int*)i == val) { resaddr = i; break; } } ((int *)buffer)[0] = resaddr; ret = sendwait(bss, clientfd, buffer, 4); CHECK_ERROR(ret < 0); break; } case 0x80: { /* cmd_rpc_big */ long long (*fun)(int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int); int r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15, r16, r17, r18; long long result; ret = recvwait(bss, clientfd, buffer, 4 + 16 * 4); CHECK_ERROR(ret < 0); fun = ((void **)buffer)[0]; r3 = ((int *)buffer)[1]; r4 = ((int *)buffer)[2]; r5 = ((int *)buffer)[3]; r6 = ((int *)buffer)[4]; r7 = ((int *)buffer)[5]; r8 = ((int *)buffer)[6]; r9 = ((int *)buffer)[7]; r10 = ((int *)buffer)[8]; r11 = ((int *)buffer)[9]; r12 = ((int *)buffer)[10]; r13 = ((int *)buffer)[11]; r14 = ((int *)buffer)[12]; r15 = ((int *)buffer)[13]; r16 = ((int *)buffer)[14]; r17 = ((int *)buffer)[15]; r18 = ((int *)buffer)[16]; result = fun(r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15, r16, r17, r18); ((long long *)buffer)[0] = result; ret = sendwait(bss, clientfd, buffer, 8); CHECK_ERROR(ret < 0); break; } case 0x99: { /* cmd_version */ ret = sendbyte(bss, clientfd, 0x82); /* WiiU */ CHECK_ERROR(ret < 0); break; } case 0x9A: { /* cmd_os_version */ /* Little bit of a hack here, the linker script will define the * symbol ver to have address of the version number! */ extern char ver[]; ((int *)buffer)[0] = (int)ver; ret = sendwait(bss, clientfd, buffer, 4); CHECK_ERROR(ret < 0); break; } case 0xcc: { /* GCFAIL */ break; } default: ret = -1; CHECK_ERROR(0); break; } next_cmd: continue; } return 0; error: bss->error = ret; return 0; } static int recvwait(struct bss_t *bss, int sock, void *buffer, int len) { int ret; while (len > 0) { ret = recv(sock, buffer, len, 0); CHECK_ERROR(ret < 0); len -= ret; buffer += ret; } return 0; error: bss->error = ret; return ret; } static int recvbyte(struct bss_t *bss, int sock) { unsigned char buffer[1]; int ret; ret = recvwait(bss, sock, buffer, 1); if (ret < 0) return ret; return buffer[0]; } static int checkbyte(struct bss_t *bss, int sock) { unsigned char buffer[1]; int ret; ret = recv(sock, buffer, 1, MSG_DONTWAIT); if (ret < 0) return ret; if (ret == 0) return -1; return buffer[0]; } static int sendwait(struct bss_t *bss, int sock, const void *buffer, int len) { int ret; while (len > 0) { ret = send(sock, buffer, len, 0); CHECK_ERROR(ret < 0); len -= ret; buffer += ret; } return 0; error: bss->error = ret; return ret; } static int sendbyte(struct bss_t *bss, int sock, unsigned char byte) { unsigned char buffer[1]; buffer[0] = byte; return sendwait(bss, sock, buffer, 1); } /* Naughty syscall which we installed to allow arbitrary kernel mode reading. * This syscall actually branches part way into __OSReadRegister32Ex after the * address validation has already occurred. */ static void *kern_read(const void *addr) { void *result; asm( "li 3,1\n" "li 4,0\n" "li 5,0\n" "li 6,0\n" "li 7,0\n" "lis 8,1\n" "mr 9,%1\n" "li 0,0x3400\n" "mr %0,1\n" "sc\n" "nop\n" /* sometimes on return it skips an instruction */ "mr 1,%0\n" "mr %0,3\n" : "=r"(result) : "b"(addr) : "memory", "ctr", "lr", "0", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" ); return result; } /* Naughty syscall which we installed to allow arbitrary kernel mode writing. * This syscall actually branches part way into __OSWriteRegister32Ex after the * address validation has already occurred. */ static void kern_write(void *addr, void *value) { asm( "li 3,1\n" "li 4,0\n" "mr 5,%1\n" "li 6,0\n" "li 7,0\n" "lis 8,1\n" "mr 9,%0\n" "mr %1,1\n" "li 0,0x3500\n" "sc\n" "nop\n" /* sometimes on return it skips an instruction */ "mr 1,%1\n" : : "r"(addr), "r"(value) : "memory", "ctr", "lr", "0", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" ); } <|start_filename|>codehandler/main.h<|end_filename|> /* string.h */ #define NULL ((void *)0) extern void *memcpy(void *dst, const void *src, int bytes); extern void *memset(void *dst, int val, int bytes); /* errno.h */ extern int *__gh_errno_ptr(void); #define errno (*__gh_errno_ptr()) #define EWOULDBLOCK 6 /* malloc.h */ extern void *(* const MEMAllocFromDefaultHeapEx)(int size, int align); extern void *(* const MEMAllocFromDefaultHeap)(int size); extern void *(* const MEMFreeToDefaultHeap)(void *ptr); #define memalign (*MEMAllocFromDefaultHeapEx) #define malloc (*MEMAllocFromDefaultHeap) #define free (*MEMFreeToDefaultHeap) /* socket.h */ #define AF_INET 2 #define SOCK_STREAM 1 #define IPPROTO_TCP 6 #define MSG_DONTWAIT 32 extern void socket_lib_init(); extern int socket(int domain, int type, int protocol); extern int socketclose(int socket); extern int connect(int socket, void *addr, int addrlen); extern int send(int socket, const void *buffer, int size, int flags); extern int recv(int socket, void *buffer, int size, int flags); struct in_addr { unsigned int s_addr; }; struct sockaddr_in { short sin_family; unsigned short sin_port; struct in_addr sin_addr; char sin_zero[8]; }; extern int bind(int socket, void *addr, int size); extern int listen(int socket, int backlog); extern int accept(int socket, void *addr, int *size); /* coreinit.rpl */ #include <stdbool.h> #include <stddef.h> #include <stdint.h> typedef struct { char tag[8]; /* 0x000 "OSContxt" */ int32_t gpr[32]; /* 0x008 from OSDumpContext */ uint32_t cr; /* 0x088 from OSDumpContext */ uint32_t lr; /* 0x08c from OSDumpContext */ uint32_t ctr; /* 0x090 from context switch code */ uint32_t xer; /* 0x094 from context switch code */ uint32_t srr0; /* 0x098 from OSDumpContext */ uint32_t srr1; /* 0x09c from OSDumpContext */ char _unknowna0[0xb8 - 0xa0]; uint64_t fpr[32]; /* 0x0b8 from OSDumpContext */ int16_t spinLockCount; /* 0x1b8 from OSDumpContext */ char _unknown1ba[0x1bc - 0x1ba]; /* 0x1ba could genuinely be padding? */ uint32_t gqr[8]; /* 0x1bc from OSDumpContext */ char _unknown1dc[0x1e0 - 0x1dc]; uint64_t psf[32]; /* 0x1e0 from OSDumpContext */ int64_t coretime[3]; /* 0x2e0 from OSDumpContext */ int64_t starttime; /* 0x2f8 from OSDumpContext */ int32_t error; /* 0x300 from OSDumpContext */ char _unknown304[0x6a0 - 0x304]; } OSThread; /* 0x6a0 total length from RAM dumps */ extern bool OSCreateThread(OSThread *thread, void (*entry)(int,void*), int argc, void *args, void *stack, size_t stack_size, int32_t priority, int16_t affinity); extern void OSResumeThread(OSThread *thread); extern void DCFlushRange(const void *addr, size_t length); extern int OSDynLoad_Acquire(char* rpl, unsigned int *handle); extern int OSDynLoad_FindExport(unsigned int handle, int isdata, char *symbol, void *address); /* gx */ extern void GX2WaitForVsync(void); /* main */ extern int (* const entry_point)(int argc, char *argv[]); #define main (*entry_point) /* BSS section */ struct bss_t { int error, line; OSThread thread; char stack[0x8000]; };
pablingalas/hacks
<|start_filename|>components/github/actions/get-repo/get-repo.js<|end_filename|> const github = require('../../github.app.js') const { Octokit } = require('@octokit/rest') module.exports = { key: "github-get-repo", name: "Get Repo", description: "Get details for a repo including the owner, description, metrics (e.g., forks, stars, watchers, issues) and more.", version: "0.0.2", type: "action", props: { github, repoFullName: { propDefinition: [github, "repoFullName"] }, }, async run() { const octokit = new Octokit({ auth: this.github.$auth.oauth_access_token }) return (await octokit.repos.get({ owner: this.repoFullName.split("/")[0], repo: this.repoFullName.split("/")[1], })).data }, } <|start_filename|>components/firebase_admin_sdk/sources/common.js<|end_filename|> const firebase = require("../firebase_admin_sdk.app.js"); module.exports = { props: { firebase, timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 15, }, }, }, methods: { processEvent() { throw new Error("processEvent is not implemented"); }, }, async run(event) { try { await this.firebase.initializeApp(); await this.processEvent(event); } catch (err) { console.log("CHECK HERE FOR ERROR: ", err.response); throw new Error(err); } finally { this.firebase.deleteApp(); } }, }; <|start_filename|>components/ahrefs/actions/get-backlinks-one-per-domain/get-backlinks-one-per-domain.js<|end_filename|> const ahrefs = require('../../ahrefs.app.js') const axios = require('axios') module.exports = { name: 'Get Backlinks One Per Domain', key: "ahrefs-get-backlinks-one-per-domain", description: "Get one backlink with the highest `ahrefs_rank` per referring domain for a target URL or domain (with details for the referring pages including anchor and page title).", version: '0.0.4', type: "action", props: { ahrefs, target: { propDefinition: [ahrefs, "target"] }, mode: { propDefinition: [ahrefs, "mode"] }, limit: { propDefinition: [ahrefs, "limit"] }, }, async run() { return (await axios({ url: `https://apiv2.ahrefs.com`, params: { token: this.ahrefs.$auth.oauth_access_token, from: "backlinks_one_per_domain", target: this.target, mode: this.mode, limit: this.limit, order_by: "ahrefs_rank:desc", output: "json" }, })).data }, } <|start_filename|>components/asana/asana.app.js<|end_filename|> const axios = require("axios"); const crypto = require("crypto"); module.exports = { type: "app", app: "asana", propDefinitions: { workspaceId: { type: "string", label: "Workspace", optional: false, async options(opts) { const workspaces = await this.getWorkspaces(); return workspaces.map((workspace) => { return { label: workspace.name, value: workspace.gid, }; }); }, }, projectId: { type: "string", label: "Project", optional: false, async options(opts) { const projects = await this.getProjects(opts.workspaceId); return projects.map((project) => { return { label: project.name, value: project.gid, }; }); }, }, taskIds: { type: "string[]", label: "Tasks", async options(opts) { const tasks = await this.getTasks(opts.projectId); return tasks.map((task) => { return { label: task.name, value: task.gid }; }); }, }, organizationId: { type: "string", label: "Organization", optional: false, async options(opts) { const organizations = await this.getOrganizations(); return organizations.map((organization) => { return { label: organization.name, value: organization.gid, }; }); }, }, }, methods: { async _getBaseUrl() { return "https://app.asana.com/api/1.0" }, async _getHeaders() { return { Accept: "application/json", Authorization: `Bearer ${this.$auth.oauth_access_token}`, }; }, async _makeRequest(endpoint) { config = { url: `${await this._getBaseUrl()}/${endpoint}`, headers: { Accept: "application/json", Authorization: `Bearer ${this.$auth.oauth_access_token}`, } }; try { return await axios(config); } catch (err) { console.log(err); } }, async _getAuthorizationHeader({ data, method, url, headers }) { return await axios({ method: "POST", url: `${await this._getBaseUrl()}/webhooks`, data: data.body, headers, }); }, async createHook(body) { const config = { method: "post", url: `${await this._getBaseUrl()}/webhooks`, headers: { "Content-Type": "applicaton/json", Accept: "application/json", Authorization: `Bearer ${this.$auth.oauth_access_token}`, }, data: { body, }, }; const authorization = await this._getAuthorizationHeader(config); config.headers.authorization = authorization; try { await axios(config); } catch (err) { console.log(err); } return authorization.data; }, async deleteHook(hookId) { const config = { method: "delete", url: `${await this._getBaseUrl()}/webhooks/${hookId}`, headers: await this._getHeaders(), }; try { await axios(config); } catch (err) { console.log(err); } }, async verifyAsanaWebhookRequest(request) { let secret = this.$auth.oauth_refresh_token; var base64Digest = function (s) { return crypto.createHmac("sha1", secret).update(s).digest("base64"); }; var content = JSON.stringify(request.body); var doubleHash = base64Digest(content); var headerHash = request.headers["x-hook-secret"]; return doubleHash === headerHash; }, async getWorkspace(workspaceId) { return (await this._makeRequest(`workspaces/${workspaceId}`)).data.data; }, async getWorkspaces() { return (await this._makeRequest("workspaces")).data.data; }, async getOrganizations() { const organizations = []; const workspaces = await this.getWorkspaces(); for (const workspace of workspaces) { let w = await this.getWorkspace(workspace.gid); if (w.is_organization) organizations.push(w); } return organizations; }, async getProject(projectId) { return (await this._makeRequest(`projects/${projectId}`)).data.data; }, async getProjects(workspaceId) { return (await this._makeRequest(`projects?workspace=${workspaceId}`)).data.data; }, async getStory(storyId) { return (await this._makeRequest(`stories/${storyId}`)).data.data; }, async getTask(taskId) { return (await this._makeRequest(`tasks/${taskId}`)).data.data; }, async getTasks(projectId) { let incompleteTasks = []; const tasks = (await this._makeRequest(`projects/${projectId}/tasks`)).data.data; for (const task of tasks) { let t = await this.getTask(task.gid); if (t.completed == false) incompleteTasks.push(task); } return incompleteTasks; }, async getTag(tagId) { return (await this._makeRequest(`tags/${tagId}`)).data.data; }, async getTeam(teamId) { return (await this._makeRequest(`teams/${teamId}`)).data.data; }, async getTeams(organizationId) { return (await this._makeRequest(`organizations/${organizationId}/teams`)).data.data; }, async getUser(userId) { return (await this._makeRequest(`users/${userId}`)).data.data; }, async getUsers(workspaceId) { return (await this._makeRequest(`workspaces/${workspaceId}/users`)).data.data; }, }, }; <|start_filename|>interfaces/timer/examples/example-cron-component.js<|end_filename|> // Example component that runs a console.log() statement once a minute // Run `pd logs <component>` to see these logs in the CLI module.exports = { name: "cronjob", version: "0.0.1", props: { timer: { type: "$.interface.timer", default: { cron: "0 0 * * *", }, }, }, async run() { console.log("Run any Node.js code here"); }, }; <|start_filename|>components/bitbucket/sources/new-repo-event/new-repo-event.js<|end_filename|> const common = require("../../common"); const { bitbucket } = common.props; const EVENT_SOURCE_NAME = "New Repository Event (Instant)"; module.exports = { ...common, name: EVENT_SOURCE_NAME, key: "bitbucket-new-repo-event", description: "Emits an event when a repository-wide event occurs.", version: "0.0.2", props: { ...common.props, repositoryId: { propDefinition: [ bitbucket, "repositoryId", c => ({ workspaceId: c.workspaceId }), ], }, eventTypes: { propDefinition: [ bitbucket, "eventTypes", c => ({ subjectType: "repository" }), ], }, }, methods: { ...common.methods, getEventSourceName() { return EVENT_SOURCE_NAME; }, getHookEvents() { return this.eventTypes; }, getHookPathProps() { return { workspaceId: this.workspaceId, repositoryId: this.repositoryId, }; }, generateMeta(data) { const { "x-request-uuid": id, "x-event-key": eventType, "x-event-time": eventDate, } = data.headers; const summary = `New repository event: ${eventType}`; const ts = +new Date(eventDate); return { id, summary, ts, }; }, async processEvent(event) { const data = { headers: event.headers, body: event.body, }; const meta = this.generateMeta(data); this.$emit(data, meta); }, }, }; <|start_filename|>components/shopify/sources/new-paid-order/new-paid-order.js<|end_filename|> const shopify = require("../../shopify.app.js"); const { dateToISOStringWithoutMs } = require("../common/utils"); /** * The component's run timer. * @constant {number} * @default 300 (5 minutes) */ const DEFAULT_TIMER_INTERVAL_SECONDS = 60 * 5; /** * The minimum time interval from Order Transaction to Order update where the * Order update will be considered the result of the Transaction. * Note: From testing, an Order (`financial_status:=PAID`) seems to be updated * within 15s of the Transaction. * @constant {number} * @default 30000 (30 seconds) */ const MIN_ALLOWED_TRANSACT_TO_ORDER_UPDATE_MS = 1000 * 30 * 1; /** * Uses Shopify GraphQL API to get Order Transactions (`created_at`) in the same * request as Orders (`updated_at`). Order Transaction `created_at` dates are * used to determine if a `PAID` Order's update was from being paid - to avoid * duped orders if there are more than 100 orders between updates of a `PAID` * Order. * * Data from GraphQL request is used to generate list of relevant Order IDs. * Relevent Orders are requested via Shopify REST API using list of relevant * Order IDs. */ module.exports = { key: "shopify-new-paid-order", name: "New Paid Order", description: "Emits an event each time a new order is paid.", version: "0.0.3", dedupe: "unique", props: { db: "$.service.db", timer: { type: "$.interface.timer", default: { intervalSeconds: DEFAULT_TIMER_INTERVAL_SECONDS, }, }, shopify, }, methods: { _getPrevCursor() { return this.db.get("prevCursor") || null; }, _setPrevCursor(prevCursor) { this.db.set("prevCursor", prevCursor); }, /** * Returns the allowed time interval between Order Transaction and Order * update where the Order update can still be considered the result of * becoming 'paid'. * * @returns {number} The number of milliseconds after a Transaction is created */ _getAllowedTransactToOrderUpdateMs() { return Math.max( MIN_ALLOWED_TRANSACT_TO_ORDER_UPDATE_MS, 2 * DEFAULT_TIMER_INTERVAL_SECONDS * 1000, ); }, /** * Gets the fields to include in a GraphQL query. * * To get the query fields for an Orders query like this, * @example * { * orders { * edges { * node { * updatedAt * name * legacyResourceId * transactions { * createdAt * } * } * } * } * } * the function would look like this: * @example * function getQueryFields() { * return [ * "updatedAt", * "name", * "legacyResourceId", * "transactions.createdAt", * ]; * } * * @returns {string[]} The GraphQL query fields */ getQueryFields() { // See https://shopify.dev/docs/admin-api/graphql/reference/orders/order // With these fields and a limit of 100, queries cost up to 202 points return [ "updatedAt", "name", "legacyResourceId", // The ID of the corresponding resource (Order) in the REST Admin API. "transactions.createdAt", ]; }, /** * Gets the filter string to be used in a GraphQL query. * @param {object} opts Options for creating the query filter * @param {string} [opts.updatedAt=null] The minimum `updated_at` time to * allow in queried resources * @returns The query filter string */ getQueryFilter({ updatedAt = null }) { return `financial_status:paid updated_at:>${updatedAt}`; }, isRelevant(order) { // Don't emit if Order was updated long after last Transaction (update not // caused by order being paid) let lastTransactionDate = null; // Iterate over Order Transactions to get date of most recent Transaction for (const transaction of order.transactions) { const transactionDate = Date.parse(transaction.createdAt); if (!lastTransactionDate || transactionDate - lastTransactionDate > 0) { lastTransactionDate = transactionDate; } } if (!lastTransactionDate) { return false; } const timeFromTransactToOrderUpdate = Date.parse(order.updatedAt) - lastTransactionDate; // - If the Order was updated long after the last Transaction, assume // becoming 'paid' was not the cause of update. // - Allow at least 2x the timer interval (2 * 5min) after an Order // Transaction for Order updates to be considered 'paid' updates. // - If 2x the timer interval isn't allowed, some Orders that are updated // from a Transaction and then one or more times between polling requests // could be considered not 'paid' by the update (because time from Order // Transaction `created_at` to Order `updated_at` would be too large). // - The larger interval could cause Orders updated multiple times within // the interval to be considered 'paid' twice, but those Order events // would be deduped if there are fewer than 100 paid Orders in 2x timer // inverval. return ( timeFromTransactToOrderUpdate < this._getAllowedTransactToOrderUpdateMs() ); }, generateMeta(order) { return { id: order.id, summary: `Order paid: ${order.name}`, ts: Date.parse(order.updated_at), }; }, }, async run() { const prevCursor = this._getPrevCursor(); const queryOrderOpts = { fields: this.getQueryFields(), filter: this.getQueryFilter({ // If there is no cursor yet, get orders updated_at after 1 day ago // The Shopify GraphQL Admin API does not accept date ISO strings that include milliseconds updatedAt: prevCursor ? null : dateToISOStringWithoutMs(this.shopify.dayAgo()), }), prevCursor, }; const orderStream = this.shopify.queryOrders(queryOrderOpts); const relevantOrderIds = []; for await (const orderInfo of orderStream) { const { order, cursor, } = orderInfo; if (this.isRelevant(order)) { relevantOrderIds.push(order.legacyResourceId); } this._setPrevCursor(cursor); } const relevantOrders = await this.shopify.getOrdersById(relevantOrderIds); relevantOrders.forEach((order) => { const meta = this.generateMeta(order); this.$emit(order, meta); }); }, }; <|start_filename|>components/twitch/actions/search-channels/search-channels.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, name: "Search Channels", key: "twitch-search-channels", description: `Returns a list of channels (users who have streamed within the past 6 months) that match the query via channel name or description either entirely or partially. Results include both live and offline channels.`, version: "0.0.1", type: "action", props: { ...common.props, max: { propDefinition: [ common.props.twitch, "max", ], description: "Maximum number of channels to return", }, query: { type: "string", label: "Query", description: "The search query", }, liveOnly: { type: "boolean", label: "Live Only", description: "Filter results for live streams only", default: false, }, }, async run() { const params = { query: this.query, live_only: this.liveOnly, }; const searchResults = await this.paginate( this.twitch.searchChannels.bind(this), params, this.max, ); return await this.getPaginatedResults(searchResults); }, }; <|start_filename|>components/datadog/sources/payload-format.js<|end_filename|> /** * This object specifies the fields to include as part of every webhook call * payload, and their mappings to Datadog webhook variables. * * See https://docs.datadoghq.com/integrations/webhooks/#usage for further * details. */ module.exports = { aggregKey: "$AGGREG_KEY", alertCycleKey: "$ALERT_CYCLE_KEY", alertId: "$ALERT_ID", alertMetric: "$ALERT_METRIC", alertPriority: "$ALERT_PRIORITY", alertQuery: "$ALERT_QUERY", alertScope: "$ALERT_SCOPE", alertStatus: "$ALERT_STATUS", alertTitle: "$ALERT_TITLE", alertTransition: "$ALERT_TRANSITION", alertType: "$ALERT_TYPE", date: "$DATE", email: "$EMAIL", eventMsg: "$EVENT_MSG", eventTitle: "$EVENT_TITLE", eventType: "$EVENT_TYPE", hostname: "$HOSTNAME", id: "$ID", lastUpdated: "$LAST_UPDATED", link: "$LINK", logsSample: "$LOGS_SAMPLE", metricNamespace: "$METRIC_NAMESPACE", orgId: "$ORG_ID", orgName: "$ORG_NAME", priority: "$PRIORITY", snapshot: "$SNAPSHOT", tags: "$TAGS", textOnlyMsg: "$TEXT_ONLY_MSG", user: "$USER", username: "$USERNAME", }; <|start_filename|>components/pipedream/pipedream.app.js<|end_filename|> // Pipedream API app file const axios = require("axios"); const { convertArrayToCSV } = require("convert-array-to-csv"); const PIPEDREAM_SQL_BASE_URL = "https://rt.pipedream.com/sql"; module.exports = { type: "app", app: "pipedream", methods: { async _makeAPIRequest(opts) { if (!opts.headers) opts.headers = {}; opts.headers["Authorization"] = `Bearer ${this.$auth.api_key}`; opts.headers["Content-Type"] = "application/json"; opts.headers["user-agent"] = "@PipedreamHQ/pipedream v0.1"; const { path } = opts; delete opts.path; opts.url = `https://api.pipedream.com/v1${ path[0] === "/" ? "" : "/" }${path}`; return await axios(opts); }, async subscribe(emitter_id, listener_id, channel) { let params = { emitter_id, listener_id, }; if (channel) { params.event_name = channel; } return await this._makeAPIRequest({ method: "POST", path: "/subscriptions", params, }); }, async listEvents(dcID, event_name) { return ( await this._makeAPIRequest({ path: `/sources/${dcID}/event_summaries`, params: { event_name, }, }) ).data; }, async deleteEvent(dcID, eventID, event_name) { return ( await this._makeAPIRequest({ method: "DELETE", path: `/sources/${dcID}/events`, params: { start_id: eventID, end_id: eventID, event_name, }, }) ).data; }, // Runs a query againt the Pipedream SQL service // https://docs.pipedream.com/destinations/sql/ async runSQLQuery(query, format) { const { data } = await axios({ url: PIPEDREAM_SQL_BASE_URL, method: "POST", headers: { Authorization: `Bearer ${this.$auth.api_key}`, }, data: { query }, }); const { error, queryExecutionId, resultSet, resultsFilename } = data; if (error && error.toDisplay) { throw new Error(error.toDisplay); } // Parse raw results const results = { columnInfo: resultSet.ResultSetMetadata.ColumnInfo, queryExecutionId, csvLocation: `https://rt.pipedream.com/sql/csv/${resultsFilename}`, }; let formattedResults = []; // We can return results as an object, CSV, or array (default) if (format === "object") { // The SQL service returns headers as the first row of results let headers = resultSet.Rows.shift(); for (const row of resultSet.Rows) { let obj = {}; for (let j = 0; j < row.Data.length; j++) { // Column name : row value obj[headers.Data[j].VarCharValue] = row.Data[j].VarCharValue; } formattedResults.push(obj); } } else { for (const row of resultSet.Rows) { formattedResults.push(row.Data.map((data) => data.VarCharValue)); } } if (format === "csv") { formattedResults = convertArrayToCSV(formattedResults); } results.results = formattedResults; return results; }, }, }; <|start_filename|>components/twilio/sources/common-polling.js<|end_filename|> const twilio = require("../twilio.app.js"); module.exports = { props: { twilio, db: "$.service.db", timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 15, }, }, }, methods: { _getCreatedAfter() { return this.db.get("createdAfter"); }, _setCreatedAfter(createdAfter) { this.db.set("createdAfter", createdAfter); }, emitEvent(result) { const meta = this.generateMeta(result); this.$emit(result, meta); }, }, async run(event) { let dateCreatedAfter = this._getCreatedAfter(); const params = { dateCreatedAfter, }; const results = await this.listResults(params); for (const result of results) { this.emitEvent(result); if ( !dateCreatedAfter || Date.parse(result.dateCreated) > Date.parse(dateCreatedAfter) ) dateCreatedAfter = result.dateCreated; } this._setCreatedAfter(dateCreatedAfter); }, }; <|start_filename|>components/twitch/actions/common.js<|end_filename|> const common = require("../sources/common.js"); module.exports = { ...common, methods: { ...common.methods, async getUserId() { const { data: authenticatedUserData } = await this.twitch.getUsers(); const { id } = authenticatedUserData[0]; return id; }, async getPaginatedResults(paginated) { const results = []; for await (const result of paginated) { results.push(result); } return results; }, }, }; <|start_filename|>components/eventbrite/sources/new-attendee-registered/new-attendee-registered.js<|end_filename|> const common = require("../common/webhook.js"); module.exports = { ...common, key: "eventbrite-new-attendee-registered", name: "<NAME> Registered (Instant)", description: "Emits an event when an attendee registers for an event", version: "0.0.1", dedupe: "unique", methods: { ...common.methods, getActions() { return "order.placed"; }, async getData(order) { const { id: orderId, event_id: eventId } = order; const attendeeStream = await this.resourceStream( this.eventbrite.getOrderAttendees.bind(this), "attendees", orderId ); const attendees = []; for await (const attendee of attendeeStream) { attendees.push(attendee); } const event = await this.eventbrite.getEvent(eventId, { expand: "ticket_classes", }); return { order, attendees, event, }; }, generateMeta({ order }) { const { id, name: summary, created } = order; return { id, summary, ts: Date.parse(created), }; }, }, }; <|start_filename|>components/pipefy/sources/card-overdue/card-overdue.js<|end_filename|> const common = require("../common-polling.js"); module.exports = { ...common, name: "Card Overdue", key: "pipefy-card-overdue", description: "Emits an event each time a card becomes overdue in a Pipe.", version: "0.0.1", methods: { isCardRelevant({ node, event }) { const { timestamp: eventTimestamp } = event; const eventDate = eventTimestamp * 1000; const { due_date: dueDateIso } = node; const dueDate = Date.parse(dueDateIso); return ( dueDate < eventDate && !node.done ); }, getMeta({ node, event }) { const { id, title: summary, due_date: dueDate, } = node; const { timestamp: eventTimestamp } = event; const ts = Date.parse(dueDate) || eventTimestamp; return { id, summary, ts, }; } }, }; <|start_filename|>components/slack/actions/list_reminders/list_reminders.js<|end_filename|> const slack = require("../../slack.app.js"); module.exports = { key: "slack-list-reminders", name: "List Reminders", description: "List all reminders for a given user", version: "0.0.1", type: "action", props: { slack, team_id: { propDefinition: [ slack, "team_id", ], optional: true, }, }, async run() { return await this.slack.sdk().reminders.list({ team_id: this.team_id, }); }, }; <|start_filename|>components/formstack/sources/new-form-submission/new-form-submission.js<|end_filename|> const formstack = require("../../formstack.app.js"); const get = require("lodash.get"); module.exports = { key: "formstack-new-form-submission", name: "New Form Submission (Instant)", description: "Emits an event for each new form submission.", version: "0.0.1", dedupe: "unique", props: { formstack, db: "$.service.db", http: "$.interface.http", formId: { propDefinition: [formstack, "formId"] }, }, hooks: { async activate() { const { id } = await this.formstack.createHook({ id: this.formId, url: this.http.endpoint, }); this.db.set("hookId", id); }, async deactivate() { await this.formstack.deleteHook({ hookId: this.db.get("hookId"), }); }, }, async run(event) { const body = get(event, "body"); if (!body) { return; } // verify incoming request if ( this.formstack.$auth.oauth_refresh_token !== get(body, "HandshakeKey") ) { console.log("HandshakeKey mismatch. Exiting."); return; } const uniqueID = get(body, "UniqueID"); if (!uniqueID) return; delete body.HandshakeKey; this.$emit(body, { id: body.UniqueID, summary: `New Form Submission ${body.UniqueID}`, ts: Date.now(), }); }, }; <|start_filename|>components/twitch/actions/get-channel-information/get-channel-information.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, name: "Get Channel Information", key: "twitch-get-channel-information", description: "Retrieves information about a particular broadcaster's channel", version: "0.0.1", type: "action", props: { ...common.props, broadcaster: { propDefinition: [ common.props.twitch, "broadcaster", ], description: "ID of the user/channel to get information about", }, }, async run() { const params = { broadcaster_id: this.broadcaster, }; return (await this.twitch.getChannelInformation(params)).data.data; }, }; <|start_filename|>components/here/here.app.js<|end_filename|> module.exports = { type: "app", app: "here", propDefinitions: { zipCode: { type: "integer", label: "ZIP code", description: "The ZIP code you'd like to pull weather stats for (only supported for locations in the United States)", }, }, methods: { _apiUrl() { return "https://weather.ls.hereapi.com/weather/1.0"; }, _apiKey() { return this.$auth.apikey; }, async returnReportForZIP(zipCode) { const baseUrl = this._apiUrl(); return await require("@pipedreamhq/platform").axios(this, { url: `${baseUrl}/report.json?apiKey=${this._apiKey()}&product=observation&zipcode=${zipCode}`, }); }, }, }; <|start_filename|>components/airtable/actions/list-records/list-records.js<|end_filename|> const common = require("../common.js"); const commonList = require("../common-list.js"); module.exports = { key: "airtable-list-records", name: "List Records", description: "Retrieve records from a table with automatic pagination. Optionally sort and filter results.", type: "action", version: "0.1.0", ...commonList, props: { ...common.props, ...commonList.props, }, }; <|start_filename|>components/textlocal/textlocal.app.js<|end_filename|> const axios = require("axios"); module.exports = { type: "app", app: "textlocal", methods: { _apiUrl() { return "https://api.txtlocal.com"; }, _apiKey() { return this.$auth.api_key; }, _apiMessageHistoryUrl() { // API docs: https://api.txtlocal.com/docs/messagereporting/getapimessagehistory const baseUrl = this._apiUrl(); return `${baseUrl}/get_history_api`; }, _contactGroupsUrl() { // API docs: https://api.txtlocal.com/docs/contactmanagement/getgroups const baseUrl = this._apiUrl(); return `${baseUrl}/get_groups`; }, _contactsUrl() { // API docs: https://api.txtlocal.com/docs/contactmanagement/getcontacts const baseUrl = this._apiUrl(); return `${baseUrl}/get_contacts`; }, _baseRequestParams() { return { apikey: this._apiKey(), }; }, async _getApiMessageHistory({ limit = 100, sortOrder = "desc", start = 0, }) { const url = this._apiMessageHistoryUrl(); const params = { ...this._baseRequestParams(), limit, sort_order: sortOrder, start, }; const { data } = await axios.get(url, { params }); return data; }, /** * Get the ID of the latest message sent via the [Send * SMS](https://api.txtlocal.com/docs/sendsms) API. * * @return {string} The message ID */ async getLatestMessageId() { const { messages } = await this._getApiMessageHistory({ limit: 1, }); if (messages.length === 0) { console.log("No messages sent so far"); return; } const { id } = messages.shift(); return id; }, /** * This generator function scans the history of messages sent via the [Send * SMS](https://api.txtlocal.com/docs/sendsms) API and yields each message * separately. * * It accepts optional parameter `lowerBoundMessageId` that will stop the * scan whenever it reaches a message with ID equal to the provided value of * the parameter. * * @param {object} options Options to customize the operation * @param {string} options.lowerBoundMessageId The ID of the message at * which the scan should stop * @yield {object} The next message in the message history */ async *scanApiMessageHistory({ lowerBoundMessageId }) { let start = 0; let prevTotal; do { const { messages, total, } = await this._getApiMessageHistory({ start, }); prevTotal = prevTotal ? prevTotal : total; for (const message of messages) { if (message.id === lowerBoundMessageId) { return; } yield message; } start += messages.length + (total - prevTotal); prevTotal = total; } while (start < prevTotal); }, /** * Retrieves the list of Contact Groups in the user's account, as provided * by the [Get * Groups](https://api.txtlocal.com/docs/contactmanagement/getgroups) API. * * @return {object} The response of the call to the Get Groups API */ async getContactGroups() { const url = this._contactGroupsUrl(); const params = this._baseRequestParams(); const { data } = await axios.get(url, { params }); return data; }, async _getContactsInGroup({ groupId, limit = 100, start = 0, }) { const url = this._contactsUrl(); const params = { ...this._baseRequestParams(), group_id: groupId, limit, start, }; const { data } = await axios.get(url, { params }); return data; }, /** * This generator function scans a specific contact group and yields each * contact in such group separately. * * It requires a parameter `groupId` that identifies the contact group to * scan. * * @param {object} options Options to customize the operation * @param {string} options.groupId The ID of the contact group to scan for * contacts * @yield {object} The next contact in the contact group */ async *scanContactGroup({ groupId }) { let start = 0; let prevNumContacts; do { const { contacts, num_contacts: numContacts, } = await this._getContactsInGroup({ groupId, }); prevNumContacts = prevNumContacts ? prevNumContacts : numContacts; for (const contact of contacts) { yield contact; } start += contacts.length + (numContacts - prevNumContacts); prevNumContacts = numContacts; } while (start < prevNumContacts); }, }, }; <|start_filename|>components/twitch/actions/get-followers/get-followers.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, name: "Get Followers", key: "twitch-get-followers", description: "Retrieves a list of users who follow the specified user", version: "0.0.1", type: "action", props: { ...common.props, user: { propDefinition: [ common.props.twitch, "user", ], description: "User ID of the user to get followers of", }, max: { propDefinition: [ common.props.twitch, "max", ], description: "Maximum number of followers to return", }, }, async run() { const params = { to_id: this.user, }; // get the users who follow the specified user const follows = await this.paginate( this.twitch.getUserFollows.bind(this), params, this.max, ); return await this.getPaginatedResults(follows); }, }; <|start_filename|>components/mysql/sources/new-table/new-table.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, key: "mysql-new-table", name: "New Table", description: "Emits an event when a new table is added to a database", version: "0.0.1", dedupe: "unique", props: { ...common.props, db: "$.service.db", }, hooks: { async deploy() { const connection = await this.mysql.getConnection(); const tables = await this.mysql.listTopTables(connection); this.iterateAndEmitEvents(tables); this._setLastResult(tables, "CREATE_TIME"); await this.mysql.closeConnection(connection); }, }, methods: { ...common.methods, async listResults(connection) { const lastResult = this._getLastResult(); const tables = await this.mysql.listBaseTables(connection, lastResult); this.iterateAndEmitEvents(tables); this._setLastResult(tables, "CREATE_TIME"); }, generateMeta({ TABLE_NAME: tableName, CREATE_TIME: createTime }) { return { id: tableName, summary: tableName, ts: Date.parse(createTime), }; }, }, }; <|start_filename|>components/shopify/sources/common/utils.js<|end_filename|> module.exports.dateToISOStringWithoutMs = (date) => { return date.toISOString().replace(/\.\d{3}Z$/, "Z"); }; <|start_filename|>components/pipefy/pipefy.app.js<|end_filename|> const axios = require("axios"); module.exports = { type: "app", app: "pipefy", methods: { _getBaseUrl() { return "https://app.pipefy.com"; }, _getHeaders() { return { Accept: "application/json", Authorization: `Bearer ${this.$auth.token}`, "User-Agent": "@PipedreamHQ/pipedream v0.1", }; }, async _makeRequest(data, endpoint) { const config = { method: "POST", url: `${this._getBaseUrl()}/${endpoint}`, headers: this._getHeaders(), data, }; return (await axios(config)).data; }, async _makeQueriesRequest(data = null) { return await this._makeRequest(data, "queries"); }, async _makeGraphQlRequest(data = null) { return await this._makeRequest(data, "graphql"); }, async createHook({ pipe_id, name, url, actions }) { const data = { query: ` mutation { createWebhook(input: { pipe_id: ${pipe_id} name: "${name}" url: "${url}" actions: ["${actions}"] headers: \"{\\\"token\\\": \\\"${this.$auth.token}\\\"}\" }) { webhook { id name } } } `, }; return (await this._makeQueriesRequest(data)).data.createWebhook; }, async deleteHook(hookId) { const data = { query: ` mutation { deleteWebhook(input: { id: ${hookId} }) { success } } `, }; await this._makeQueriesRequest(data); }, async getCard(id) { const data = { query: ` { card(id: ${id}) { id title url comments{text} createdAt createdBy{name} due_date } } `, }; return await this._makeGraphQlRequest(data); }, async listCards(pipe_id) { const data = { query: ` { cards(pipe_id: ${pipe_id}, first: 100) { edges { node { id title assignees { id } comments { text } comments_count current_phase { name id } done late expired due_date fields { name value } labels { name } phases_history { phase { name } firstTimeIn lastTimeOut } url } } } } `, }; return (await this._makeQueriesRequest(data)).data.cards; }, }, }; <|start_filename|>components/snowflake/sources/query-results/query-results.js<|end_filename|> const { v4: uuidv4 } = require("uuid"); const common = require("../common"); module.exports = { ...common, key: "snowflake-query-results", name: "Query Results", description: "Emit an event with the results of an arbitrary query", version: "0.0.1", props: { ...common.props, sqlQuery: { type: "string", label: "SQL Query", description: "Your SQL query", }, dedupeKey: { type: "string", label: "De-duplication Key", description: "The name of a column in the table to use for de-duplication", optional: true, }, }, methods: { ...common.methods, generateMeta(data) { const { row: { [this.dedupeKey]: id = uuidv4(), }, timestamp: ts, } = data; const summary = `New event (ID: ${id})`; return { id, summary, ts, }; }, generateMetaForCollection(data) { const { timestamp: ts, } = data; const id = uuidv4(); const summary = `New event (ID: ${id})`; return { id, summary, ts, }; }, getStatement() { return { sqlText: this.sqlQuery, }; }, }, }; <|start_filename|>components/activecampaign/sources/new-campaign-unsubscribe/new-campaign-unsubscribe.js<|end_filename|> const activecampaign = require("../../activecampaign.app.js"); const common = require("../common-campaign.js"); module.exports = { ...common, name: "New Campaign Unsubscribe (Instant)", key: "activecampaign-new-campaign-unsubscribe", description: "Emits an event when a contact unsubscribes as a result of a campaign email sent to them.", version: "0.0.1", methods: { ...common.methods, getEvents() { return ["unsubscribe"]; }, }, }; <|start_filename|>components/slack/actions/find-message/find-message.js<|end_filename|> const slack = require("../../slack.app.js"); module.exports = { key: "slack-find-message", name: "Find Message", description: "Find a Slack message", version: "0.0.1", type: "action", props: { slack, query: { propDefinition: [ slack, "query", ], }, count: { propDefinition: [ slack, "count", ], optional: true, }, team_id: { propDefinition: [ slack, "team_id", ], optional: true, }, }, async run() { return await this.slack.sdk().search.messages({ query: this.query, count: this.count, }); }, }; <|start_filename|>components/mysql/sources/new-or-updated-row/new-or-updated-row.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, key: "mysql-new-or-updated-row", name: "New or Updated Row", description: "Emits an event when you add or modify a new row in a table", version: "0.0.1", dedupe: "unique", props: { ...common.props, db: "$.service.db", table: { propDefinition: [common.props.mysql, "table"] }, column: { propDefinition: [ common.props.mysql, "column", (c) => ({ table: c.table }), ], label: "Order By", description: "A datetime column, such as 'date_updated' or 'last_modified' that is set to the current datetime when a row is updated.", }, }, hooks: { async deploy() { const connection = await this.mysql.getConnection(); await this.listTopRows(connection, this.column); await this.mysql.closeConnection(connection); }, }, methods: { ...common.methods, async listResults(connection) { await this.listRowResults(connection, this.column); }, generateMeta(row) { return { id: JSON.stringify(row), summary: `New Row Added/Updated ${row[this.column]}`, ts: Date.now(), }; }, }, }; <|start_filename|>components/formstack/sources/new-form/new-form.js<|end_filename|> const formstack = require("../../formstack.app.js"); module.exports = { key: "formstack-new-form", name: "New Form", description: "Emits an event for each new form added.", version: "0.0.1", dedupe: "unique", props: { formstack, db: "$.service.db", timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 15, }, }, }, async run() { const largestPreviousFormId = this.db.get("largestPreviousFormId") || 0; let largestFormId = 0; let forms = []; let page = 1; const per_page = 100; let total = per_page; while (total === per_page) { const results = await this.formstack.getForms(page, per_page); total = results.length; forms = forms.concat(results); page++; } for (const form of forms) { if (form.id > largestPreviousFormId) { this.$emit(form, { id: form.id, summary: form.name, ts: Date.now(), }); largestFormId = form.id; } } if (largestFormId > 0) this.db.set("largestPreviousFormId", largestFormId); }, }; <|start_filename|>components/twist/event-types.js<|end_filename|> // The Twist event types that can be subscribed to via webhook. // The lines commented out are for event types listed in Twist's documentation, // but not yet available. Coming Soon! module.exports = [ { label: "Workspace Added", value: `workspace_added` }, { label: "Workspace Updated", value: `workspace_updated` }, // { label: "Workspace Deleted", value: `workspace_deleted` }, { label: "Workspace User Added", value: `workspace_user_added` }, { label: "Workspace User Updated", value: `workspace_user_updated` }, { label: "Workspace User Removed", value: `workspace_user_removed` }, { label: "Channel Added", value: `channel_added` }, { label: "Channel Updated", value: `channel_updated` }, { label: "Channel Deleted", value: `channel_deleted` }, { label: "Channel User Added", value: `channel_user_added` }, // { label: "Channel User Updated", value: `channel_user_updated` }, { label: "Channel User Removed", value: `channel_user_removed` }, { label: "Thread Added", value: `thread_added` }, { label: "Thread Updated", value: `thread_updated` }, { label: "Thread Deleted", value: `thread_deleted` }, { label: "Comment Added", value: `comment_added` }, { label: "Comment Updated", value: `comment_updated` }, { label: "Comment Deleted", value: `comment_deleted` }, { label: "Message Added", value: `message_added` }, { label: "Message Updated", value: `message_updated` }, // { label: "Message Deleted", value: `message_deleted` }, // { label: "Group Added", value: `group_added` }, // { label: "Group Updated", value: `group_updated` }, // { label: "Group Deleted", value: `group_deleted` }, // { label: "Group User Added", value: `group_user_added` }, // { label: "Group User Removed", value: `group_user_removed` }, ]; <|start_filename|>components/twitch/actions/get-stream-by-user/get-stream-by-user.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, name: "Get Stream By User", key: "twitch-get-stream-by-user", description: "Gets stream information (the stream object) for a specified user", version: "0.0.1", type: "action", props: { ...common.props, user: { propDefinition: [ common.props.twitch, "user", ], description: "User ID of the user whose stream to get information about", }, }, async run() { // get live streams for the specified streamer const streams = await this.paginate(this.twitch.getStreams.bind(this), { user_id: this.user, }); return await this.getPaginatedResults(streams); }, }; <|start_filename|>components/faunadb/faunadb.app.js<|end_filename|> // FaunaDB app file const faunadb = require("faunadb"); const q = faunadb.query; module.exports = { type: "app", app: "faunadb", propDefinitions: { collection: { type: "string", label: "Collection", description: "The collection you'd like to watch for changes", async options() { return await this.getCollections(); }, }, }, methods: { // Fetches events (changes) for all documents in a collection // made after a specific epoch timestamp getClient() { return new faunadb.Client({ secret: this.$auth.secret }); }, async getCollections() { const client = this.getClient(); const collections = []; const collectionsPaginator = await client.paginate(q.Collections()); await collectionsPaginator.each((page) => { for (const collection of page) { collections.push({ label: collection.id, value: collection.id, }); } }); return collections; }, async getEventsInCollectionAfterTs(collection, after) { const client = this.getClient(); // Fetch pages of all changes (events) for a particular collection // since the given timestamp cursor. See docs on Events / Pagination // https://docs.fauna.com/fauna/current/api/fql/functions/events // https://docs.fauna.com/fauna/current/api/fql/functions/paginate const paginationHelper = await client.paginate( q.Documents(q.Collection(collection)), { after, events: true } ); const events = []; await paginationHelper.each((page) => { for (const event of page) { events.push(event); } }); return events; }, }, }; <|start_filename|>components/calendly/sources/invitee-canceled/invitee-canceled.js<|end_filename|> const common = require("../common-webhook.js"); module.exports = { ...common, key: "calendly-invitee-cancelled", name: "Invitee Cancelled (Instant)", description: "Emits an event when an invitee cancels a scheduled event", version: "0.0.2", dedupe: "unique", methods: { ...common.methods, getEvents() { return ["invitee.canceled"]; }, generateMeta(body) { return this.generateInviteeMeta(body); }, }, }; <|start_filename|>components/google_drive/utils.js<|end_filename|> const { MY_DRIVE_VALUE } = require("./constants"); /** * Returns whether the specified drive ID corresponds to the authenticated * user's My Drive or not * * @param {String} drive the ID value of a Google Drive * @returns `true` only when the specified drive is the user's 'My Drive' */ function isMyDrive(drive) { return drive === MY_DRIVE_VALUE; } /** * Returns a valid Google Drive ID to be used in Google Drive API calls * * @param {String} drive the ID value of a Google Drive, as provided by the * `drive` prop definition of this app * @returns the proper Google Drive ID to be used in Google Drive API calls */ function getDriveId(drive) { return isMyDrive(drive) ? null : drive; } module.exports = { MY_DRIVE_VALUE, isMyDrive, getDriveId, }; <|start_filename|>components/uservoice/uservoice.app.js<|end_filename|> /* API docs: https://developer.uservoice.com/docs/api/v2/reference/ Getting Started Guide: https://developer.uservoice.com/docs/api/v2/getting-started/ */ module.exports = { type: "app", app: "uservoice", methods: { _accessToken() { return this.$auth.access_token; }, _apiUrl() { return `https://${this._subdomain()}.uservoice.com/api/v2`; }, async _makeRequest(opts) { if (!opts.headers) opts.headers = {}; opts.headers.authorization = `Bearer ${this._accessToken()}`; opts.headers["user-agent"] = "@PipedreamHQ/pipedream v0.1"; const { path } = opts; delete opts.path; opts.url = `${this._apiUrl()}${path[0] === "/" ? "" : "/"}${path}`; return await require("@pipedreamhq/platform").axios(this, opts); }, _subdomain() { return this.$auth.subdomain; }, // https://developer.uservoice.com/docs/api/v2/reference/#operation/ListNpsRatings async listNPSRatings({ updated_after, numSampleResults }) { const npsRatings = []; let cursor; do { const { nps_ratings, pagination } = await this._makeRequest({ path: "/admin/nps_ratings", params: { per_page: 100, // max allowed by API cursor, updated_after, }, }); npsRatings.push(...(nps_ratings || [])); // When retrieving sample data, return early once we've fetched numSampleResults if (numSampleResults && npsRatings.length >= numSampleResults) { return npsRatings.slice(0, numSampleResults); } cursor = pagination.cursor; } while (cursor); // Calculate the ISO 8601 timestamp of the most recent record, if available let maxUpdatedAt; if (npsRatings.length) { const dates = npsRatings.map((r) => new Date(r.updated_at)); maxUpdatedAt = new Date(Math.max.apply(null, dates)).toISOString(); } return { npsRatings, maxUpdatedAt }; }, }, }; <|start_filename|>components/mysql/sources/common.js<|end_filename|> const mysql = require("../mysql.app.js"); module.exports = { props: { mysql, timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 15, }, }, }, methods: { _getLastResult() { return this.db.get("lastResult"); }, /** * Sets lastResult in db. Since results are ordered by the specified column, we can assume the maximum * result for that column is in the first row returned. * @param {object} rows - The rows returned to be emitted. * @param {string} column - Name of the table column to order by */ _setLastResult(rows, column) { if (rows.length) this.db.set("lastResult", rows[0][column]); }, iterateAndEmitEvents(results) { for (const result of results) { const meta = this.generateMeta(result); this.$emit(result, meta); } }, /** * Used by components that call listRows(). Gets lastResult, gets rows, sets lastResult, and returns rows. * @param {object} connection - The database connection. * @param {string} column - Name of the table column to order by */ async listRowResults(connection, column) { let lastResult = this._getLastResult(); const rows = await this.mysql.listRows( connection, this.table, column, lastResult ); this._setLastResult(rows, column); this.iterateAndEmitEvents(rows); }, async listTopRows(connection, column, maxCount = 10) { const rows = await this.mysql.listMaxRows( connection, this.table, column, maxCount ); this._setLastResult(rows, column); this.iterateAndEmitEvents(rows); }, }, async run(event) { const connection = await this.mysql.getConnection(); try { await this.listResults(connection); } catch (err) { console.log(err); } finally { await this.mysql.closeConnection(connection); } }, }; <|start_filename|>components/github/sources/new-security-alert/new-security-alert.js<|end_filename|> const common = require("../common-polling.js"); module.exports = { ...common, key: "github-new-security-alert", name: "New Security Alert", description: "Emit new events when GitHub discovers a security vulnerability in one of your repositories", version: "0.0.4", type: "source", dedupe: "greatest", methods: { ...common.methods, generateMeta(data) { const ts = new Date(data.updated_at).getTime(); return { id: data.updated_at, summary: data.subject.title, ts, }; }, }, async run() { const since = this.db.get("since"); const notifications = await this.getFilteredNotifications( { participating: false, since, }, "security_alert", ); let maxDate = since; for (const notification of notifications) { if (!maxDate || new Date(notification.updated_at) > new Date(maxDate)) { maxDate = notification.updated_at; } const meta = this.generateMeta(notification); this.$emit(notification, meta); } if (maxDate !== since) { this.db.set("since", maxDate); } }, }; <|start_filename|>components/threads/actions/delete-thread/delete-thread.js<|end_filename|> const threads = require("../../threads.app.js"); module.exports = { key: "threads-delete-thread", name: "Delete a Thread", description: "Delete a thread", version: "0.0.1", type: "action", props: { threads, threadID: { propDefinition: [ threads, "threadID", ], }, }, async run() { return await this.threads.deleteThread({ threadID: this.threadID, }); }, }; <|start_filename|>components/hubspot/sources/new-contact-in-list/new-contact-in-list.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, key: "hubspot-new-contact-in-list", name: "New Contact in List", description: "Emits an event for each new contact in a list.", version: "0.0.2", dedupe: "unique", props: { ...common.props, lists: { propDefinition: [common.props.hubspot, "lists"] }, }, methods: { ...common.methods, generateMeta(contact, list) { const { vid, properties } = contact; const { value, label } = list; return { id: `${vid}${value}`, summary: `${properties.firstname.value} ${properties.lastname.value} added to ${label}`, ts: Date.now(), }; }, async emitEvent(contact, properties, list) { const contactInfo = await this.hubspot.getContact( contact.vid, properties ); const meta = this.generateMeta(contact, list); this.$emit({ contact, contactInfo }, meta); }, }, async run(event) { const properties = this.db.get("properties"); for (let list of this.lists) { list = JSON.parse(list); const params = { count: 100, }; let hasMore = true; while (hasMore) { const results = await this.hubspot.getListContacts(params, list.value); hasMore = results["has-more"]; if (hasMore) params.vidOffset = results["vid-offset"]; for (const contact of results.contacts) { await this.emitEvent(contact, properties, list); } } } }, }; <|start_filename|>components/clickup/actions/common.js<|end_filename|> const clickup = require("../clickup.app.js"); module.exports = { props: { clickup, workspace: { propDefinition: [ clickup, "workspace", ], }, space: { propDefinition: [ clickup, "space", (c) => ({ workspace: c.workspace, }), ], }, folder: { propDefinition: [ clickup, "folder", (c) => ({ space: c.space, }), ], }, priority: { propDefinition: [ clickup, "priority", ], }, }, }; <|start_filename|>components/google_drive/actions/language-codes.js<|end_filename|> module.exports = [ { label: "Undetected", value: "und", }, { label: "Abkhazian", value: "ab", }, { label: "Afar", value: "aa", }, { label: "Afrikaans", value: "af", }, { label: "Akan", value: "ak", }, { label: "Albanian", value: "sq", }, { label: "Amharic", value: "am", }, { label: "Arabic", value: "ar", }, { label: "Aragonese", value: "an", }, { label: "Armenian", value: "hy", }, { label: "Assamese", value: "as", }, { label: "Avaric", value: "av", }, { label: "Avestan", value: "ae", }, { label: "Aymara", value: "ay", }, { label: "Azerbaijani", value: "az", }, { label: "Bambara", value: "bm", }, { label: "Bashkir", value: "ba", }, { label: "Basque", value: "eu", }, { label: "Belarusian", value: "be", }, { label: "Bengali", value: "bn", }, { label: "Bihari languages", value: "bh", }, { label: "Bislama", value: "bi", }, { label: "Bokmål, Norwegian; Norwegian Bokmål", value: "nb", }, { label: "Bosnian", value: "bs", }, { label: "Breton", value: "br", }, { label: "Bulgarian", value: "bg", }, { label: "Burmese", value: "my", }, { label: "Catalan; Valencian", value: "ca", }, { label: "Central Khmer", value: "km", }, { label: "Chamorro", value: "ch", }, { label: "Chechen", value: "ce", }, { label: "Chichewa; Chewa; Nyanja", value: "ny", }, { label: "Chinese", value: "zh", }, { label: "Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic", value: "cu", }, { label: "Chuvash", value: "cv", }, { label: "Cornish", value: "kw", }, { label: "Corsican", value: "co", }, { label: "Cree", value: "cr", }, { label: "Croatian", value: "hr", }, { label: "Czech", value: "cs", }, { label: "Danish", value: "da", }, { label: "Divehi; Dhivehi; Maldivian", value: "dv", }, { label: "Dutch; Flemish", value: "nl", }, { label: "Dzongkha", value: "dz", }, { label: "English", value: "en", }, { label: "Esperanto", value: "eo", }, { label: "Estonian", value: "et", }, { label: "Ewe", value: "ee", }, { label: "Faroese", value: "fo", }, { label: "Fijian", value: "fj", }, { label: "Finnish", value: "fi", }, { label: "French", value: "fr", }, { label: "Fulah", value: "ff", }, { label: "Gaelic; Scottish Gaelic", value: "gd", }, { label: "Galician", value: "gl", }, { label: "Ganda", value: "lg", }, { label: "Georgian", value: "ka", }, { label: "German", value: "de", }, { label: "Greek, Modern (1453-)", value: "el", }, { label: "Guarani", value: "gn", }, { label: "Gujarati", value: "gu", }, { label: "Haitian; Haitian Creole", value: "ht", }, { label: "Hausa", value: "ha", }, { label: "Hebrew", value: "he", }, { label: "Herero", value: "hz", }, { label: "Hindi", value: "hi", }, { label: "<NAME>", value: "ho", }, { label: "Hungarian", value: "hu", }, { label: "Icelandic", value: "is", }, { label: "Ido", value: "io", }, { label: "Igbo", value: "ig", }, { label: "Indonesian", value: "id", }, { label: "Interlingua (International Auxiliary Language Association)", value: "ia", }, { label: "Interlingue; Occidental", value: "ie", }, { label: "Inuktitut", value: "iu", }, { label: "Inupiaq", value: "ik", }, { label: "Irish", value: "ga", }, { label: "Italian", value: "it", }, { label: "Japanese", value: "ja", }, { label: "Javanese", value: "jv", }, { label: "Kalaallisut; Greenlandic", value: "kl", }, { label: "Kannada", value: "kn", }, { label: "Kanuri", value: "kr", }, { label: "Kashmiri", value: "ks", }, { label: "Kazakh", value: "kk", }, { label: "Kikuyu; Gikuyu", value: "ki", }, { label: "Kinyarwanda", value: "rw", }, { label: "Kirghiz; Kyrgyz", value: "ky", }, { label: "Komi", value: "kv", }, { label: "Kongo", value: "kg", }, { label: "Korean", value: "ko", }, { label: "Kuanyama; Kwanyama", value: "kj", }, { label: "Kurdish", value: "ku", }, { label: "Lao", value: "lo", }, { label: "Latin", value: "la", }, { label: "Latvian", value: "lv", }, { label: "Limburgan; Limburger; Limburgish", value: "li", }, { label: "Lingala", value: "ln", }, { label: "Lithuanian", value: "lt", }, { label: "Luba-Katanga", value: "lu", }, { label: "Luxembourgish; Letzeburgesch", value: "lb", }, { label: "Macedonian", value: "mk", }, { label: "Malagasy", value: "mg", }, { label: "Malay", value: "ms", }, { label: "Malayalam", value: "ml", }, { label: "Maltese", value: "mt", }, { label: "Manx", value: "gv", }, { label: "Maori", value: "mi", }, { label: "Marathi", value: "mr", }, { label: "Marshallese", value: "mh", }, { label: "Mongolian", value: "mn", }, { label: "Nauru", value: "na", }, { label: "Navajo; Navaho", value: "nv", }, { label: "Ndebele, North; North Ndebele", value: "nd", }, { label: "Ndebele, South; South Ndebele", value: "nr", }, { label: "Ndonga", value: "ng", }, { label: "Nepali", value: "ne", }, { label: "Northern Sami", value: "se", }, { label: "Norwegian", value: "no", }, { label: "Norwegian Nynorsk; Nynorsk, Norwegian", value: "nn", }, { label: "Occitan (post 1500)", value: "oc", }, { label: "Ojibwa", value: "oj", }, { label: "Oriya", value: "or", }, { label: "Oromo", value: "om", }, { label: "Ossetian; Ossetic", value: "os", }, { label: "Pali", value: "pi", }, { label: "Panjabi; Punjabi", value: "pa", }, { label: "Persian", value: "fa", }, { label: "Polish", value: "pl", }, { label: "Portuguese", value: "pt", }, { label: "Pushto; Pashto", value: "ps", }, { label: "Quechua", value: "qu", }, { label: "Romanian; Moldavian; Moldovan", value: "ro", }, { label: "Romansh", value: "rm", }, { label: "Rundi", value: "rn", }, { label: "Russian", value: "ru", }, { label: "Samoan", value: "sm", }, { label: "Sango", value: "sg", }, { label: "Sanskrit", value: "sa", }, { label: "Sardinian", value: "sc", }, { label: "Serbian", value: "sr", }, { label: "Shona", value: "sn", }, { label: "<NAME>; Nuosu", value: "ii", }, { label: "Sindhi", value: "sd", }, { label: "Sinhala; Sinhalese", value: "si", }, { label: "Slovak", value: "sk", }, { label: "Slovenian", value: "sl", }, { label: "Somali", value: "so", }, { label: "Sotho, Southern", value: "st", }, { label: "Spanish; Castilian", value: "es", }, { label: "Sundanese", value: "su", }, { label: "Swahili", value: "sw", }, { label: "Swati", value: "ss", }, { label: "Swedish", value: "sv", }, { label: "Tagalog", value: "tl", }, { label: "Tahitian", value: "ty", }, { label: "Tajik", value: "tg", }, { label: "Tamil", value: "ta", }, { label: "Tatar", value: "tt", }, { label: "Telugu", value: "te", }, { label: "Thai", value: "th", }, { label: "Tibetan", value: "bo", }, { label: "Tigrinya", value: "ti", }, { label: "Tonga (Tonga Islands)", value: "to", }, { label: "Tsonga", value: "ts", }, { label: "Tswana", value: "tn", }, { label: "Turkish", value: "tr", }, { label: "Turkmen", value: "tk", }, { label: "Twi", value: "tw", }, { label: "Uighur; Uyghur", value: "ug", }, { label: "Ukrainian", value: "uk", }, { label: "Urdu", value: "ur", }, { label: "Uzbek", value: "uz", }, { label: "Venda", value: "ve", }, { label: "Vietnamese", value: "vi", }, { label: "Volapük", value: "vo", }, { label: "Walloon", value: "wa", }, { label: "Welsh", value: "cy", }, { label: "Western Frisian", value: "fy", }, { label: "Wolof", value: "wo", }, { label: "Xhosa", value: "xh", }, { label: "Yiddish", value: "yi", }, { label: "Yoruba", value: "yo", }, { label: "Zhuang; Chuang", value: "za", }, { label: "Zulu", value: "zu", }, ]; <|start_filename|>components/textlocal/sources/new-contact/new-contact.js<|end_filename|> const common = require("../common/timer-based"); module.exports = { ...common, key: "textlocal-new-contact", name: "New Contact", version: "0.0.1", dedupe: "unique", props: { ...common.props, groupId: { type: "string", label: "Contact Group", description: "The contact group to monitor for new contacts", async options(context) { const { page } = context; if (page !== 0) { return []; } const { groups } = await this.textlocal.getContactGroups(); const options = groups.map((group) => ({ label: group.name, value: group.id, })); return { options, }; }, }, }, hooks: { ...common.hooks, deactivate() { this.db.set("isInitialized", false); }, }, methods: { ...common.methods, _isContactProcessed(contact) { const { number } = contact; return Boolean(this.db.get(number)); }, _markContactAsProcessed(contact) { const { number } = contact; this.db.set(number, true); }, async takeContactGroupSnapshot() { const contactScan = await this.textlocal.scanContactGroup({ groupId: this.groupId, }); for await (const contact of contactScan) { this._markContactAsProcessed(contact); } }, generateMeta({ contact, ts, }) { const { number, first_name: firstName, last_name: lastName, } = contact; const maskedName = this.getMaskedName({ firstName, lastName, }); const maskedNumber = this.getMaskedNumber(number); const summary = `New contact: ${maskedName} (${maskedNumber})`; return { id: number, summary, ts, }; }, async processEvent(event) { const isInitialized = this.db.get("isInitialized"); if (!isInitialized) { await this.takeContactGroupSnapshot(); this.db.set("isInitialized", true); return; } const { timestamp: ts } = event; const contactScan = await this.textlocal.scanContactGroup({ groupId: this.groupId, }); for await (const contact of contactScan) { if (this._isContactProcessed(contact)) { continue; } const meta = this.generateMeta({ contact, ts, }); this.$emit(contact, meta); this._markContactAsProcessed(contact); } }, }, }; <|start_filename|>components/ahrefs/ahrefs.app.js<|end_filename|> module.exports = { type: "app", app: "ahrefs", propDefinitions: { limit: { type: "integer", description: "Number of results to return.", default: 1000, optional: true, }, mode: { type: "string", description: "Select a mode of operation (defaults to `Domain`).", options: [ { label: 'Exact', value: 'exact' }, { label: 'Domain', value: 'domain' }, { label: 'Subdomain', value: 'subdomains' }, { label: 'Prefix', value: 'prefix' }, ], default: 'domain', optional: true, }, target: { type: "string", description: "Enter a domain or URL.", }, } } <|start_filename|>components/bitbucket/sources/new-repository/new-repository.js<|end_filename|> const common = require("../../common"); const watchWorkspace = require("../new-workspace-event/new-workspace-event"); const EVENT_SOURCE_NAME = "New Repository (Instant)"; module.exports = { ...watchWorkspace, name: EVENT_SOURCE_NAME, key: "bitbucket-new-repository", description: "Emits an event when a repository is created.", version: "0.0.1", props: { ...common.props, }, methods: { ...watchWorkspace.methods, getEventSourceName() { return EVENT_SOURCE_NAME; }, getHookEvents() { return [ "repo:created", ]; }, generateMeta(data) { const { headers, body } = data; const { "x-request-uuid": id, "x-event-time": eventDate, } = headers; const { full_name: repositoryName, } = body.repository; const summary = `New repository created: ${repositoryName}`; const ts = +new Date(eventDate); return { id, summary, ts, }; }, }, }; <|start_filename|>components/ongage/ongage.app.js<|end_filename|> const axios = require("axios"); const Ongage = require("ongage"); module.exports = { type: "app", app: "ongage", methods: { _ongage (client) { return new Ongage[client]( this.$auth.x_username, this.$auth.x_password, this.$auth.x_account_code, ); }, async _execute ({ body, ...config }) { if (body) config.data = body; const res = await axios(config); return res.data; }, async getLists (page) { const api = this._ongage("ListsApi"); const req = api.getAll({ sort: "name", order: "ASC", limit: 50, offset: 50 * page, }); return await this._execute(req); }, async subscribe (listId, email, fields = {}, overwrite = false) { const api = this._ongage("ContactsApi"); const req = api.create({ email, overwrite, fields, }, listId); return await this._execute(req); }, async updateSubscriber (listId, email, fields = {}) { const api = this._ongage("ContactsApi"); const req = api.update({ email, fields, }, listId); return await this._execute(req); }, async findSubscriber (email) { const api = this._ongage("ContactsApi"); const req = api.getListsByEmail(email); return await this._execute(req); }, }, propDefinitions: { listId: { type: "string", label: "List ID", async options ({ page }) { const { payload } = await this.getLists(page); return payload.map(list => ({ label: list.name, value: list.id, })); }, }, overwrite: { type: "boolean", label: "Overwrite?", default: false, description: "Whether to overwrite the specified fields if the subscriber already exists. Only the fields specified will be overwritten. For more information, see the [Ongage API documentation](https://ongage.atlassian.net/wiki/spaces/HELP/pages/1004175381/Contacts+API+Methods#ContactsAPIMethods-Description.3)", }, haltOnError: { type: "boolean", label: "Halt on error?", default: true, }, email: { type: "string", label: "Email Address", }, fields: { type: "object", label: "List Fields", }, }, }; <|start_filename|>components/eventbrite/sources/common/event.js<|end_filename|> const common = require("./webhook.js"); module.exports = { ...common, methods: { ...common.methods, generateMeta({ id, name, created }) { return { id, summary: name.text, ts: Date.parse(created), }; }, }, }; <|start_filename|>components/firebase_admin_sdk/sources/new-child-object/new-child-object.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, key: "firebase_admin_sdk-new-child-object", name: "New Child Object in a Realtime Database", description: "Emits an event when a new child object is discovered within a specific path", version: "0.0.1", dedupe: "unique", props: { ...common.props, path: { propDefinition: [ common.props.firebase, "path", ], }, }, methods: { ...common.methods, async processEvent(event) { const { timestamp } = event; const ref = this.firebase.getApp().database() .ref(this.path); const snapshot = await ref.get(); const children = snapshot.val() || {}; for (const [ key, value, ] of Object.entries(children)) { const meta = this.generateMeta(key, timestamp); const child = { [key]: value, }; this.$emit(child, meta); } }, generateMeta(key, timestamp) { return { id: key, summary: `New child object: ${key}`, ts: timestamp, }; }, }, }; <|start_filename|>components/twitch/twitch.app.js<|end_filename|> const axios = require("axios"); const crypto = require("crypto"); const qs = require("qs"); module.exports = { type: "app", app: "twitch", propDefinitions: { streamerLoginNames: { type: "string[]", label: "Streamer Login Names", description: "Enter the login names of the streamers whose streams you want to watch.", }, game: { type: "string", label: "Game Title", description: "Watch for live streams about the specified game.", }, language: { type: "string", label: "Stream Language", description: "Watch for games streamed in the specified language. A language value must be either the ISO 639-1 two-letter code for a supported stream language or \"other\".", }, max: { type: "integer", label: "Max Items", description: "The maximum number of items to return at one time. Streams are returned sorted by number of viewers, in descending order. Videos and Clips are returned sorted by publish date.", min: 1, }, user: { type: "string", label: "User ID", }, broadcaster: { type: "string", label: "Broadcaster Id", }, }, methods: { _getBaseUrl() { return "https://api.twitch.tv/helix"; }, _getHeaders() { return { "Authorization": `Bearer ${this.$auth.oauth_access_token}`, "client-id": this.$auth.oauth_client_id, "Content-Type": "application/json", }; }, _getParamsSerializer() { return (p) => qs.stringify(p, { arrayFormat: "repeat", }); }, async _makeRequest(method, endpoint, params = {}) { const config = { method, url: `${this._getBaseUrl()}/${endpoint}`, headers: this._getHeaders(), params, paramsSerializer: this._getParamsSerializer(params), }; return await axios(config); }, // Uses Twitch API to create or delete webhook subscriptions. // Set mode to "subscribe" to create a webhook and "unsubscribe" to delete it. async manageHook(mode, url, topic, leaseSeconds, secretToken) { const data = { "hub.callback": url, "hub.mode": mode, "hub.topic": `${this._getBaseUrl()}/${topic}`, "hub.lease_seconds": leaseSeconds, "hub.secret": secretToken, }; return await this._makeRequest("POST", "webhooks/hub", data); }, verifyWebhookRequest(headers, bodyRaw, secretToken) { const [ algorithm, expectedHash, ] = headers["x-hub-signature"].split("="); const hash = crypto .createHmac(algorithm, secretToken) .update(bodyRaw) .digest("hex"); return expectedHash == hash; }, async blockUser(params) { return await this._makeRequest("PUT", "users/blocks", params); }, async checkUserSubscription(params) { return await this._makeRequest("GET", "subscriptions/user", params); }, async deleteVideo(params) { return await this._makeRequest("DELETE", "videos", params); }, async getBroadcasterSubscriptions(params) { return await this._makeRequest("GET", "subscriptions", params); }, async getChannelEditors(params) { return await this._makeRequest("GET", "channels/editors", params); }, async getChannelInformation(params) { return await this._makeRequest("GET", "channels", params); }, async getChannelTeams(params) { return await this._makeRequest("GET", "teams/channel", params); }, async getClips(params) { return await this._makeRequest("GET", "clips", params); }, async getEmoteSets(params) { return await this._makeRequest("GET", "chat/emotes/set", params); }, async getGames(name = []) { let endpoint = "games"; const params = { name, }; return (await this._makeRequest("GET", encodeURI(endpoint), params)).data; }, async getMultipleUsers(params) { return await this._makeRequest("GET", "users", params); }, // gets all live streams that match the given parameters async getStreams(params) { return await this._makeRequest("GET", "streams", params); }, async getTopGames() { return await this._makeRequest("GET", "games/top"); }, async getUsers(login = []) { let endpoint = "users"; const params = { login, }; return (await this._makeRequest("GET", encodeURI(endpoint), params)).data; }, async getUserFollows(params) { return await this._makeRequest("GET", "users/follows", params); }, async getVideos(params) { return await this._makeRequest("GET", "videos", params); }, async searchChannels(params) { return await this._makeRequest("GET", "search/channels", params); }, async searchGames(params) { return await this._makeRequest("GET", "search/categories", params); }, async unblockUser(params) { return await this._makeRequest("DELETE", "users/blocks", params); }, async updateChannel(params) { return await this._makeRequest("PATCH", "channels", params); }, }, }; <|start_filename|>components/airtable/actions/common.js<|end_filename|> const airtable = require("../airtable.app.js"); module.exports = { props: { airtable, baseId: { type: "$.airtable.baseId", appProp: "airtable", }, tableId: { type: "$.airtable.tableId", baseIdProp: "baseId", }, }, }; <|start_filename|>components/slack/actions/complete-reminder/complete-reminder.js<|end_filename|> const slack = require("../../slack.app.js"); module.exports = { key: "slack-complete-reminder", name: "Complete Reminder", description: "Complete a reminder", version: "0.0.1", type: "action", props: { slack, reminder: { propDefinition: [ slack, "reminder", ], }, }, async run() { return await this.slack.sdk().reminders.complete({ reminder: this.reminder, }); }, }; <|start_filename|>components/twitch/actions/get-videos/get-videos.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, name: "Get Videos", key: "twitch-get-videos", description: "Gets video information by video ID, user ID, or game ID", version: "0.0.1", type: "action", props: { ...common.props, id: { type: "string", label: "Video ID", description: `ID of the video being queried. If this is specified, you cannot use any of the optional query parameters below. Each request must specify one video id, one user_id, or one game_id.`, optional: true, }, userId: { propDefinition: [ common.props.twitch, "user", ], description: "ID of the user who owns the video. Each request must specify one video id, one user_id, or one game_id", optional: true, }, gameId: { type: "string", label: "Game ID", description: "ID of the game the video is of. Each request must specify one video id, one user_id, or one game_id.", optional: true, }, language: { propDefinition: [ common.props.twitch, "language", ], description: "Language of the video being queried. A language value must be either the ISO 639-1 two-letter code for a supported stream language or “other”.", optional: true, }, period: { type: "string", label: "Period", description: "Period during which the video was created. Defaults to “all” if left blank", options: [ "all", "day", "week", "month", ], optional: true, }, sort: { type: "string", label: "Sort", description: "Sort order of the videos. Defaults to “time” if left blank", options: [ "time", "trending", "views", ], optional: true, }, type: { type: "string", label: "Type", description: "Type of video. Defaults to “all” if left blank", options: [ "all", "upload", "archive", "highlight", ], optional: true, }, max: { propDefinition: [ common.props.twitch, "max", ], description: "Maximum number of videos to return", }, }, async run() { let params = { id: this.id, user_id: this.userId, game_id: this.gameId, language: this.language, period: this.period, sort: this.sort, type: this.type, }; // remove empty values from params Object.keys(params).forEach((k) => (params[k] == null || params[k] == "") && delete params[k]); const videos = await this.paginate( this.twitch.getVideos.bind(this), params, this.max, ); return await this.getPaginatedResults(videos); }, }; <|start_filename|>components/stack_exchange/sources/new-answers-for-questions/new-answers-for-questions.js<|end_filename|> const stack_exchange = require('../../stack_exchange.app'); module.exports = { key: "stack_exchange-new-answers-for-questions", name: "New Answers for Specific Questions", description: "Emits an event when a new answer is posted in one of the specified questions", version: "0.0.1", dedupe: "unique", props: { stack_exchange, db: "$.service.db", siteId: { propDefinition: [stack_exchange, "siteId"] }, questionIds: { propDefinition: [ stack_exchange, "questionIds", c => ({ siteId: c.siteId }), ], }, timer: { type: '$.interface.timer', default: { intervalSeconds: 60 * 15, // 15 minutes }, }, }, hooks: { async activate() { const fromDate = this._getCurrentEpoch(); this.db.set("fromDate", fromDate); }, }, methods: { _getCurrentEpoch() { // The StackExchange API works with Unix epochs in seconds. return Math.floor(Date.now() / 1000); }, generateMeta(data) { const { answer_id: id, question_id: questionId, creation_date: ts, } = data; const summary = `New answer for question ID ${questionId}`; return { id, summary, ts, }; }, }, async run() { const fromDate = this.db.get("fromDate"); const toDate = this._getCurrentEpoch(); const filter = '!SWKA(ozr4ec2cHE9JK'; // See https://api.stackexchange.com/docs/filters const searchParams = { fromDate, toDate, filter, sort: 'creation', order: 'asc', site: this.siteId, } const items = this.stack_exchange.answersForQuestions(this.questionIds, searchParams); for await (const item of items) { const meta = this.generateMeta(item); this.$emit(item, meta); } this.db.set("fromDate", toDate); }, }; <|start_filename|>components/snowflake/sources/common-table-scan.js<|end_filename|> const isString = require("lodash/isString"); const common = require("./common"); module.exports = { ...common, props: { ...common.props, tableName: { type: "string", label: "Table Name", description: "The name of the table to watch for new rows", async options(context) { const { page } = context; if (page !== 0) { return []; } const options = await this.snowflake.listTables(); return options.map(i => i.name); }, }, uniqueKey: { type: "string", label: "Unique Key", description: "The name of a column in the table to use for deduplication. Defaults to `ID`", default: "ID", async options(context) { const { page } = context; if (page !== 0) { return []; } const options = await this.snowflake.listFieldsForTable(this.tableName); return options.map(i => i.name); }, }, }, hooks: { ...common.hooks, async activate() { await this.validateColumn(this.uniqueKey); let lastResultId = this.db.get("lastResultId"); if (lastResultId === undefined) { lastResultId = await this._getLastId(); this.db.set("lastResultId", lastResultId); } console.log(` Starting scan of table "${this.tableName}" from ${this.uniqueKey}=${lastResultId} `); }, }, methods: { ...common.methods, /** * Utility method to make sure that a certain column exists in the target * table. Useful for SQL query sanitizing. * * @param {string} columnNameToValidate The name of the column to validate * for existence */ async validateColumn(columnNameToValidate) { if (!isString(columnNameToValidate)) { throw new Error("columnNameToValidate must be a string"); } const columns = await this.snowflake.listFieldsForTable(this.tableName); const columnNames = columns.map(i => i.name); if (!columnNames.includes(columnNameToValidate)) { throw new Error(`Inexistent column: ${columnNameToValidate}`); } }, generateMeta(data) { const { row: { [this.uniqueKey]: id, }, timestamp: ts, } = data; const summary = `New row: ${id}`; return { id, summary, ts, }; }, generateMetaForCollection(data) { const { lastResultId: id, rowCount, timestamp: ts, } = data; const entity = rowCount === 1 ? "row" : "rows"; const summary = `${rowCount} new ${entity}`; return { id, summary, ts, }; }, async _getLastId() { const sqlText = ` SELECT ${this.uniqueKey} FROM IDENTIFIER(:1) ORDER BY ${this.uniqueKey} DESC LIMIT 1 `; const binds = [ this.tableName, this.uniqueKey, ]; const statement = { sqlText, binds, }; const rowStream = await this.snowflake.getRows(statement); for await (const row of rowStream) { return row[this.uniqueKey]; } return 0; }, }, async run(event) { const prevLastResultId = this.db.get("lastResultId"); const statement = await this.getStatement(prevLastResultId); const { timestamp } = event; const { lastResultId = prevLastResultId, } = (this.eventSize === 1) ? await this.processSingle(statement, timestamp) : await this.processCollection(statement, timestamp); this.db.set("lastResultId", lastResultId); }, }; <|start_filename|>components/discord_webhook/actions/send-message-advanced/send-message-advanced.js<|end_filename|> const discordWebhook = require("../../discord_webhook.app.js"); module.exports = { key: "discord_webhook-send-message-advanced", name: "Send Message (Advanced)", description: "Send a simple or structured message (using embeds) to a Discord channel", version: "0.1.4", type: "action", props: { discordWebhook, message: { propDefinition: [ discordWebhook, "message", ], optional: true, }, threadID: { propDefinition: [ discordWebhook, "threadID", ], }, embeds: { propDefinition: [ discordWebhook, "embeds", ], }, username: { propDefinition: [ discordWebhook, "username", ], }, avatarURL: { propDefinition: [ discordWebhook, "avatarURL", ], }, }, async run() { const content = this.message; const { avatarURL, embeds, threadID, username, } = this; if (!content && !embeds) { throw new Error("This action requires at least 1 message OR embeds object. Please enter one or the other above."); } // No interesting data is returned from Discord await this.discordWebhook.sendMessage({ avatarURL, embeds, content, threadID, username, }); }, }; <|start_filename|>interfaces/http/examples/http-hello-world.js<|end_filename|> module.exports = { name: "http", version: "0.0.2", props: { http: { type: "$.interface.http", customResponse: true, }, }, async run(event) { this.http.respond({ status: 200, body: "Hello world!", }); // Emit the whole event, which contains // the HTTP payload, headers, and more this.$emit(event); }, }; <|start_filename|>components/airtable/actions/get-record/get-record.js<|end_filename|> const airtable = require("../../airtable.app.js"); const common = require("../common.js"); module.exports = { key: "airtable-get-record", name: "Get Record", description: "Get a record from a table by record ID.", version: "0.1.0", type: "action", props: { ...common.props, recordId: { propDefinition: [ airtable, "recordId", ], }, }, async run() { this.airtable.validateRecordID(this.recordId); const base = this.airtable.base(this.baseId); try { return await base(this.tableId).find(this.recordId); } catch (err) { this.airtable.throwFormattedError(err); } }, }; <|start_filename|>components/hubspot/sources/new-deal-in-stage/new-deal-in-stage.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, key: "hubspot-new-deal-in-stage", name: "New Deal In Stage", description: "Emits an event for each new deal in a stage.", version: "0.0.2", dedupe: "unique", hooks: {}, props: { ...common.props, stages: { propDefinition: [common.props.hubspot, "stages"] }, }, methods: { ...common.methods, generateMeta(deal, stage) { const { id, properties, updatedAt } = deal; const { label } = stage; const ts = Date.parse(updatedAt); return { id: `${id}${properties.dealstage}`, summary: `${properties.dealname} ${label}`, ts, }; }, emitEvent(deal) { const stage = this.db.get("stage"); const meta = this.generateMeta(deal, stage); this.$emit(deal, meta); }, isRelevant(deal, updatedAfter) { return Date.parse(deal.updatedAt) > updatedAfter; }, }, async run(event) { const updatedAfter = this._getAfter(); for (let stage of this.stages) { stage = JSON.parse(stage); this.db.set("stage", stage); const data = { limit: 100, filters: [ { propertyName: "dealstage", operator: "EQ", value: stage.value, }, ], sorts: [ { propertyName: "lastmodifieddate", direction: "DESCENDING", }, ], object: "deals", }; await this.paginate( data, this.hubspot.searchCRM.bind(this), "results", updatedAfter ); } this._setAfter(Date.now()); }, }; <|start_filename|>components/bitbucket/common.js<|end_filename|> const bitbucket = require("./bitbucket.app"); module.exports = { dedupe: "unique", props: { bitbucket, db: "$.service.db", http: { type: "$.interface.http", customResponse: true, }, workspaceId: { propDefinition: [bitbucket, "workspaceId"] }, }, hooks: { async activate() { const hookParams = this._getHookParams(); const hookPathProps = this.getHookPathProps(); const opts = { hookParams, hookPathProps, }; const { hookId } = await this.bitbucket.createHook(opts); console.log( `Created webhook for ${JSON.stringify(hookPathProps)}. Hook parameters: ${JSON.stringify(hookParams)}. (Hook ID: ${hookId}, endpoint: ${hookParams.url})` ); this.db.set("hookId", hookId); }, async deactivate() { const hookId = this.db.get("hookId"); const hookPathProps = this.getHookPathProps(); const opts = { hookId, hookPathProps, }; await this.bitbucket.deleteHook(opts); console.log( `Deleted webhook for ${JSON.stringify(hookPathProps)}. (Hook ID: ${hookId})` ); }, }, methods: { _isValidSource(headers, db) { const hookId = headers["x-hook-uuid"]; const expectedHookId = db.get("hookId"); return hookId === expectedHookId; }, _getHookParams() { const eventSourceName = this.getEventSourceName(); const hookDescription = `Pipedream - ${eventSourceName}`; const hookEvents = this.getHookEvents(); return { description: hookDescription, url: this.http.endpoint, active: true, events: hookEvents, }; }, async processEvent(event) { const { body } = event; const meta = this.generateMeta(event); this.$emit(body, meta); }, }, async run(event) { const { headers } = event; // Reject any calls not made by the proper BitBucket webhook. if (!this._isValidSource(headers, this.db)) { this.http.respond({ status: 404, }); return; } // Acknowledge the event back to BitBucket. this.http.respond({ status: 200, }); return await this.processEvent(event); }, }; <|start_filename|>components/shopify/shopify.app.js<|end_filename|> const get = require("lodash.get"); const Shopify = require("shopify-api-node"); const toPath = require("lodash/toPath"); const retry = require("async-retry"); const events = [ { label: "Article Created", value: JSON.stringify({ filter: "Article", verb: "create", }), }, { label: "Article Destroyed", value: JSON.stringify({ filter: "Article", verb: "destroy", }), }, { label: "Article Published", value: JSON.stringify({ filter: "Article", verb: "published", }), }, { label: "Article Unpublished", value: JSON.stringify({ filter: "Article", verb: "unpublished", }), }, { label: "Article Updated", value: JSON.stringify({ filter: "Article", verb: "update", }), }, { label: "Blog Created", value: JSON.stringify({ filter: "Blog", verb: "create", }), }, { label: "Blog Destroyed", value: JSON.stringify({ filter: "Blog", verb: "destroy", }), }, { label: "Collection Created", value: JSON.stringify({ filter: "Collection", verb: "create", }), }, { label: "Collection Destroyed", value: JSON.stringify({ filter: "Collection", verb: "destroy", }), }, { label: "Collection Published", value: JSON.stringify({ filter: "Collection", verb: "published", }), }, { label: "Collection Unpublished", value: JSON.stringify({ filter: "Collection", verb: "unpublished", }), }, { label: "Order Confirmed", value: JSON.stringify({ filter: "Order", verb: "confirmed", }), }, { label: "Page Created", value: JSON.stringify({ filter: "Page", verb: "create", }), }, { label: "Page Destroyed", value: JSON.stringify({ filter: "Page", verb: "destroy", }), }, { label: "Page Published", value: JSON.stringify({ filter: "Page", verb: "published", }), }, { label: "Page Unpublished", value: JSON.stringify({ filter: "Page", verb: "unpublished", }), }, { label: "Price Rule Created", value: JSON.stringify({ filter: "PriceRule", verb: "create", }), }, { label: "Price Rule Destroyed", value: JSON.stringify({ filter: "PriceRule", verb: "destroy", }), }, { label: "Price Rule Updated", value: JSON.stringify({ filter: "PriceRule", verb: "update", }), }, { label: "Product Created", value: JSON.stringify({ filter: "Product", verb: "create", }), }, { label: "Product Destroyed", value: JSON.stringify({ filter: "Product", verb: "destroy", }), }, { label: "Product Published", value: JSON.stringify({ filter: "Product", verb: "published", }), }, { label: "Product Unpublished", value: JSON.stringify({ filter: "Product", verb: "unpublished", }), }, ]; module.exports = { type: "app", app: "shopify", propDefinitions: { eventTypes: { type: "string[]", label: "Event Types", optional: true, description: "Only emit events for the selected event types.", options: events, }, }, methods: { _getBaseURL() { return `https://${this.$auth.shop_id}.myshopify.com/admin/api/2020-10`; }, _getAuthHeader() { return { "x-shopify-access-token": this.$auth.oauth_access_token, }; }, _monthAgo() { const now = new Date(); const monthAgo = new Date(now.getTime()); monthAgo.setMonth(monthAgo.getMonth() - 1); return monthAgo; }, _jsonPathToGraphQl(path) { return toPath(path).reduceRight( (accum, item) => accum ? `${item} { ${accum} }` : item, ); }, /** * Returns if an error code represents a retriable error. * @callback isRetriableErrCode * @param {string} errCode The error code * @returns {boolean} If the error code is retriable */ /** * Returns if a GraphQL error code represents a retriable error. * @type {isRetriableErrCode} */ _isRetriableGraphQLErrCode(errCode) { return errCode === "THROTTLED"; }, /** * Options for handling error objects returned by API calls. * @typedef {Object} ErrorOptions * @property {(string|number)[]|string} errCodePath Path to the status/error * code in the error object * @property {(string|number)[]|string} errDataPath Path to the error data * in the error object * @property {isRetriableErrCode} isRetriableErrCode Function that returns if * the error code is retriable */ /** * Returns options for handling GraphQL error objects. * @returns {ErrorOptions} The options */ _graphQLErrOpts() { // Shopify GraphQL requests are throttled if queries exceed point limit. // See https://shopify.dev/concepts/about-apis/rate-limits // GraphQL err: { extensions: { code='THROTTLED' }, response: { body: { errors: [] } } } return { errCodePath: [ "extensions", "code", ], errDataPath: [ "response", "body", "errors", "0", ], isRetriableErrCode: this._isRetriableGraphQLErrCode, }; }, /** * * @param {function} apiCall The function that makes the API request * @param {object} opts Options for retrying the API call * @param {ErrorOptions} opts.errOpts Options for handling errors thrown by the API call * @param {object} opts.retryOpts Options for async-retry. See * https://www.npmjs.com/package/async-retry * @returns {Promise} A promise that resolves to the return value of the apiCall */ async _withRetries(apiCall, opts = {}) { const { errOpts: { errCodePath, errDataPath, isRetriableErrCode, } = this._graphQLErrOpts(), retryOpts = { retries: 5, factor: 2, minTimeout: 2000, // In milliseconds }, } = opts; return retry(async (bail, retryCount) => { try { return await apiCall(); } catch (err) { const errCode = get(err, errCodePath); if (!isRetriableErrCode(errCode)) { const errData = get(err, errDataPath, {}); return bail(new Error(` Unexpected error (error code: ${errCode}): ${JSON.stringify(errData, null, 2)} `)); } console.log(` [Attempt #${retryCount}] Temporary error: ${err.message} `); throw err; } }, retryOpts); }, _makeGraphQlRequest(query, variables = {}) { const shopifyClient = this.getShopifyInstance(); return this._withRetries( () => shopifyClient.graphql(query, variables), ); }, dayAgo() { const dayAgo = new Date(); dayAgo.setDate(dayAgo.getDate() - 1); return dayAgo; }, getShopifyInstance() { return new Shopify({ shopName: this.$auth.shop_id, accessToken: this.$auth.oauth_access_token, autoLimit: true, }); }, getSinceParams(sinceId = false, useCreatedAt = false, updatedAfter = null) { let params = {}; if (sinceId) params = { ...params, since_id: sinceId, }; if (updatedAfter) params = { ...params, updated_at_min: updatedAfter, }; // If no sinceId or updatedAfter, get objects created within the last month if (!sinceId && !updatedAfter && useCreatedAt) return { created_at_min: this._monthAgo(), }; return params; }, async getObjects(objectType, params = {}, id = null) { const shopify = this.getShopifyInstance(); let objects = []; do { const results = id ? await shopify[objectType].list(id, params) : await shopify[objectType].list(params); objects = objects.concat(results); params = results.nextPageParameters; } while (params !== undefined); return objects; }, async getAbandonedCheckouts(sinceId) { let params = this.getSinceParams(sinceId, true); return await this.getObjects("checkout", params); }, async getArticles(blogId, sinceId) { let params = this.getSinceParams(sinceId, true); return await this.getObjects("article", params, blogId); }, async getBlogs() { return await this.getObjects("blog"); }, async getCustomers(sinceId, updatedAfter) { let params = this.getSinceParams(sinceId, true, updatedAfter); return await this.getObjects("customer", params); }, async getEvents(sinceId, filter = null, verb = null) { let params = this.getSinceParams(sinceId, true); params.filter = filter; params.verb = verb; return await this.getObjects("event", params); }, async getOrders(fulfillmentStatus, useCreatedAt = false, sinceId = null, updatedAfter = null, status = "any") { let params = this.getSinceParams(sinceId, useCreatedAt, updatedAfter); params.status = status; params.fulfillment_status = fulfillmentStatus; return await this.getObjects("order", params); }, async getOrdersById(ids = []) { if (ids.length === 0) { return []; } const params = { ids: ids.join(","), status: "any", limit: 100, }; return await this.getObjects("order", params); }, async getPages(sinceId) { let params = this.getSinceParams(sinceId, true); return await this.getObjects("page", params); }, async getProducts(sinceId) { let params = this.getSinceParams(sinceId, true); return await this.getObjects("product", params); }, async *queryOrders(opts = {}) { const { sortKey = "UPDATED_AT", filter = "", fields = [], } = opts; const nodeFields = [ "id", ...fields.map(this._jsonPathToGraphQl), ].join("\n"); const query = ` query orders($after: String, $filter: String, $sortKey: OrderSortKeys) { orders(after: $after, first: 100, query: $filter, sortKey: $sortKey) { pageInfo { hasNextPage } edges { cursor node { ${nodeFields} } } } } `; let { prevCursor: after = null } = opts; while (true) { const variables = { after, filter, sortKey, }; const { orders } = await this._makeGraphQlRequest(query, variables); const { edges = [] } = orders; for (const edge of edges) { const { node: order, cursor, } = edge; yield { order, cursor, }; after = cursor; } if (!orders.pageInfo.hasNextPage) { return; } } }, }, }; <|start_filename|>components/ahrefs/actions/get-referring-domains/get-referring-domains.js<|end_filename|> const ahrefs = require('../../ahrefs.app.js') const axios = require('axios') module.exports = { name: 'Get Referring Domains', description: "Get the referring domains that contain backlinks to the target URL or domain.", key: "ahrefs-get-referring-domains", version: '0.0.16', type: "action", props: { ahrefs, target: { propDefinition: [ahrefs, "target"] }, mode: { propDefinition: [ahrefs, "mode"] }, limit: { propDefinition: [ahrefs, "limit"] }, }, async run() { return (await axios({ url: `https://apiv2.ahrefs.com`, params: { token: this.ahrefs.$auth.oauth_access_token, from: "refdomains", target: this.target, mode: this.mode, limit: this.limit, order_by: "domain_rating:desc", output: "json" }, })).data }, } <|start_filename|>components/twilio/sources/new-incoming-sms/new-incoming-sms.js<|end_filename|> const common = require("../common-webhook.js"); const MessagingResponse = require("twilio").twiml.MessagingResponse; module.exports = { ...common, key: "twilio-new-incoming-sms", name: "New Incoming SMS (Instant)", description: "Configures a webhook in Twilio, tied to an incoming phone number, and emits an event each time an SMS is sent to that number", version: "0.0.5", dedupe: "unique", props: { ...common.props, responseMessage: { propDefinition: [common.props.twilio, "responseMessage"], }, }, methods: { ...common.methods, async setWebhook(...args) { return await this.twilio.setIncomingSMSWebhookURL(...args); }, getResponseBody() { const twiml = new MessagingResponse(); let responseBody = "<Response></Response>"; if (this.responseMessage) { twiml.message(this.responseMessage); responseBody = twiml.toString(); } return responseBody; }, generateMeta(body, headers) { return { /** if Twilio retries a message, but we've already emitted, dedupe */ id: headers["i-twilio-idempotency-token"], summary: body.Body, ts: Date.now(), }; }, }, }; <|start_filename|>components/slack/actions/reply-to-a-message-thread/reply-to-a-message-thread.js<|end_filename|> const slack = require("../../slack.app.js"); module.exports = { key: "slack-reply-to-a-message", name: "Reply to a Message Thread", description: "Send a message as a threaded reply", version: "0.1.0", type: "action", props: { slack, thread_ts: { propDefinition: [ slack, "thread_ts", ], optional: false, }, reply_channel: { propDefinition: [ slack, "reply_channel", ], optional: false, }, text: { propDefinition: [ slack, "text", ], optional: false, }, as_user: { propDefinition: [ slack, "as_user", ], }, username: { propDefinition: [ slack, "username", ], }, icon_emoji: { propDefinition: [ slack, "icon_emoji", ], }, icon_url: { propDefinition: [ slack, "icon_url", ], }, }, async run() { return await this.slack.sdk().chat.postMessage({ text: this.text, channel: this.reply_channel, thread_ts: this.thread_ts, as_user: this.as_user, username: this.username, icon_emoji: this.icon_emoji, icon_url: this.icon_url, }); }, }; <|start_filename|>components/twitter_developer_app/sources/common.js<|end_filename|> const twitter_developer_app = require("../twitter_developer_app.app"); module.exports = { props: { twitter_developer_app, db: "$.service.db", timer: { type: "$.interface.timer", default: { intervalSeconds: 15 * 60, // 15 minutes }, }, }, }; <|start_filename|>components/textlocal/sources/new-sent-api-message/new-sent-api-message.js<|end_filename|> const common = require("../common/timer-based"); module.exports = { ...common, key: "textlocal-new-sent-api-message", name: "New Sent API Message", version: "0.0.1", dedupe: "unique", hooks: { ...common.hooks, async activate() { let latestMessageId = this.db.get("latestMessageId"); if (!latestMessageId) { latestMessageId = await this.textlocal.getLatestMessageId(); this.db.set("latestMessageId", latestMessageId); } console.log(`Starting scanning from message ID: ${latestMessageId}`); }, }, methods: { ...common.methods, generateMeta(message) { const { id, datetime, number, sender, } = message; const maskedNumber = this.getMaskedNumber(number); const summary = `New message from ${sender} to ${maskedNumber}`; const ts = Date.parse(datetime); return { id, summary, ts, }; }, async processEvent() { const latestMessageId = this.db.get("latestMessageId"); const messageScan = await this.textlocal.scanApiMessageHistory({ lowerBoundMessageId: latestMessageId, }); const messages = []; for await (const message of messageScan) { messages.push(message); } if (messages.length === 0) { console.log("No new messages detected. Skipping..."); return; } messages.reverse().forEach((message) => { const meta = this.generateMeta(message); this.$emit(message, meta); }); const newLatestMessageId = Math.max( ...messages.map(({ id }) => id) ).toString(); this.db.set("latestMessageId", newLatestMessageId); }, }, }; <|start_filename|>components/supersaas/utils/makeEventSummary.js<|end_filename|> const dayjs = require('dayjs'); // See: https://www.supersaas.com/info/dev/webhooks module.exports = function makeEventSummary(ev) { const withUserEmail = x => { if (!ev.body.email) { return x; } return `${x} (${ev.body.email})`; }; const withStartDateTime = x => { const start = ev.body.slot ? ev.body.slot.start : ev.body.start; if (!start) { return x; } return `${x} for ${dayjs(start).format('YYYY-MM-DD [at] HH:mm')}`; }; switch (ev.body.event) { // User events: case 'new': return withUserEmail('New user'); case 'change': if (ev.body.deleted) { return withUserEmail('Deleted user'); } return withUserEmail('Changed user'); case 'delete': return withUserEmail('Deleted user'); case 'purchase': return withUserEmail('Purchased credit'); // Appointment events: case 'create': return withStartDateTime('Created an appointment'); break; case 'edit': return withStartDateTime( ev.body.deleted ? 'Deleted an appointment' : 'Changed an appointment', ); case 'destroy': return withStartDateTime('Deleted an appointment'); break; default: console.log('Unsupported event:', ev.body.event); return null; } }; <|start_filename|>components/airtable/actions/update-record/update-record.js<|end_filename|> const airtable = require("../../airtable.app.js"); const common = require("../common.js"); module.exports = { key: "airtable-update-record", name: "Update record", description: "Update a single record in a table by Record ID.", version: "0.1.0", type: "action", props: { ...common.props, recordId: { propDefinition: [ airtable, "recordId", ], }, record: { propDefinition: [ airtable, "record", ], }, }, async run() { this.airtable.validateRecordID(this.recordId); const base = this.airtable.base(this.baseId); try { return (await base(this.tableId).update([ { id: this.recordId, fields: this.record, }, ]))[0]; } catch (err) { this.airtable.throwFormattedError(err); } }, }; <|start_filename|>components/bandwidth/sources/new-outgoing-sms/new-outgoing-sms.js<|end_filename|> const bandwidth = require('../../bandwidth.app'); module.exports = { name: 'New Outgoing SMS', description: 'Emits an event each time an outbound message status event is received at the source url', key: 'bandwidth-new-ourgoing-sms', version: '1.1.1', props: { bandwidth, http: { type: '$.interface.http', customResponse: true, }, }, async run(event) { const messageBody = event.body[0]; this.http.respond({ status: 204, }); if (messageBody.message.direction == 'out') { this.$emit(messageBody, { summary: messageBody.type, id: messageBody.message.id, ts: +new Date(messageBody.time), }); } }, }; <|start_filename|>examples/user-input-prop.js<|end_filename|> module.exports = { name: "User Input Prop Example", version: "0.1", props: { msg: { type: "string", label: "Message", description: "Enter a message to `console.log()`", }, }, async run() { this.$emit(this.msg); }, }; <|start_filename|>components/webflow/sources/site-published/site-published.js<|end_filename|> const common = require("../common"); module.exports = { ...common, key: "webflow-site-published", name: "Site Published (Instant)", description: "Emit an event when a site is published", version: "0.0.1", methods: { ...common.methods, getWebhookTriggerType() { return "site_publish"; }, generateMeta(data) { const { site: siteId, publishTime: ts, } = data; const summary = `Site published: ${siteId}`; const id = `${siteId}-${ts}`; return { id, summary, ts, }; }, }, }; <|start_filename|>components/threads/actions/post-thread/post-thread.js<|end_filename|> const threads = require("../../threads.app.js"); module.exports = { key: "threads-post-thread", name: "Post a Thread", description: "Post a new thread to a specific forum", version: "0.0.1", type: "action", props: { threads, forumID: { propDefinition: [ threads, "forumID", ], }, title: { propDefinition: [ threads, "title", ], }, body: { propDefinition: [ threads, "body", ], }, }, async run() { const { forumID, title, body, } = this; return await this.threads.postThread({ forumID, title, body, }); }, }; <|start_filename|>components/sendgrid/sources/common/http-based.js<|end_filename|> const { EventWebhook, EventWebhookHeader, } = require("@sendgrid/eventwebhook"); const base = require("./base"); module.exports = { ...base, props: { ...base.props, http: { type: "$.interface.http", customResponse: true, }, }, hooks: { ...base.hooks, async activate() { const { endpoint: endpointUrl } = this.http; const { enabled, url, } = await this.sendgrid.getWebhookSettings(); if (enabled && endpointUrl !== url) { throw new Error(` Your account already has an active event webhook. Please verify and safely disable it before using this event source. `); } const newWebhookSettings = { ...this.baseWebhookSettings(), ...this.webhookEventFlags(), enabled: true, url: endpointUrl, }; await this.sendgrid.setWebhookSettings(newWebhookSettings); const webhookPublicKey = await this.sendgrid.enableSignedWebhook(); this.db.set("webhookPublicKey", webhookPublicKey); }, async deactivate() { const webhookSettings = { ...this.baseWebhookSettings(), enabled: false, url: null, }; await this.sendgrid.setWebhookSettings(webhookSettings); await this.sendgrid.disableSignedWebhook(); }, }, methods: { ...base.methods, _isValidSource(event) { const { [EventWebhookHeader.SIGNATURE().toLowerCase()]: signature, [EventWebhookHeader.TIMESTAMP().toLowerCase()]: timestamp, } = event.headers; const { bodyRaw: payload } = event; const webhookPublicKey = this.db.get("webhookPublicKey"); const webhookHelper = new EventWebhook(); const ecdsaPublicKey = webhookHelper.convertPublicKeyToECDSA(webhookPublicKey); return webhookHelper.verifySignature(ecdsaPublicKey, payload, signature, timestamp); }, processEvent(event) { if (!this._isValidSource(event)) { this.http.respond({ status: 400, body: "Signature check failed", }); return; } this.http.respond({ status: 200, }); const { body: events } = event; events.forEach((e) => { const meta = this.generateMeta(e); this.$emit(e, meta); }); }, }, }; <|start_filename|>components/twitter/actions/advanced-search/advanced-search.js<|end_filename|> const twitter = require('../../twitter.app.js') const moment = require('moment') module.exports = { key: "twitter-advanced-search", name: "Advanced Search", description: "Return Tweets that matches your search criteria.", version: "0.0.2", type: "action", props: { db: "$.service.db", twitter, q: { propDefinition: [twitter, "q"] }, result_type: { propDefinition: [twitter, "result_type"] }, includeRetweets: { propDefinition: [twitter, "includeRetweets"] }, includeReplies: { propDefinition: [twitter, "includeReplies"] }, lang: { propDefinition: [twitter, "lang"] }, locale: { propDefinition: [twitter, "locale"] }, geocode: { propDefinition: [twitter, "geocode"] }, since_id: { propDefinition: [twitter, "since_id"] }, enrichTweets: { propDefinition: [twitter, "enrichTweets"] }, count: { propDefinition: [twitter, "count"] }, maxRequests: { propDefinition: [twitter, "maxRequests"] }, }, async run(event) { const { lang, locale, geocode, result_type, enrichTweets, includeReplies, includeRetweets, since_id, maxRequests, count } = this let q = this.q, max_id, limitFirstPage if (!since_id) { limitFirstPage = true } else { limitFirstPage = false } // run paginated search return await this.twitter.paginatedSearch({ q, since_id, lang, locale, geocode, result_type, enrichTweets, includeReplies, includeRetweets, maxRequests, count, limitFirstPage, }) }, } <|start_filename|>components/discord_webhook/actions/send-message/send-message.js<|end_filename|> const discordWebhook = require("../../discord_webhook.app.js"); module.exports = { key: "discord_webhook-send-message", name: "Send Message", description: "Send a simple message to a Discord channel", version: "0.1.2", type: "action", props: { discordWebhook, message: { propDefinition: [ discordWebhook, "message", ], }, threadID: { propDefinition: [ discordWebhook, "threadID", ], }, username: { propDefinition: [ discordWebhook, "username", ], }, avatarURL: { propDefinition: [ discordWebhook, "avatarURL", ], }, }, async run() { const { avatarURL, threadID, username, } = this; // No interesting data is returned from Discord await this.discordWebhook.sendMessage({ avatarURL, content: this.message, threadID, username, }); }, }; <|start_filename|>components/procore/sources/common.js<|end_filename|> const procore = require("../procore.app.js"); module.exports = { dedupe: "unique", props: { procore, db: "$.service.db", http: "$.interface.http", company: { propDefinition: [procore, "company"] }, project: { propDefinition: [procore, "project", (c) => ({ company: c.company })], }, }, methods: { getComponentEventTypes() { return this.procore.getEventTypes(); }, getResourceName() { throw new Error("getResourceName is not implemented"); }, }, hooks: { async activate() { const hook = await this.procore.createHook( this.http.endpoint, this.company, this.project ); this.db.set("hookId", hook.id); // create hook triggers eventTypes = this.getComponentEventTypes(); resourceName = this.getResourceName(); const triggerIds = []; for (const eventType of eventTypes) { const trigger = await this.procore.createHookTrigger( hook.id, this.company, this.project, resourceName, eventType ); triggerIds.push(trigger.id); } this.db.set("triggerIds", triggerIds); }, async deactivate() { const hookId = this.db.get("hookId"); const triggerIds = this.db.get("triggerIds"); // delete hook triggers for (const triggerId of triggerIds) { await this.procore.deleteHookTrigger( hookId, triggerId, this.company, this.project ); } // delete hook await this.procore.deleteHook(hookId, this.company, this.project); }, }, async run(event) { const { body } = event; if (!body) { return; } const dataToEmit = await this.getDataToEmit(body); const meta = this.getMeta(dataToEmit); this.$emit(dataToEmit, meta); }, }; <|start_filename|>components/intercom/sources/conversation-closed/conversation-closed.js<|end_filename|> const intercom = require("../../intercom.app.js"); module.exports = { key: "intercom-conversation-closed", name: "New Closed Conversation", description: "Emits an event each time a conversation is closed.", version: "0.0.1", dedupe: "unique", props: { intercom, db: "$.service.db", timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 15, }, }, }, async run(event) { const monthAgo = this.intercom.monthAgo(); let lastConversationClosedAt = this.db.get("lastConversationClosedAt") || Math.floor(monthAgo / 1000); const data = { query: { field: "statistics.last_close_at", operator: ">", value: lastConversationClosedAt, }, }; const results = await this.intercom.searchConversations(data); for (const conversation of results) { if (conversation.created_at > lastConversationClosedAt) lastConversationClosedAt = conversation.statistics.last_close_at; this.$emit(conversation, { id: `${conversation.id}${conversation.last_close_at}`, summary: conversation.source.body, ts: conversation.last_close_at, }); } this.db.set("lastConversationClosedAt", lastConversationClosedAt); }, }; <|start_filename|>components/hubspot/sources/new-contact/new-contact.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, key: "hubspot-new-contact", name: "New Contacts", description: "Emits an event for each new contact added.", version: "0.0.2", dedupe: "unique", methods: { ...common.methods, generateMeta(contact) { const { id, properties, createdAt } = contact; const ts = Date.parse(createdAt); return { id, summary: `${properties.firstname} ${properties.lastname}`, ts, }; }, isRelevant(contact, createdAfter) { return Date.parse(contact.createdAt) > createdAfter; }, }, async run(event) { const createdAfter = this._getAfter(); const data = { limit: 100, sorts: [ { propertyName: "createdate", direction: "DESCENDING", }, ], properties: this.db.get("properties"), object: "contacts", }; await this.paginate( data, this.hubspot.searchCRM.bind(this), "results", createdAfter ); this._setAfter(Date.now()); }, }; <|start_filename|>components/webflow/sources/changed-collection-item/changed-collection-item.js<|end_filename|> const common = require("../collection-common"); module.exports = { ...common, key: "webflow-changed-collection-item", name: "Changed Collection Item (Instant)", description: "Emit an event when a collection item is changed", version: "0.0.1", methods: { ...common.methods, getWebhookTriggerType() { return "collection_item_changed"; }, generateMeta(data) { const { _id: itemId, slug, "updated-on": updatedOn, } = data; const summary = `Collection item changed: ${slug}`; const ts = Date.parse(updatedOn); const id = `${itemId}-${ts}`; return { id, summary, ts, }; }, }, }; <|start_filename|>components/rss/actions/merge-rss-feeds/merge-rss-feeds.js<|end_filename|> const Parser = require("rss-parser"); module.exports = { name: "Merge RSS Feeds", description: "Retrieve multiple RSS feeds and return a merged array of items sorted by date.", key: "rss-merge-rss-feeds", version: "0.0.1", type: "action", props: { feeds: { type: "string[]", label: "Feeds", description: "The list of RSS feeds you want to parse.", }, merge: { type: "boolean", optional: true, default: true, description: "If `true`, all items are returned in a date sorted array. If `false`, each feed is returned as one result in the array.", }, rss: { type: "app", app: "rss", }, }, async run() { /* If merge is true, its an array of feed items where each item has a .feed property with info on the feed. A bit repetitve. It's sorted by date. If merge is false, each array item is an object with: { feed: info on feed items: items } */ let result = []; let parser = new Parser(); const requests = this.feeds.map(feed => parser.parseURL(feed)); const results = await Promise.all(requests); for (const feedResult of results) { const feed = { title: feedResult.title, description: feedResult.description, lastBuildDate: feedResult.lastBuildDate, link: feedResult.link, feedUrl: feedResult.feedUrl, }; if (this.merge) { feedResult.items.forEach(f => { let newItem = f; newItem.feed = feed; result.push(newItem); }); } else { result.push({ feed, items: feedResult.items, }); } } // now sort by pubDate, if merging of course if (this.merge) { result = result.sort((a, b) => { let aDate = new Date(a.isoDate); let bDate = new Date(b.isoDate); return bDate - aDate; }); } return result; }, }; <|start_filename|>components/ringcentral/sources/new-event/new-event.js<|end_filename|> const notificationTypes = require("../common/notification-types"); const common = require("../common/http-based"); module.exports = { ...common, key: "ringcentral-new-event", name: "New Event (Instant)", description: "Emits an event for each notification from RingCentral of a specified type", version: "0.0.1", props: { ...common.props, extensionId: { optional: true, propDefinition: [ common.props.ringcentral, "extensionId", ], }, deviceId: { optional: true, propDefinition: [ common.props.ringcentral, "deviceId", c => ({ extensionId: c.extensionId }), ], }, notificationTypes: { type: "string[]", label: "Notification Types", description: "The types of notifications to emit events for", options({ page = 0 }) { if (page !== 0) { return []; } return notificationTypes.map(({ label, key }) => ({ label, value: key, })); }, }, }, methods: { ...common.methods, _getEventTypeFromFilter(eventFilter) { return eventFilter .replace(/\/restapi\/v\d+\.\d+\//, "") .replace(/account\/.*?\//, "") .replace(/extension\/.*?\//, ""); }, getSupportedNotificationTypes() { return new Set(this.notificationTypes); }, generateMeta(data) { const { uuid: id, timestamp, event: eventFilter, } = data; const eventType = this._getEventTypeFromFilter(eventFilter); const summary = `New event: ${eventType}`; const ts = Date.parse(timestamp); return { id, summary, ts, }; }, }, }; <|start_filename|>components/bitbucket/sources/new-issue/new-issue.js<|end_filename|> const common = require("../../common"); const { bitbucket } = common.props; const EVENT_SOURCE_NAME = "New Issue (Instant)"; module.exports = { ...common, name: EVENT_SOURCE_NAME, key: "bitbucket-new-issue", description: "Emits an event when a new issue is created", version: "0.0.2", props: { ...common.props, repositoryId: { propDefinition: [ bitbucket, "repositoryId", c => ({ workspaceId: c.workspaceId }), ], }, }, methods: { ...common.methods, getEventSourceName() { return EVENT_SOURCE_NAME; }, getHookEvents() { return [ "issue:created", ]; }, getHookPathProps() { return { workspaceId: this.workspaceId, repositoryId: this.repositoryId, }; }, generateMeta(data) { const { headers, body } = data; const { id, title } = body.issue; const summary = `New Issue: #${id} ${title}`; const ts = +new Date(headers["x-event-time"]); return { id, summary, ts, }; }, }, }; <|start_filename|>components/pagerduty/pagerduty.app.js<|end_filename|> const axios = require("axios"); module.exports = { type: "app", app: "pagerduty", propDefinitions: { escalationPolicies: { type: "string[]", label: "Escalation Policies", description: "To filter your on-call rotations to specific escalation policies, select them here. **To listen for rotations across all escalation policies, leave this blank**.", async options({ prevContext }) { const { offset } = prevContext; const escalationPolicies = await this.listEscalationPolicies(offset); const options = escalationPolicies.map((policy) => { return { label: policy.summary, value: policy.id, }; }); return { options, context: { offset }, }; }, optional: true, }, }, methods: { async _makeRequest(opts) { if (!opts.headers) opts.headers = {}; opts.headers.authorization = `Bearer ${this.$auth.oauth_access_token}`; opts.headers["user-agent"] = "@PipedreamHQ/pipedream v0.1"; opts.headers.accept = "application/vnd.pagerduty+json;version=2"; const { path } = opts; delete opts.path; opts.url = `https://api.pagerduty.com${ path[0] === "/" ? "" : "/" }${path}`; return await axios(opts); }, async getEscalationPolicy(id) { return ( await this._makeRequest({ path: `/escalation_policies/${id}`, }) ).data.escalation_policy; }, async listEscalationPolicies(offset) { return ( await this._makeRequest({ path: "/escalation_policies", params: { offset }, }) ).data.escalation_policies; }, async listOnCallUsers({ escalation_policy_ids }) { return ( await this._makeRequest({ path: "/oncalls", params: { escalation_policy_ids }, }) ).data.oncalls.map(({ user }) => user); }, }, }; <|start_filename|>components/netlify/common.js<|end_filename|> const netlify = require("./netlify.app"); module.exports = { dedupe: "unique", props: { netlify, db: "$.service.db", http: { type: "$.interface.http", customResponse: true, }, siteId: { propDefinition: [netlify, "siteId"] }, }, hooks: { async activate() { const event = this.getHookEvent(); const opts = { event, url: this.http.endpoint, siteId: this.siteId, }; const { hookId, token } = await this.netlify.createHook(opts); this.db.set("hookId", hookId); this.db.set("token", token); }, async deactivate() { const hookId = this.db.get("hookId"); const opts = { hookId, siteId: this.siteId, }; await this.netlify.deleteHook(opts); }, }, methods: { generateMeta(data) { const { id, created_at } = data; const ts = +new Date(created_at); const summary = this.getMetaSummary(data); return { id, summary, ts, }; }, }, async run(event) { const { headers, body, bodyRaw } = event; // Reject any calls not made by the proper Netlify webhook. if (!this.netlify.isValidSource(headers, bodyRaw, this.db)) { this.http.respond({ status: 404, }); return; } // Acknowledge the event back to Netlify. this.http.respond({ status: 200, }); const meta = this.generateMeta(body); this.$emit(body, meta); }, }; <|start_filename|>components/todoist/sources/common-project.js<|end_filename|> const common = require("./common.js"); module.exports = { ...common, async run(event) { const syncResult = await this.todoist.syncProjects(this.db); Object.values(syncResult) .filter(Array.isArray) .flat() .forEach((element) => { element.summary = `Project: ${element.id}`; const meta = this.generateMeta(element); this.$emit(element, meta); }); }, }; <|start_filename|>components/twitch/actions/get-clips/get-clips.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, name: "Get Clips", key: "twitch-get-clips", description: "Gets clip information by clip ID, user ID, or game ID", version: "0.0.1", type: "action", props: { ...common.props, id: { type: "string", label: "Clip ID", description: `ID of the video being queried. For a query to be valid, id, broadcaster_id, or game_id must be specified. You may specify only one of these parameters.`, optional: true, }, broadcaster: { propDefinition: [ common.props.twitch, "broadcaster", ], description: `ID of the broadcaster for whom clips are returned. Results are ordered by view count. For a query to be valid, id, broadcaster_id, or game_id must be specified. You may specify only one of these parameters.`, optional: true, }, gameId: { type: "string", label: "Game ID", description: `ID of the game the clip is of. For a query to be valid, id, broadcaster_id, or game_id must be specified. You may specify only one of these parameters.`, optional: true, }, max: { propDefinition: [ common.props.twitch, "max", ], description: "Maximum number of videos to return", }, }, async run() { let params = { id: this.id, broadcaster_id: this.broadcaster, game_id: this.gameId, }; // remove empty values from params Object.keys(params).forEach((k) => (params[k] == null || params[k] == "") && delete params[k]); const clips = await this.paginate( this.twitch.getClips.bind(this), params, this.max, ); return await this.getPaginatedResults(clips); }, }; <|start_filename|>components/google_drive/constants.js<|end_filename|> /** * @typedef {string} UpdateType - a type of push notification as defined by * the [Google Drive API docs](https://bit.ly/3wcsY2X) */ /** * A new channel was successfully created. You can expect to start receiving * notifications for it. * * @type {UpdateType} */ const GOOGLE_DRIVE_NOTIFICATION_SYNC = "sync"; /** * A new resource was created or shared * * @type {UpdateType} */ const GOOGLE_DRIVE_NOTIFICATION_ADD = "add"; /** * An existing resource was deleted or unshared * * @type {UpdateType} */ const GOOGLE_DRIVE_NOTIFICATION_REMOVE = "remove"; /** * One or more properties (metadata) of a resource have been updated * * @type {UpdateType} */ const GOOGLE_DRIVE_NOTIFICATION_UPDATE = "update"; /** * A resource has been moved to the trash * * @type {UpdateType} */ const GOOGLE_DRIVE_NOTIFICATION_TRASH = "trash"; /** * A resource has been removed from the trash * * @type {UpdateType} */ const GOOGLE_DRIVE_NOTIFICATION_UNTRASH = "untrash"; /** * One or more new changelog items have been added * * @type {UpdateType} */ const GOOGLE_DRIVE_NOTIFICATION_CHANGE = "change"; /** * All the available Google Drive update types * @type {UpdateType[]} */ const GOOGLE_DRIVE_UPDATE_TYPES = [ GOOGLE_DRIVE_NOTIFICATION_SYNC, GOOGLE_DRIVE_NOTIFICATION_ADD, GOOGLE_DRIVE_NOTIFICATION_REMOVE, GOOGLE_DRIVE_NOTIFICATION_UPDATE, GOOGLE_DRIVE_NOTIFICATION_TRASH, GOOGLE_DRIVE_NOTIFICATION_UNTRASH, GOOGLE_DRIVE_NOTIFICATION_CHANGE, ]; /** * This is a custom string value to represent the 'My Drive' Google Drive, which * is represented as `null` by the Google Drive API. In order to simplify the * code by avoiding null values, we assign this special value to the 'My Drive' * drive. */ const MY_DRIVE_VALUE = "myDrive"; /** * The maximum amount of time a subscription can be active without expiring is * 24 hours. In order to minimize subscription renewals (which involve the * execution of an event source) we set the expiration of subscriptions to its * maximum allowed value. * * More information can be found in the API docs: * https://developers.google.com/drive/api/v3/push#optional-properties */ const WEBHOOK_SUBSCRIPTION_EXPIRATION_TIME_MILLISECONDS = 24 * 60 * 60 * 1000; /** * The default time interval between webhook subscription renewals. Since * subscriptions expire after 24 hours at most, we set this time to 95% of this * time window by default to make sure the event sources don't miss any events * due to an expired subscription not being renewed on time. * * More information can be found in the API docs: * https://developers.google.com/drive/api/v3/push#optional-properties */ const WEBHOOK_SUBSCRIPTION_RENEWAL_SECONDS = ( WEBHOOK_SUBSCRIPTION_EXPIRATION_TIME_MILLISECONDS * .95 / 1000 ); module.exports = { GOOGLE_DRIVE_NOTIFICATION_SYNC, GOOGLE_DRIVE_NOTIFICATION_ADD, GOOGLE_DRIVE_NOTIFICATION_REMOVE, GOOGLE_DRIVE_NOTIFICATION_UPDATE, GOOGLE_DRIVE_NOTIFICATION_TRASH, GOOGLE_DRIVE_NOTIFICATION_UNTRASH, GOOGLE_DRIVE_NOTIFICATION_CHANGE, GOOGLE_DRIVE_UPDATE_TYPES, MY_DRIVE_VALUE, WEBHOOK_SUBSCRIPTION_EXPIRATION_TIME_MILLISECONDS, WEBHOOK_SUBSCRIPTION_RENEWAL_SECONDS, }; <|start_filename|>components/firebase_admin_sdk/sources/new-doc-in-firestore-collection/new-doc-in-firestore-collection.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, key: "firebase_admin_sdk-new-doc-in-firestore-collection", name: "New Document in Firestore Collection", description: "Emits an event when a structured query returns new documents", version: "0.0.1", dedupe: "unique", props: { ...common.props, apiKey: { propDefinition: [ common.props.firebase, "apiKey", ], }, query: { propDefinition: [ common.props.firebase, "query", ], }, }, methods: { ...common.methods, async processEvent() { const structuredQuery = JSON.parse(this.query); const queryResults = await this.firebase.runQuery( structuredQuery, this.apiKey, ); for (const result of queryResults) { const meta = this.generateMeta(result); this.$emit(result, meta); } }, generateMeta({ document }) { const { name, createTime, } = document; const id = name.substring(name.lastIndexOf("/") + 1); return { id, summary: name, ts: Date.parse(createTime), }; }, }, }; <|start_filename|>components/slack/sources/new-message-in-channels/new-message-in-channels.js<|end_filename|> const slack = require("../../slack.app.js"); module.exports = { key: "slack-new-message-in-channels", name: "New Message In Channels", version: "0.0.2", description: "Emit an event when a new message is posted to one or more channels", dedupe: "unique", props: { slack, conversations: { type: "string[]", label: "Channels", description: "Select one or more channels to monitor for new messages.", optional: true, async options({ prevContext }) { let { types, cursor, userNames, } = prevContext; if (types == null) { const scopes = await this.slack.scopes(); types = [ "public_channel", ]; if (scopes.includes("groups:read")) { types.push("private_channel"); } if (scopes.includes("mpim:read")) { types.push("mpim"); } if (scopes.includes("im:read")) { types.push("im"); // TODO use paging userNames = {}; for (const user of (await this.slack.users()).users) { userNames[user.id] = user.name; } } } const resp = await this.slack.availableConversations(types.join(), cursor); return { options: resp.conversations.map((c) => { if (c.is_im) { return { label: `Direct messaging with: @${userNames[c.user]}`, value: c.id, }; } else if (c.is_mpim) { return { label: c.purpose.value, value: c.id, }; } else { return { label: `${c.is_private ? "Private" : "Public" } channel: ${c.name}`, value: c.id, }; } }), context: { types, cursor: resp.cursor, userNames }, }; }, }, slackApphook: { type: "$.interface.apphook", appProp: "slack", async eventNames() { return this.conversations || []; }, }, ignoreMyself: { type: "boolean", label: "Ignore myself", description: "Ignore messages from me", default: true, }, resolveNames: { type: "boolean", label: "Resolve names", description: "Resolve user and channel names (incurs extra API calls)", default: false, }, ignoreBot: { type: "boolean", label: "Ignore bots", description: "Ignore messages from bots", default: false, }, nameCache: "$.service.db", }, methods: { async maybeCached(key, refreshVal, timeoutMs = 3600000) { let record = this.nameCache.get(key); const time = Date.now(); if (!record || time - record.ts > timeoutMs) { record = { ts: time, val: await refreshVal(), }; this.nameCache.set(key, record); } return record.val; }, async getBotName(id) { return this.maybeCached(`bots:${id}`, async () => { const info = await this.slack.sdk().bots.info({ bot: id, }); if (!info.ok) throw new Error(info.error); return info.bot.name; }); }, async getUserName(id) { return this.maybeCached(`users:${id}`, async () => { const info = await this.slack.sdk().users.info({ user: id, }); if (!info.ok) throw new Error(info.error); return info.user.name; }); }, async getConversationName(id) { return this.maybeCached(`conversations:${id}`, async () => { const info = await this.slack.sdk().conversations.info({ channel: id, }); if (!info.ok) throw new Error(info.error); if (info.channel.is_im) { return `DM with ${await this.getUserName(info.channel.user)}`; } else { return info.channel.name; } }); }, async getTeamName(id) { return this.maybeCached(`team:${id}`, async () => { try { const info = await this.slack.sdk().team.info({ team: id, }); return info.team.name; } catch (err) { console.log("Error getting team name, probably need to re-connect the account at pipedream.com/apps", err); return id; } }); }, }, async run(event) { if (event.subtype != null && event.subtype != "bot_message" && event.subtype != "file_share") { // This source is designed to just emit an event for each new message received. // Due to inconsistencies with the shape of message_changed and message_deleted // events, we are ignoring them for now. If you want to handle these types of // events, feel free to change this code!! console.log("Ignoring message with subtype."); return; } if (this.ignoreMyself && event.user == this.slack.mySlackId()) { return; } if (this.ignoreBot && event.subtype == "bot_message") { return; } if (this.resolveNames) { if (event.user) { event.user_id = event.user; event.user = await this.getUserName(event.user); } else if (event.bot_id) { event.bot = await this.getBotName(event.bot_id); } event.channel_id = event.channel; event.channel = await this.getConversationName(event.channel); if (event.team) { event.team_id = event.team; event.team = await this.getTeamName(event.team); } } if (!event.client_msg_id) { event.pipedream_msg_id = `pd_${Date.now()}_${Math.random().toString(36) .substr(2, 10)}`; } this.$emit(event, { id: event.client_msg_id || event.pipedream_msg_id, }); }, }; <|start_filename|>components/hubspot/sources/new-engagement/new-engagement.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, key: "hubspot-new-engagement", name: "New Engagement", description: "Emits an event for each new engagement created.", version: "0.0.2", dedupe: "unique", hooks: {}, methods: { ...common.methods, generateMeta(engagement) { const { id, type, createdAt } = engagement.engagement; const ts = Date.parse(createdAt); return { id, summary: type, ts, }; }, isRelevant(engagement, createdAfter) { return engagement.engagement.createdAt > createdAfter; }, }, async run(event) { const createdAfter = this._getAfter(); const params = { limit: 250, }; await this.paginateUsingHasMore( params, this.hubspot.getEngagements.bind(this), "results", createdAfter ); }, }; <|start_filename|>components/activecampaign/sources/common-webhook.js<|end_filename|> const activecampaign = require("../activecampaign.app.js"); const common = require("./common.js"); module.exports = { ...common, props: { ...common.props, http: "$.interface.http", sources: { propDefinition: [activecampaign, "sources"] }, }, methods: { isRelevant(body) { return true; }, }, hooks: { async activate() { const sources = this.sources.length > 0 ? this.sources : this.activecampaign.getAllSources(); const hookData = await this.activecampaign.createHook( this.getEvents(), this.http.endpoint, sources ); this.db.set("hookId", hookData.webhook.id); }, async deactivate() { await this.activecampaign.deleteHook(this.db.get("hookId")); }, }, async run(event) { const { body } = event; if (!body) { return; } if (!this.isRelevant(body)) return; const meta = await this.getMeta(body); this.$emit(body, meta); }, }; <|start_filename|>components/sentry/sources/issue-event/issue-event.js<|end_filename|> const sentry = require('../../sentry.app'); const EVENT_SOURCE_NAME = 'Issue Event (Instant)'; module.exports = { key: 'sentry-issue-events', version: '0.0.1', name: EVENT_SOURCE_NAME, props: { db: '$.service.db', http: { type: '$.interface.http', customResponse: true, }, sentry, organizationSlug: {propDefinition: [sentry, 'organizationSlug']}, }, hooks: { async activate() { const {slug: integrationSlug} = await this.sentry.createIntegration( this.getEventSourceName(), this.organizationSlug, this.http.endpoint, ); this.db.set('integrationSlug', integrationSlug); const clientSecret = await this.sentry.getClientSecret(integrationSlug); this.db.set('clientSecret', clientSecret); }, async deactivate() { const integrationSlug = this.db.get('integrationSlug'); await this.sentry.disableIntegration(integrationSlug); }, }, methods: { getEventSourceName() { return EVENT_SOURCE_NAME; }, generateMeta(event) { const {body, headers} = event; const { 'request-id': id, 'sentry-hook-resource': resourceType, 'sentry-hook-timestamp': ts, } = headers; const {action, data} = body; const {[resourceType]: resource} = data; const summary = `${resourceType} #${resource.id} ${action}`; return { id, summary, ts, }; }, }, async run(event) { const clientSecret = this.db.get('clientSecret'); if (!this.sentry.isValidSource(event, clientSecret)) { this.http.respond({ statusCode: 404, }); return; } this.http.respond({ statusCode: 200, }); const {body} = event; const meta = this.generateMeta(event); this.$emit(body, meta); }, }; <|start_filename|>components/todoist/resource-types.js<|end_filename|> module.exports = [ "collaborators", "filters", "items", "labels", "live_notifications", "locations", "notes", "notification_settings", "projects", "reminders", "sections", "user", "user_settings" ] <|start_filename|>components/activecampaign/sources/common.js<|end_filename|> const activecampaign = require("../activecampaign.app.js"); module.exports = { dedupe: "unique", props: { activecampaign, db: "$.service.db", }, }; <|start_filename|>components/google_drive/actions/create-file/create-file.js<|end_filename|> const googleDrive = require("../../google_drive.app"); const fs = require("fs"); const got = require("got"); const isoLanguages = require("../language-codes.js"); const googleMimeTypes = require("../google-mime-types.js"); const mimeDb = require("mime-db"); const mimeTypes = Object.keys(mimeDb); module.exports = { key: "google_drive-create-file", name: "Create a New File", description: "Create a new file from a URL or /tmp/filepath.", version: "0.0.3", type: "action", props: { googleDrive, drive: { propDefinition: [ googleDrive, "watchedDrive", ], }, parent: { type: "string", label: "Parent Folder", description: `The ID of the parent folder which contains the file. If not specified as part of a create request, the file will be placed directly in the user's My Drive folder.`, optional: true, async options({ prevContext }) { const { nextPageToken } = prevContext; let results; if (this.drive === "myDrive") { results = await this.googleDrive.listFolderOptions(nextPageToken); } else { results = await this.googleDrive.listFolderOptions(nextPageToken, { corpora: "drive", driveId: this.drive, includeItemsFromAllDrives: true, supportsAllDrives: true, }); } return results; }, }, uploadType: { type: "string", label: "Upload Type", description: `The type of upload request to the /upload URI. If you are uploading data (using an /upload URI), this field is required. If you are creating a metadata-only file, this field is not required. media - Simple upload. Upload the media only, without any metadata. multipart - Multipart upload. Upload both the media and its metadata, in a single request. resumable - Resumable upload. Upload the file in a resumable fashion, using a series of at least two requests where the first request includes the metadata.`, options: [ "media", "multipart", "resumable", ], }, fileUrl: { type: "string", label: "File URL", description: `The URL of the file you want to upload to Google Drive. Must specify either File URL or File Path.`, optional: true, }, filePath: { type: "string", label: "File Path", description: "The path to the file, e.g. /tmp/myFile.csv . Must specify either File URL or File Path.", optional: true, }, ignoreDefaultVisibility: { type: "boolean", label: "Ignore Default Visibility", description: `Whether to ignore the domain's default visibility settings for the created file. Domain administrators can choose to make all uploaded files visible to the domain by default; this parameter bypasses that behavior for the request. Permissions are still inherited from parent folders.`, default: false, }, includePermissionsForView: { type: "string", label: "Include Permissions For View", description: `Specifies which additional view's permissions to include in the response. Only 'published' is supported.`, optional: true, options: [ "published", ], }, keepRevisionForever: { type: "boolean", label: "Keep Revision Forever", description: `Whether to set the 'keepForever' field in the new head revision. This is only applicable to files with binary content in Google Drive. Only 200 revisions for the file can be kept forever. If the limit is reached, try deleting pinned revisions.`, default: false, }, ocrLanguage: { type: "string", label: "OCR Language", description: "A language hint for OCR processing during image import (ISO 639-1 code).", optional: true, options: isoLanguages, }, useContentAsIndexableText: { type: "boolean", label: "Use Content As Indexable Text", description: "Whether to use the uploaded content as indexable text.", default: false, }, supportsAllDrives: { type: "boolean", label: "Supports All Drives", description: `Whether to include shared drives. Set to 'true' if saving to a shared drive. Defaults to 'false' if left blank.`, optional: true, }, contentHintsIndexableText: { type: "string", label: "Content Hints Indexable Text", description: `Text to be indexed for the file to improve fullText queries. This is limited to 128KB in length and may contain HTML elements.`, optional: true, }, contentRestrictionsReadOnly: { type: "boolean", label: "Content Restrictions Read Only", description: `Whether the content of the file is read-only. If a file is read-only, a new revision of the file may not be added, comments may not be added or modified, and the title of the file may not be modified.`, optional: true, }, contentRestrictionsReason: { type: "string", label: "Content Restrictions Reason", description: `Reason for why the content of the file is restricted. This is only mutable on requests that also set readOnly=true.`, optional: true, }, copyRequiresWriterPermission: { type: "boolean", label: "Copy Requires Writer Permission", description: `Whether the options to copy, print, or download this file, should be disabled for readers and commenters.`, optional: true, }, description: { type: "string", label: "Description", description: "A short description of the file.", optional: true, }, folderColorRgb: { type: "string", label: "Folder Color RGB", description: `The color for a folder as an RGB hex string. If an unsupported color is specified, the closest color in the palette will be used instead.`, optional: true, }, mimeType: { type: "string", label: "Mime Type", description: `The MIME type of the file. Google Drive will attempt to automatically detect an appropriate value from uploaded content if no value is provided. The value cannot be changed unless a new revision is uploaded. If a file is created with a Google Doc MIME type, the uploaded content will be imported if possible. Google Workspace and Drive MIME Types: https://developers.google.com/drive/api/v3/mime-types`, optional: true, async options({ page = 0 }) { const allTypes = googleMimeTypes.concat(mimeTypes); const start = (page - 1) * 10; const end = start + 10; return allTypes.slice(start, end); }, }, name: { type: "string", label: "Name", description: "Name of the file", optional: true, }, originalFilename: { type: "string", label: "Original Filename", description: "The original filename of the uploaded content if available, or else the original value of the name field. This is only available for files with binary content in Google Drive.", optional: true, }, shortcutDetailsTargetId: { type: "string", label: "Shortcut Details Target ID", description: "The ID of the file that this shortcut points to.", optional: true, }, starred: { type: "boolean", label: "Starred", description: "Whether the user has starred the file.", optional: true, }, writersCanShare: { type: "boolean", label: "Writers Can Share", description: "Whether users with only writer permission can modify the file's permissions. Not populated for items in shared drives.", optional: true, }, }, async run() { const body = this.fileUrl ? await got.stream(this.fileUrl) : fs.createReadStream(this.filePath); return ( await this.googleDrive.createFile({ ignoreDefaultVisibility: this.ignoreDefaultVisibility, includePermissionsForView: this.includePermissionsForView, keepRevisionForever: this.keeprevisionForever, ocrLanguage: this.ocrLanguage, useContentAsIndexableText: this.useContentAsIndexableText, supportsAllDrives: this.supportsAllDrives, resource: { name: this.name, originalFilename: this.originalFilename, parents: [ this.parent, ], mimeType: this.mimeType, description: this.description, folderColorRgb: this.folderColorRgb, shortcutDetails: { targetId: this.shortcutDetailsTargetId, }, starred: this.starred, writersCanShare: this.writersCanShare, contentHints: { indexableText: this.contentHintsIndexableText, }, contentRestrictions: { readOnly: this.contentRestrictionsReadOnly, reason: this.contentRestrictionsReason, }, copyRequiresWriterPermission: this.copyRequiresWriterPermission, }, media: { mimeType: this.mimeType, uploadType: this.uploadType, body, }, fields: "*", }) ); }, }; <|start_filename|>components/docusign/docusign.app.js<|end_filename|> const axios = require("axios"); module.exports = { type: "app", app: "docusign", propDefinitions: { account: { type: "string", label: "Account", async options() { const { accounts } = await this.getUserInfo(); return accounts.map((account) => { return { label: account.account_name, value: account.account_id, }; }); }, }, template: { type: "string", label: "Template", async options({ account }) { const baseUri = await this.getBaseUri(account); const { envelopeTemplates } = await this.listTemplates(baseUri); return envelopeTemplates.map((template) => { return { label: template.name, value: template.templateId, }; }); }, }, emailSubject: { type: "string", label: "Email Subject", description: "Subject line of email", }, emailBlurb: { type: "string", label: "Email Blurb", description: "Email message to recipient. Overrides template setting.", optional: true, }, recipientEmail: { type: "string", label: "Recipient Email", description: "Email address of signature request recipient", }, recipientName: { type: "string", label: "Recipient Name", description: "The full name of the recipient", }, role: { type: "string", label: "Recipient Role", description: "Choose role as defined on template or use a custom value", async options({ account, template, }) { const baseUri = await this.getBaseUri(account); const { signers } = await this.listTemplateRecipients( baseUri, template, ); return signers.map((signer) => { return signer.roleName; }); }, }, }, methods: { _getHeaders() { return { "Authorization": `Bearer ${this.$auth.oauth_access_token}`, "Content-Type": "application/json", }; }, async _makeRequest(method, url, data = null, params = null) { const config = { method, url, headers: this._getHeaders(), data, params, }; return (await axios(config)).data; }, async getUserInfo() { return await this._makeRequest( "GET", "https://account-d.docusign.com/oauth/userinfo", ); }, async getBaseUri(accountId) { const { accounts } = await this.getUserInfo(); const account = accounts.find((a) => a.account_id === accountId); const { base_uri: baseUri } = account; return `${baseUri}/restapi/v2.1/accounts/${accountId}/`; }, async listTemplates(baseUri) { return await this._makeRequest("GET", `${baseUri}templates`); }, async listTemplateRecipients(baseUri, templateId) { return await this._makeRequest( "GET", `${baseUri}templates/${templateId}/recipients`, ); }, async createEnvelope(baseUri, data) { return await this._makeRequest("POST", `${baseUri}envelopes`, data); }, async listFolders(baseUri, params) { return await this._makeRequest("GET", `${baseUri}folders`, null, params); }, async listFolderItems(baseUri, params, folderId) { return await this._makeRequest("GET", `${baseUri}folders/${folderId}`, null, params); }, async listEnvelopes(baseUri, params) { return await this._makeRequest( "GET", `${baseUri}envelopes`, null, params, ); }, }, }; <|start_filename|>components/slack/actions/update-message/update-message.js<|end_filename|> const slack = require("../../slack.app.js"); module.exports = { key: "slack-update-message", name: "Update Message", description: "Update a message", version: "0.1.0", type: "action", props: { slack, conversation: { propDefinition: [ slack, "conversation", ], }, timestamp: { propDefinition: [ slack, "timestamp", ], }, text: { propDefinition: [ slack, "text", ], }, as_user: { propDefinition: [ slack, "as_user", ], description: "Pass true to update the message as the authed user. Bot users in this context are considered authed users.", }, attachments: { propDefinition: [ slack, "attachments", ], }, }, async run() { return await this.slack.sdk().chat.update({ ts: this.timestamp, text: this.text, channel: this.conversation, as_user: this.as_user, attachments: this.attachments, }); }, }; <|start_filename|>components/dev_to/dev_to.app.js<|end_filename|> module.exports = { type: "app", app: "dev_to", } <|start_filename|>components/intercom/intercom.app.js<|end_filename|> const axios = require("axios"); module.exports = { type: "app", app: "intercom", methods: { _getBaseURL() { return "https://api.intercom.io"; }, _getHeader() { return { Authorization: `Bearer ${this.$auth.oauth_access_token}`, Accept: "application/json", }; }, monthAgo() { const now = new Date(); const monthAgo = new Date(now.getTime()); monthAgo.setMonth(monthAgo.getMonth() - 1); return monthAgo; }, async getCompanies(lastCompanyCreatedAt) { let results = null; let starting_after = null; let done = false; const companies = []; while ((!results || results.data.pages.next) && !done) { if (results) starting_after = results.data.pages.next.starting_after; const config = { method: "GET", url: `${this._getBaseURL()}/companies${starting_after ? "?starting_after=" + starting_after : ""}`, headers: this._getHeader(), }; results = await axios(config); for (const company of results.data.data) { if (company.created_at > lastCompanyCreatedAt) companies.push(company); else done = true; } } return companies; }, async getConversation(id) { const config = { method: "GET", url: `${this._getBaseURL()}/conversations/${id}`, headers: this._getHeader(), }; return await axios(config); }, async getEvents(user_id, nextURL = null) { let results = null; let since = null; const events = []; while (!results || results.data.pages.next) { if (results) nextURL = results.data.pages.next; const url = nextURL || `${this._getBaseURL()}/events?type=user&intercom_user_id=${user_id}`; const config = { method: "GET", url, headers: this._getHeader(), }; results = await axios(config); for (const result of results.data.events) { events.push(result); } if (results.data.pages.since) since = results.data.pages.since; } return { events, since }; }, async searchContacts(data, starting_after = null) { const config = { method: "POST", url: `${this._getBaseURL()}/contacts/search${ starting_after ? "?starting_after=" + starting_after : "" }`, headers: this._getHeader(), data, }; return await axios(config); }, async searchContacts(data) { let results = null; let starting_after = null; let config = null; const contacts = []; while (!results || results.data.pages.next) { if (results) starting_after = results.data.pages.next.starting_after; config = { method: "POST", url: `${this._getBaseURL()}/contacts/search${starting_after ? "?starting_after=" + starting_after : ""}`, headers: this._getHeader(), data, }; results = await axios(config); for (const contact of results.data.data) { contacts.push(contact); } } return contacts; }, async searchConversations(data) { let results = null; let starting_after = null; let config = null; const conversations = []; while (!results || results.data.pages.next) { if (results) starting_after = results.data.pages.next.starting_after; config = { method: "POST", url: `${this._getBaseURL()}/conversations/search${starting_after ? "?starting_after=" + starting_after : ""}`, headers: this._getHeader(), data, }; results = await axios(config); for (const result of results.data.conversations) { conversations.push(result); } } return conversations; }, }, }; <|start_filename|>components/github/sources/new-watcher/new-watcher.js<|end_filename|> const github = require("../../github.app.js"); const common = require("../common-polling.js"); module.exports = { ...common, key: "github-new-watcher", name: "New Watcher", description: "Emit new events when new watchers are added to a repository", version: "0.0.3", type: "source", dedupe: "last", props: { ...common.props, repoFullName: { propDefinition: [ github, "repoFullName", ], }, }, methods: { generateMeta(data) { const ts = Date.now(); return { id: data.id, summary: data.login, ts, }; }, }, async run() { const watchers = await this.github.getWatchers({ repoFullName: this.repoFullName, }); watchers.forEach((watcher) => { const meta = this.generateMeta(watcher); this.$emit(watcher, meta); }); }, }; <|start_filename|>components/intercom/sources/tag-added-to-lead/tag-added-to-lead.js<|end_filename|> const intercom = require("../../intercom.app.js"); module.exports = { key: "intercom-tag-added-to-lead", name: "Tag Added To Lead", description: "Emits an event each time a new tag is added to a lead.", version: "0.0.1", dedupe: "unique", props: { intercom, db: "$.service.db", timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 15, }, }, }, async run(event) { const data = { query: { field: "role", operator: "=", value: "lead", }, }; const results = await this.intercom.searchContacts(data); for (const lead of results) { if (lead.tags.data.length > 0) { for (const tag of lead.tags.data) { this.$emit(tag, { id: `${lead.id}${tag.id}`, summary: `Tag added to ${lead.name ? lead.name : lead.id}`, ts: Date.now(), }); } } } }, }; <|start_filename|>components/google_drive/sources/common-webhook.js<|end_filename|> const includes = require("lodash/includes"); const { v4: uuid } = require("uuid"); const googleDrive = require("../google_drive.app.js"); const { WEBHOOK_SUBSCRIPTION_RENEWAL_SECONDS } = require("../constants.js"); module.exports = { props: { googleDrive, db: "$.service.db", http: "$.interface.http", drive: { propDefinition: [ googleDrive, "watchedDrive", ], }, watchForPropertiesChanges: { propDefinition: [ googleDrive, "watchForPropertiesChanges", ], }, timer: { label: "Push notification renewal schedule", description: "The Google Drive API requires occasional renewal of push notification subscriptions. **This runs in the background, so you should not need to modify this schedule**.", type: "$.interface.timer", default: { intervalSeconds: WEBHOOK_SUBSCRIPTION_RENEWAL_SECONDS, }, }, }, hooks: { async activate() { // Called when a component is created or updated. Handles all the logic // for starting and stopping watch notifications tied to the desired // files. const channelID = uuid(); const { startPageToken, expiration, resourceId, } = await this.googleDrive.activateHook( channelID, this.http.endpoint, this.getDriveId(), ); // We use and increment the pageToken as new changes arrive, in run() this._setPageToken(startPageToken); // Save metadata on the subscription so we can stop / renew later // Subscriptions are tied to Google's resourceID, "an opaque value that // identifies the watched resource". This value is included in request headers this._setSubscription({ resourceId, expiration, }); this._setChannelID(channelID); }, async deactivate() { const channelID = this._getChannelID(); const { resourceId } = this._getSubscription(); await this.googleDrive.deactivateHook(channelID, resourceId); this._setSubscription(null); this._setChannelID(null); this._setPageToken(null); }, }, methods: { _getSubscription() { return this.db.get("subscription"); }, _setSubscription(subscription) { this.db.set("subscription", subscription); }, _getChannelID() { return this.db.get("channelID"); }, _setChannelID(channelID) { this.db.set("channelID", channelID); }, _getPageToken() { return this.db.get("pageToken"); }, _setPageToken(pageToken) { this.db.set("pageToken", pageToken); }, isMyDrive(drive = this.drive) { return googleDrive.methods.isMyDrive(drive); }, getDriveId(drive = this.drive) { return googleDrive.methods.getDriveId(drive); }, /** * This method returns the types of updates/events from Google Drive that * the event source should listen to. This base implementation returns an * empty list, which means that any event source that extends this module * and that does not refine this implementation will essentially ignore * every incoming event from Google Drive. * * @returns * @type {UpdateType[]} */ getUpdateTypes() { return []; }, /** * This method is responsible for processing a list of changed files * according to the event source's purpose. As an abstract method, it must * be implemented by every event source that extends this module. * * @param {object[]} [changedFiles] - the list of file changes, as [defined * by the API](https://bit.ly/3h7WeUa) * @param {object} [headers] - an object containing the request headers of * the webhook call made by Google Drive */ processChanges() { throw new Error("processChanges is not implemented"); }, }, async run(event) { // This function is polymorphic: it can be triggered as a cron job, to make // sure we renew watch requests for specific files, or via HTTP request (the // change payloads from Google) const subscription = this._getSubscription(); const channelID = this._getChannelID(); const pageToken = this._getPageToken(); // Component was invoked by timer if (event.timestamp) { const { newChannelID, newPageToken, expiration, resourceId, } = await this.googleDrive.invokedByTimer( this.drive, subscription, this.http.endpoint, channelID, pageToken, ); this._setSubscription({ expiration, resourceId, }); this._setChannelID(newChannelID); this._setPageToken(newPageToken); return; } const { headers } = event; if (!this.googleDrive.checkHeaders(headers, subscription, channelID)) { return; } if (!includes(this.getUpdateTypes(), headers["x-goog-resource-state"])) { console.log( `Update type ${headers["x-goog-resource-state"]} not in list of updates to watch: `, this.getUpdateTypes(), ); return; } // We observed false positives where a single change to a document would trigger two changes: // one to "properties" and another to "content,properties". But changes to properties // alone are legitimate, most users just won't want this source to emit in those cases. // If x-goog-changed is _only_ set to "properties", only move on if the user set the prop if ( !this.watchForPropertiesChanges && headers["x-goog-changed"] === "properties" ) { console.log( "Change to properties only, which this component is set to ignore. Exiting", ); return; } const driveId = this.getDriveId(); const changedFilesStream = this.googleDrive.listChanges(pageToken, driveId); for await (const changedFilesPage of changedFilesStream) { const { changedFiles, nextPageToken, } = changedFilesPage; // Process all the changed files retrieved from the current page await this.processChanges(changedFiles, headers); // After successfully processing the changed files, we store the page // token of the next page this._setPageToken(nextPageToken); } }, }; <|start_filename|>components/ringcentral/sources/common/http-based.js<|end_filename|> const template = require("lodash/template"); const { v4: uuid } = require("uuid"); const base = require("./base"); const notificationTypes = require("./notification-types"); module.exports = { ...base, dedupe: "unique", props: { ...base.props, http: { type: "$.interface.http", customResponse: true, }, }, hooks: { ...base.hooks, async activate() { const verificationToken = this._getVerificationToken(); this.db.set("verificationToken", verificationToken); const opts = { address: this.http.endpoint, eventFilters: this._getEventFilters(), verificationToken, }; const { id: webhookId, } = await this.ringcentral.createHook(opts); this.db.set("webhookId", webhookId); }, async deactivate() { const webhookId = this.db.get("webhookId"); await this.ringcentral.deleteHook(webhookId); this.db.set("verificationToken", null); }, }, methods: { ...base.methods, _getPropValues() { return Object.entries(this) .filter(([_, value]) => value != null) .reduce((accum, [prop, value]) => ({ ...accum, [prop]: value, }), {}); }, _getEventFilters() { const eventKeys = this.getSupportedNotificationTypes(); const propValues = this._getPropValues(); return notificationTypes .filter(({ key }) => eventKeys.has(key)) .map(({ filter }) => template(filter)) .map((templateFn) => templateFn(propValues)); }, _getVerificationToken() { return uuid().replace(/-/g, ""); }, /** * Provides the set of notification types to which an HTTP-based event * source subscribes. This should be a subset of the `key` properties * available in the `notification-types` module. * * @return {Set} The set of supported notification type keys */ getSupportedNotificationTypes() { throw new Error("getSupportedNotificationTypes is not implemented"); }, /** * Validate that the incoming HTTP event comes from the expected source, and * reply with a `200` status code and the proper validation token header, as * described here: * https://community.ringcentral.com/questions/1306/validation-token-is-not-returned-when-creating-a-s.html * * In case the event comes from an unrecognized source, reply with a `404` * status code. * * The result of this method indicates whether the incoming event was valid * or not. * * @param {object} event The HTTP event that triggers this event source * @return {boolean} The outcome of the validation check (`true` for valid * events, `false` otherwise) */ validateEvent(event) { const { "validation-token": validationToken, "verification-token": verificationToken, } = event.headers; const expectedVerificationToken = this.db.get("verificationToken") || verificationToken; if (verificationToken !== expectedVerificationToken) { this.http.respond({ status: 404 }); return false; } this.http.respond({ status: 200, headers: { "validation-token": validationToken, }, }); return true; }, /** * Determines if the incoming event is relevant to this particular event * source, so that it's either processed or skipped in case it's relevant or * not, respectively. * * @param {object} event The HTTP event that triggers this event source * @return {boolean} Whether the incoming event is relevant to this event * source or not */ isEventRelevant(event) { return true; }, processEvent(event) { const { body } = event; if (!body) { console.log("Empty event payload. Skipping..."); return; } if (!this.isEventRelevant(event)) { console.log("Event is irrelevant. Skipping...") return; } const meta = this.generateMeta(body); this.$emit(body, meta); }, }, async run(event) { const isValidEvent = this.validateEvent(event); if (!isValidEvent) { console.log("Invalid event. Skipping..."); return; } return this.processEvent(event); }, }; <|start_filename|>components/webflow/webflow.app.js<|end_filename|> const Webflow = require("webflow-api"); module.exports = { type: "app", app: "webflow", methods: { _apiVersion() { return "1.0.0"; }, _authToken() { return this.$auth.oauth_access_token; }, _createApiClient() { const token = this._authToken(); const version = this._apiVersion(); const clientOpts = { token, version, }; return new Webflow(clientOpts); }, async listSites() { const apiClient = this._createApiClient(); return apiClient.sites(); }, async createWebhook(siteId, url, triggerType, filter = {}) { const apiClient = this._createApiClient(); const params = { siteId, triggerType, url, filter, }; return apiClient.createWebhook(params); }, async removeWebhook(siteId, webhookId) { const apiClient = this._createApiClient(); const params = { siteId, webhookId, }; return apiClient.removeWebhook(params); }, async listCollections(siteId) { const apiClient = this._createApiClient(); const params = { siteId, }; return apiClient.collections(params); }, }, }; <|start_filename|>components/twitter/sources/new-tweet-in-list/new-tweet-in-list.js<|end_filename|> const base = require("../common/tweets"); module.exports = { ...base, key: "twitter-new-tweet-in-list", name: "New Tweet in List", description: "Emit new Tweets posted by members of a list", version: "0.0.1", props: { ...base.props, includeRetweets: { propDefinition: [ base.props.twitter, "includeRetweets", ], }, list: { type: "string", description: "The Twitter list to watch for new Tweets", async options(context) { const { page } = context; if (page !== 0) { return []; } const lists = await this.twitter.getLists(); return lists.map(({ name, id_str, }) => ({ label: name, value: id_str, })); }, }, includeEntities: { type: "boolean", label: "Entities", description: ` Include the 'entities' node, which offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags `, default: false, }, }, methods: { ...base.methods, shouldIncludeRetweets() { return this.includeRetweets !== "exclude"; }, retrieveTweets() { return this.twitter.getListTweets({ list_id: this.list, count: this.count, since_id: this.getSinceId(), includeEntities: this.includeEntities, includeRetweets: this.shouldIncludeRetweets(), }); }, }, }; <|start_filename|>components/twitter_developer_app/sources/new-tweet-metrics/new-tweet-metrics.js<|end_filename|> const isEqual = require("lodash/isEqual"); const common = require("../common"); module.exports = { ...common, key: "twitter_developer_app-new-tweet-metrics", name: "New Tweet Metrics", version: "0.0.2", dedupe: "unique", props: { ...common.props, tweetIds: { type: "string[]", label: "Tweet IDs", description: "The IDs of the Tweets for which to retrieve metrics", }, onlyChangedMetrics: { type: "boolean", label: "Only Changed Metrics?", description: ` When enabled, this event source will only emit events if the values of the retrieved metrics changed `, default: false, }, excludePublic: { type: "boolean", label: "Exclude Public Metrics", description: "Exclude public metrics from the emitted events", default: false, }, excludeNonPublic: { type: "boolean", label: "Exclude Non-Public Metrics", description: "Exclude non-public metrics from the emitted events", default: false, }, excludeOrganic: { type: "boolean", label: "Exclude Organic Metrics", description: "Exclude organic metrics from the emitted events", default: false, }, }, hooks: { deactivate() { this._setLastMetrics(null); }, }, methods: { ...common.methods, _getLastMetrics() { return this.db.get("lastmetrics"); }, _setLastMetrics(metrics) { this.db.set("lastmetrics", metrics); }, _shouldSkipExecution(metrics) { return ( this.onlyChangedMetrics && isEqual(this._getLastMetrics(), metrics) ); }, generateMeta({ event, metrics, }) { const { id: tweetId } = metrics; const { timestamp: ts } = event; const id = `${tweetId}-${ts}`; const summary = "New metrics"; return { id, summary, ts, }; }, }, async run(event) { const metrics = await this.twitter_developer_app.getMetricsForIds({ tweetIds: this.tweetIds, excludePublic: this.excludePublic, excludeNonPublic: this.excludeNonPublic, excludeOrganic: this.excludeOrganic, }); if (this._shouldSkipExecution(metrics)) { console.log("No new metrics found. Skipping..."); return; } const meta = this.generateMeta({ event, metrics, }); this.$emit(metrics, meta); this._setLastMetrics(metrics); }, }; <|start_filename|>components/twitch/actions/unblock-user/unblock-user.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, name: "Unblock User", key: "twitch-unblock-user", description: "Unblocks a user; that is, deletes a specified target user to your blocks list", version: "0.0.1", type: "action", props: { ...common.props, user: { propDefinition: [ common.props.twitch, "user", ], description: "User ID of the user to be unblocked", }, }, async run() { const params = { target_user_id: this.user, }; const { status, statusText, } = await this.twitch.unblockUser(params); return status == 204 ? "User Successfully Unblocked" : `${status} ${statusText}`; }, }; <|start_filename|>components/microsoft_onedrive/microsoft_onedrive.app.js<|end_filename|> const axios = require("axios"); const get = require("lodash/get"); const querystring = require("querystring"); const retry = require("async-retry"); module.exports = { type: "app", app: "microsoft_onedrive", methods: { _apiUrl() { return "https://graph.microsoft.com/v1.0"; }, _authToken() { return this.$auth.oauth_access_token; }, /** * This is a utility method that returns the path to the authenticated * user's OneDrive drive * * @returns the path to the user's drive */ _getMainDrivePath() { return "/me/drive"; }, /** * This is a utility method that returns the path to a OneDrive drive based * on its identifier, or the authenticated user's drive if an identifier is * not specified. * * @param {string} [driveId] the OneDrive drive identifier. When not * provided, the method returns the path of the authenticated user's drive. * @returns the path to the specified drive */ _getDrivePath(driveId) { return driveId ? `/drives/${driveId}` : this._getMainDrivePath(); }, /** * This is a utility method that returns the path to a OneDrive item based * on its identifier, or the root if an identifier is not specified. * * @param {string} [itemId] the OneDrive item identifier. When not * provided, the method returns the path of the root item. * @returns the path to the specified drive */ _getDriveItemPath(itemId) { return itemId ? `/items/${itemId}` : "/root"; }, /** * This is a utility method that returns the API URL that references a * OneDrive drive * * @param {string} [driveId] the OneDrive drive identifier. When not * provided, the method returns the URL of the authenticated user's drive. * @returns the API URL referrencing a OneDrive drive */ _driveEndpoint(driveId) { const baseUrl = this._apiUrl(); const drivePath = this._getDrivePath(driveId); return `${baseUrl}${drivePath}`; }, /** * This is a utility method that returns the API URL of the [OneDrive Delta * Link](https://bit.ly/3fNawcs) endpoint. Depending on the input arguments * provided by the caller, the endpoint will refer to the Delta endpoint of * a particular drive and/or folder. * * @example * // returns `${baseUrl}/me/drive/root/delta` * this._deltaEndpoint(); * * @example * // returns `${baseUrl}/drives/bf3ec8cc5e81199f/root/delta` * this._deltaEndpoint({ driveId: "bf3ec8cc5e81199f" }); * * @example * // returns `${baseUrl}/me/drive/items/BF3EC8CC5E81199F!104/delta` * this._deltaEndpoint({ folderId: "BF3EC8CC5E81199F!104" }); * * @example * // returns `${baseUrl}/drives/bf3ec8cc5e81199f/items/BF3EC8CC5E81199F!104/delta` * this._deltaEndpoint({ * driveId: "bf3ec8cc5e81199f", * folderId: "BF3EC8CC5E81199F!104", * }); * * @param {object} [opts] an object containing the different options * referring to the target of the Delta Link endpoint * @param {string} [opts.driveId] the OneDrive drive identifier. When not * provided, the method uses the ID of the authenticated user's drive. * @param {string} [opts.folderId] when provided, the returned URL will * point to the Delta Link endpoint of the specified folder. Otherwise, it * will point to the root of the drive. * @returns a [OneDrive Delta Link](https://bit.ly/3fNawcs) endpoint URL */ _deltaEndpoint({ driveId, folderId, } = {}) { const baseUrl = this._apiUrl(); const drivePath = this._getDrivePath(driveId); const itemPath = this._getDriveItemPath(folderId); return `${baseUrl}${drivePath}${itemPath}/delta`; }, /** * This is a utility method that returns the API URL of the endpoint * referencing to a drive folder's [children](https://bit.ly/3sC6V3F). The * specific drive and item are customizable. * * @example * // returns `${baseUrl}/me/drive/root/children` * this._deltaEndpoint(); * * @example * // returns `${baseUrl}/drives/bf3ec8cc5e81199f/root/children` * this._deltaEndpoint({ driveId: "bf3ec8cc5e81199f" }); * * @example * // returns `${baseUrl}/me/drive/items/BF3EC8CC5E81199F!104/children` * this._deltaEndpoint({ folderId: "BF3EC8CC5E81199F!104" }); * * @example * // returns `${baseUrl}/drives/bf3ec8cc5e81199f/items/BF3EC8CC5E81199F!104/children` * this._deltaEndpoint({ * driveId: "bf3ec8cc5e81199f", * folderId: "BF3EC8CC5E81199F!104", * }); * * @param {object} [opts] an object containing the different options * referring to the target of the Delta Link endpoint * @param {string} [opts.driveId] the OneDrive drive identifier. When not * provided, the method uses the ID of the authenticated user's drive. * @param {string} [opts.folderId] when provided, the returned URL will * point to the children endpoint of the specified folder. Otherwise, it * will point to the root of the drive. * @returns an endpoint URL referencing the drive folder's children */ _driveChildrenEndpoint({ driveId, folderId, } = {}) { const baseUrl = this._apiUrl(); const drivePath = this._getDrivePath(driveId); const itemPath = this._getDriveItemPath(folderId); return `${baseUrl}${drivePath}${itemPath}/children`; }, _subscriptionsEndpoint(id) { const baseUrl = this._apiUrl(); const url = `${baseUrl}/subscriptions`; return id ? `${url}/${id}` : url; }, _makeRequestConfig() { const authToken = this._authToken(); const headers = { "Authorization": `bearer ${authToken}`, "User-Agent": "@PipedreamHQ/pipedream v0.1", }; return { headers, }; }, /** * This method is intended to be used as a decorator around external API * calls. It provides exponential backoff retries for the calls made to a * specified function, and aborts with an exception if the call fails with a * non-retriable error or if the maximum retry count is reached. * * @param {function} apiCall is a function that encapsulates an API call. * The function will be called without any additional parameters, so this * argument should already define the closure needed to operate. * @param {function} [isRequestRetriable] is a function that determines * whether a failed request should be retried or not based on the exception * thrown by a call to the `apiCall` argument. When it's not provided, the * behaviour defaults to retrying the call based on the value of * `exception.response.status` (see the `_isStatusCodeRetriable` method). * @returns a promise containing the result of the call to `apiCall`, or an * exception containing the details about the last error */ _withRetries( apiCall, isRequestRetriable = this._isStatusCodeRetriable.bind(this), ) { const retryOpts = { retries: 5, factor: 2, minTimeout: 2000, // In milliseconds }; return retry(async (bail, retryCount) => { try { return await apiCall(); } catch (err) { if (!isRequestRetriable(err)) { const statusCode = get(err, [ "response", "status", ]); const errData = get(err, [ "response", "data", ], {}); return bail(new Error(` Unexpected error (status code: ${statusCode}): ${JSON.stringify(errData, null, 2)} `)); } console.log(` [Attempt #${retryCount}] Temporary error: ${err.message} `); throw err; } }, retryOpts); }, _isStatusCodeRetriable(responseErr) { const statusCode = get(responseErr, [ "response", "status", ]); return [ 429, 500, 503, 509, ].includes(statusCode); }, _isHookRequestRetriable(responseErr) { // Sometimes an API call to create a webhook/subscription fails because // our component was unable to quickly validate the subscription. In those // cases, we want to retry the request since at this point the webhook is // not created but the request itself is well formed. // // See the docs for more information on how webhooks are validated upon // creation: https://bit.ly/3fzc3Tr const errPattern = /endpoint must respond .*? to validation request/i; const errMsg = get(responseErr, [ "response", "data", "error", "message", ], ""); return ( errPattern.test(errMsg) || this._isStatusCodeRetriable(responseErr) ); }, _getDefaultHookExpirationDateTime() { // 30 days from now const futureTimestamp = Date.now() + 43200 * 60 * 1000; return new Date(futureTimestamp).toISOString(); }, /** * This method creates a [OneDrive webhook](https://bit.ly/2PxfQ9j) to * monitor a specific resource, defaulted to the authenticated user's drive. * * @param {string} notificationUrl the target URL of the webhook * @param {object} [opts] an object containing the different options for * the hook creation * @param {string} [opts.driveId] the resource to which the webhook will * subscribe for events * @param {string} [opts.expirationDateTime] the timestamp of the hook * subscription expiration, in ISO-8601 format. Defaults to 30 days after * the time this method is called. * @returns the ID of the created webhook */ async createHook(notificationUrl, { driveId, expirationDateTime = this._getDefaultHookExpirationDateTime(), } = {}) { const url = this._subscriptionsEndpoint(); const drivePath = this._getDrivePath(driveId); const resource = `${drivePath}/root`; const requestData = { notificationUrl, resource, expirationDateTime, changeType: "updated", }; const requestConfig = this._makeRequestConfig(); const { data: { id: hookId } = {} } = await this._withRetries( () => axios.post(url, requestData, requestConfig), this._isHookRequestRetriable.bind(this), ); return hookId; }, /** * This method performs an update to a [OneDrive * webhook](https://bit.ly/2PxfQ9j). An example of such operation is to * extend the expiration time of a webhook subscription. * * @param {string} id the ID of the webhook to update * @param {object} [opts] the fields to update in the webhook * @param {string} [opts.expirationDateTime] the new expiration date of the * webhook subscription */ async updateHook(id, { expirationDateTime } = {}) { const url = this._subscriptionsEndpoint(id); const requestData = { expirationDateTime, }; const requestConfig = this._makeRequestConfig(); await this._withRetries( () => axios.patch(url, requestData, requestConfig), this._isHookRequestRetriable.bind(this), ); }, /** * This method deletes an existing [OneDrive * webhook](https://bit.ly/2PxfQ9j) * * @param {string} id the ID of the webhook to delete */ async deleteHook(id) { const url = this._subscriptionsEndpoint(id); const requestConfig = this._makeRequestConfig(); await this._withRetries( () => axios.delete(url, requestConfig), ); }, /** * This method returns a parameterized [OneDrive Delta * Link](https://bit.ly/3fNawcs) for a particular drive and/or item * (defaulting to the root of the authenticated user's drive). The link will * also include additional query parameters, depending on the options * provded by the caller. * * @param {object} [opts] an object containing the different options to * customize the Delta Link * @param {string} [opts.driveId] the OneDrive drive identifier. When not * provided, the method uses the ID of the authenticated user's drive. * @param {string} [opts.folderId] the top-level folder that the returned * Delta Link will track. When left unset, the link will refer to the entire * drive. * @param {number} [opts.pageSize] the size of the page that a call to the * returned Delta Link will retrieve (see the `$top` parameter in the [Delta * Link docs](https://bit.ly/3sRzRpn)) * @param {string} [opts.token] a [Delta Link * token](https://bit.ly/3ncApEf), which will be directly added to the * returned link. Especially useful when retrieving the _latest_ Delta Link. * @returns a [OneDrive Delta Link](https://bit.ly/3fNawcs) */ getDeltaLink({ driveId, folderId, pageSize, token, } = {}) { const url = this._deltaEndpoint({ driveId, folderId, }); const params = {}; if (pageSize) { params.$top = Math.max(pageSize, 1); } if (token) { params.token = token; } const paramsString = querystring.stringify(params); return `${url}?${paramsString}`; }, /** * This method retrieves the [latest OneDrive Delta * Link](https://bit.ly/3wB5d5O) for the authenticated user's drive * * @param {object} [opts] an object containing the different options to * customize the retrieved Delta Link * @param {string} [opts.folderId] the top-level folder to track with the * Delta Link. When left unset, the link will refer to the entire drive. * @returns the [latest OneDrive Delta Link](https://bit.ly/3wB5d5O) */ async getLatestDeltaLink({ folderId } = {}) { const params = { token: "<PASSWORD>", folderId, }; const url = this.getDeltaLink(params); const requestConfig = this._makeRequestConfig(); const { data } = await this._withRetries( () => axios.get(url, requestConfig), ); return data["@odata.deltaLink"]; }, /** * This generator method scans the latest updated items in a OneDrive drive * based on the provided Delta Link. It yields drive items until the updated * items collection is exhausted, after which it finally returns the Delta * Link to use in future scans. * * @param {string} deltaLink the [OneDrive Delta * Link](https://bit.ly/3fNawcs) from where to start scanning the drive's * items * @yields the next updated item in the drive * @returns the Delta Link to use in the next drive scan */ async *scanDeltaItems(deltaLink) { const requestConfig = this._makeRequestConfig(); let url = deltaLink; while (url) { // See the docs for more information on the format of the delta API // response: https://bit.ly/31I0wZP const { data } = await this._withRetries( () => axios.get(url, requestConfig), ); const { "@odata.nextLink": nextLink, "@odata.deltaLink": nextDeltaLink, "value": items, } = data; for (const item of items) { yield item; } if (items.length === 0 || nextDeltaLink) { return nextDeltaLink; } url = nextLink; } }, /** * This generator method scans the folders under the specified OneDrive * drive and/or folder. The scan is limited to the root of the specified * drive and/or folder (i.e. it does **not** perform a recursive scan). * * @param {object} [opts] an object containing the different options * referring to the target of the Delta Link endpoint * @param {string} [opts.driveId] the OneDrive drive identifier. When not * provided, the method uses the ID of the authenticated user's drive. * @param {string} [opts.folderId] when provided, the method will return * the child folders under this one. Otherwise, it will stick to the root of * the drive. * @yields the next child folder */ async *listFolders({ driveId, folderId, } = {}) { const fieldsToRetrieve = [ "folder", "id", "name", ]; const params = { $orderby: "name", $select: fieldsToRetrieve.join(","), }; const baseRequestConfig = this._makeRequestConfig(); const requestConfig = { ...baseRequestConfig, params, }; let url = this._driveChildrenEndpoint({ driveId, folderId, }); while (url) { const { data } = await this._withRetries( () => axios.get(url, requestConfig), ); const { "@odata.nextLink": nextLink, "value": children, } = data; for (const child of children) { if (!child.folder) { // We skip non-folder children continue; } yield child; } url = nextLink; } }, }, }; <|start_filename|>components/twitter_developer_app/actions/send-dm/send-dm.js<|end_filename|> const twitter = require('../../twitter_developer_app.app.js') const Twit = require('twit') module.exports = { key: "twitter_developer_app-send-dm", name: "Send Direct Message (DM)", description: "Send a DM to a user.", version: "0.0.2", type: "action", props: { twitter, recipient_id: { type: "string", label: "Recipient ID", description: "The ID of the user who should receive the direct message. You must pass the string value of the numeric id (i.e, the value for the `id_str` field in Twitter's `user` object). For example, the correct ID to send a DM to `@pipedream` is `1067926271856766976`. If you only have the user's screen name, lookup the user first and pass the `id_str` to this field." }, message: { type: "string", description: "The text of your direct message. Max length of 10,000 characters. Max length of 9,990 characters if used as a [Welcome Message](https://developer.twitter.com/en/docs/direct-messages/welcome-messages/api-reference/new-welcome-message)." }, }, async run(event) { const { api_key, api_secret_key, access_token, access_token_secret } = this.twitter.$auth const T = new Twit({ consumer_key: api_key, consumer_secret: api_secret_key, access_token, access_token_secret, timeout_ms: 60 * 1000, // optional HTTP request timeout to apply to all requests. strictSSL: true, // optional - requires SSL certificates to be valid. }) const response = await T.post("direct_messages/events/new", { "event": { "type": "message_create", "message_create": { "target": { "recipient_id": this.recipient_id }, "message_data": { "text": this.message } } } }); return response.data.event }, } <|start_filename|>components/sentry/sentry.app.js<|end_filename|> const axios = require("axios"); const { createHmac } = require("crypto"); const parseLinkHeader = require("parse-link-header"); const slugify = require("slugify"); module.exports = { type: "app", app: "sentry", propDefinitions: { organizationSlug: { type: "string", label: "Organization", description: "The organization for which to consider issues events", async options(context) { const url = this._organizationsEndpoint(); const params = {}; // We don't need to provide query parameters at the moment. const { data, next } = await this._propDefinitionsOptions(url, params, context); const options = data.map(this._organizationObjectToOption); return { options, context: { nextPage: next, }, }; }, }, }, methods: { _apiUrl() { return "https://sentry.io/api/0"; }, _organizationsEndpoint() { const baseUrl = this._apiUrl(); return `${baseUrl}/organizations/`; }, _integrationsEndpoint(integrationSlug) { const baseUrl = this._apiUrl(); const url = `${baseUrl}/sentry-apps`; return integrationSlug ? `${url}/${integrationSlug}/` : `${url}/`; }, _authToken() { return this.$auth.auth_token; }, _makeRequestConfig() { const authToken = this._authToken(); const headers = { "Authorization": `Bearer ${authToken}`, "User-Agent": "@PipedreamHQ/pipedream v0.1", }; return { headers, }; }, _organizationObjectToOption(organization) { const { name, slug } = organization; const label = `${name} (${slug})`; return { label, value: slug, }; }, async _propDefinitionsOptions(url, params, { page, prevContext }) { let requestConfig = this._makeRequestConfig(); // Basic axios request config if (page === 0) { // First time the options are being retrieved. // Include the parameters provided, which will be persisted // across the different pages. requestConfig = { ...requestConfig, params, }; } else if (prevContext.nextPage) { // Retrieve next page of options. url = prevContext.nextPage.url; } else { // No more options available. return { data: [] }; } const { data, headers: { link }, } = await axios.get(url, requestConfig); // https://docs.sentry.io/api/pagination/ const { next } = parseLinkHeader(link); return { data, next, }; }, _baseIntegrationParams() { return { scopes: [ "event:read", ], events: [ "issue", ], isAlertable: true, isInternal: true, verifyInstall: false, }; }, _formatIntegrationName(rawName) { const options = { remove: /[()]/g, lower: true, }; const enrichedRawName = `pd-${rawName}`; return slugify(enrichedRawName, options).substring(0, 57); }, async createIntegration(eventSourceName, organization, webhookUrl) { const url = this._integrationsEndpoint(); const name = this._formatIntegrationName(eventSourceName); const requestData = { ...this._baseIntegrationParams(), name, organization, webhookUrl, }; const requestConfig = this._makeRequestConfig(); const { data } = await axios.post(url, requestData, requestConfig); return data; }, async deleteIntegration(integrationSlug) { const url = this._integrationsEndpoint(integrationSlug); const requestConfig = this._makeRequestConfig(); await axios.delete(url, requestConfig); }, async disableIntegration(integrationSlug) { const url = this._integrationsEndpoint(integrationSlug); const requestConfig = this._makeRequestConfig(); const requestData = { events: null, isAlertable: false, name: "pipedream (disabled)", webhookUrl: null, }; await axios.put(url, requestData, requestConfig); }, async getClientSecret(integrationSlug) { const url = this._integrationsEndpoint(integrationSlug); const requestConfig = this._makeRequestConfig(); const { data } = await axios.get(url, requestConfig); return data.clientSecret; }, isValidSource(event, clientSecret) { const { headers: { "sentry-hook-signature": signature, }, bodyRaw, } = event; const hmac = createHmac("sha256", clientSecret); hmac.update(bodyRaw, "utf8"); const digest = hmac.digest("hex"); return digest === signature; }, }, }; <|start_filename|>components/textlocal/sources/common/timer-based.js<|end_filename|> const base = require("./base"); module.exports = { ...base, props: { ...base.props, timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 15, // 15 minutes }, }, }, }; <|start_filename|>components/eventbrite/eventbrite.app.js<|end_filename|> const axios = require("axios"); /* timezone-list: https://www.npmjs.com/package/timezones-list */ const timezones = require("timezones-list"); module.exports = { type: "app", app: "eventbrite", propDefinitions: { organization: { type: "string", label: "Organization", async options({ prevContext }) { const { prevHasMore: hasMore = false, prevContinuation: continuation, } = prevContext; const params = hasMore ? { continuation, } : null; const { organizations, pagination, } = await this.listMyOrganizations( params, ); const options = organizations.map((org) => { const { name, id, } = org; return { label: name, value: id, }; }); const { has_more_items: prevHasMore, continuation: prevContinuation, } = pagination; return { options, context: { prevHasMore, prevContinuation, }, }; }, }, eventId: { type: "integer", label: "Event ID", description: "Enter the ID of an event", }, timezone: { type: "string", label: "Timezone", description: "The timezone", default: "UTC", async options() { timezones.unshift({ label: "UTC (GMT+00:00)", tzCode: "UTC", }); return timezones.map(({ label, tzCode, }) => ({ label, value: tzCode, })); }, }, }, methods: { _getBaseUrl() { return "https://www.eventbriteapi.com/v3/"; }, _getHeaders() { return { "Authorization": `Bearer ${this.$auth.oauth_access_token}`, "Content-Type": "application/json", }; }, async _makeRequest( method, endpoint, params = null, data = null, url = `${this._getBaseUrl()}${endpoint}`, ) { const config = { method, url, headers: this._getHeaders(), params, data, }; return (await axios(config)).data; }, async createHook(orgId, data) { return await this._makeRequest( "POST", `organizations/${orgId}/webhooks/`, null, data, ); }, async deleteHook(hookId) { return await this._makeRequest("DELETE", `webhooks/${hookId}/`); }, async listMyOrganizations(params) { return await this._makeRequest("GET", "users/me/organizations", params); }, async listEvents( { orgId, params, }, ) { return await this._makeRequest( "GET", `organizations/${orgId}/events/`, params, ); }, async getResource(url) { return await this._makeRequest("GET", null, null, null, url); }, async getEvent(eventId, params = null) { return await this._makeRequest("GET", `events/${eventId}/`, params); }, async getOrderAttendees(orderId) { return await this._makeRequest("GET", `orders/${orderId}/attendees/`); }, async getEventAttendees(eventId, params = null) { return await this._makeRequest( "GET", `events/${eventId}/attendees/`, params, ); }, async createEvent(orgId, data) { return await this._makeRequest( "POST", `organizations/${orgId}/events/`, null, data, ); }, }, }; <|start_filename|>components/clickup/package-lock.json<|end_filename|> { "name": "@pipedream/clickup", "version": "0.0.1", "lockfileVersion": 1, "requires": true, "dependencies": { "axios": { "version": "0.21.1", "resolved": "https://registry.npmjs.org/axios/-/axios-0.21.1.tgz", "integrity": "<KEY> "requires": { "follow-redirects": "^1.10.0" } }, "axios-retry": { "version": "3.1.9", "resolved": "https://registry.npmjs.org/axios-retry/-/axios-retry-3.1.9.tgz", "integrity": "sha512-NFCoNIHq8lYkJa6ku4m+V1837TP6lCa7n79Iuf8/AqATAHYB0ISaAS1eyIenDOfHOLtym34W65Sjke2xjg2fsA==", "requires": { "is-retry-allowed": "^1.1.0" } }, "follow-redirects": { "version": "1.14.2", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.2.tgz", "integrity": "<KEY> }, "is-retry-allowed": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/is-retry-allowed/-/is-retry-allowed-1.2.0.tgz", "integrity": "<KEY> } } } <|start_filename|>components/mailgun/actions/send-email/send-email.js<|end_filename|> const mailgun = require("../../mailgun.app.js"); module.exports = { key: "mailgun-send-email", name: "Mailgun Send Email", description: "Send email with Mailgun.", version: "0.0.1", type: "action", props: { mailgun, domain: { propDefinition: [ mailgun, "domain", ], }, fromName: { type: "string", label: "From Name", description: "Sender name", }, from: { type: "string", label: "From Email", description: "Sender email address", }, replyTo: { type: "string", label: "Reply-To", description: "Sender reply email address", optional: true, }, to: { type: "string[]", label: "To", description: "Recipient email address(es)", }, cc: { type: "string[]", label: "CC", description: "Copy email address(es)", optional: true, }, bcc: { type: "string[]", label: "BCC", description: "Blind copy email address(es)", optional: true, }, subject: { type: "string", label: "Subject", description: "Message subject", }, text: { type: "string", label: "Message Body (text)", }, html: { type: "string", label: "Message Body (HTML)", optional: true, }, testMode: { type: "boolean", label: "Send in test mode?", default: true, description: "Enables sending in test mode. For more information, see the [Mailgun API documentation](https://documentation.mailgun.com/en/latest/api-sending.html#sending)", }, dkim: { type: "boolean", label: "Use DKIM?", default: true, description: "Enables or disables DKIM signatures. For more information, see the [Mailgun API documentation](https://documentation.mailgun.com/en/latest/api-sending.html#sending)", optional: true, }, tracking: { type: "boolean", label: "Use Tracking?", default: true, description: "Enables or disables tracking. For more information, see the [Mailgun API documentation](https://documentation.mailgun.com/en/latest/api-sending.html#sending)", optional: true, }, haltOnError: { propDefinition: [ mailgun, "haltOnError", ], }, }, async run () { try { const msg = { "from": `${this.fromName} <${this.from}>`, "to": this.to, "cc": this.cc, "bcc": this.bcc, "subject": this.subject, "text": this.text, "html": this.html, "o:testmode": this.testMode, }; if (this.replyTo) { msg["h:Reply-To"] = this.replyTo; } if (this.dkim !== null) { msg["o:dkim"] = this.dkim ? "yes" : "no"; } if (this.tracking) { msg["o:tracking"] = "yes"; } return await this.mailgun.api("messages").create(this.domain, msg); } catch (err) { if (this.haltOnError) { throw err; } return err; } }, }; <|start_filename|>components/zoom/package.json<|end_filename|> { "name": "@pipedream/zoom", "version": "0.3.3", "description": "Pipedream Zoom Components", "main": "zoom.app.js", "keywords": [ "pipedream", "zoom" ], "homepage": "https://pipedream.com/apps/zoom", "author": "Pipedream <<EMAIL>> (https://pipedream.com/)", "license": "MIT", "gitHead": "e12480b94cc03bed4808ebc6b13e7fdb3a1ba535", "publishConfig": { "access": "public" } } <|start_filename|>components/microsoft_onedrive/sources/common/constants.js<|end_filename|> module.exports = { // Defaulting to 15 days. The maximum allowed expiration time is 30 days, // according to their API response message: "Subscription expiration can only // be 43200 minutes in the future". // // More information can be found in the official API docs: // https://docs.microsoft.com/en-us/onedrive/developer/rest-api/concepts/using-webhooks?view=odsp-graph-online#expiration WEBHOOK_SUBSCRIPTION_RENEWAL_SECONDS: 43200 * 60 / 2, // The maximum amount of events sent during the initialization of the event // source. The number of emitted events might be lower than this, depending on // whether there's enough data to emit them or not. MAX_INITIAL_EVENT_COUNT: 10, }; <|start_filename|>components/twitch/actions/update-channel/update-channel.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, name: "Update Channel", key: "twitch-update-channel", description: `Update information for the channel owned by the authenticated user. At least one parameter must be provided.`, version: "0.0.1", type: "action", props: { ...common.props, title: { type: "string", label: "Title", description: "The title of the stream. Value must not be an empty string", optional: true, }, game: { type: "string", label: "Game ID", description: `The current game ID being played on the channel. Use “0” or “” (an empty string) to unset the game`, optional: true, }, language: { type: "string", label: "Stream Language", description: `A language value must be either the ISO 639-1 two-letter code for a supported stream language or "other".`, optional: true, }, delay: { type: "string", label: "Delay", description: `Stream delay in seconds. Stream delay is a Twitch Partner feature trying to set this value for other account types will return a 400 error.`, optional: true, }, }, async run() { // get the userID of the authenticated user const userId = await this.getUserId(); let params = { broadcaster_id: userId, game_id: this.game, broadcaster_language: this.language, title: this.title, delay: this.delay, }; // remove empty values from params Object.keys(params).forEach((k) => (params[k] == null || params[k] == "") && delete params[k]); const result = (await this.twitch.updateChannel(params)); // Response code of 204 indicates Channel/Stream updated successfully if (result.status !== 204) return result.data; // return updated channel information params = { broadcaster_id: userId, }; return (await this.twitch.getChannelInformation(params)).data.data; }, }; <|start_filename|>components/supersaas/envConf.js<|end_filename|> exports.urlPrefix = 'https://supersaas.com'; <|start_filename|>components/netlify/sources/new-deploy-failure/new-deploy-failure.js<|end_filename|> const common = require("../../common"); module.exports = { ...common, key: "netlify-new-deploy-failure", name: "New Deploy Failure (Instant)", description: "Emits an event when a new deployment fails", version: "0.0.1", dedupe: "unique", methods: { ...common.methods, getHookEvent() { return "deploy_failed"; }, getMetaSummary(data) { const { commit_ref } = data; return `Deploy failed for commit ${commit_ref}`; }, }, }; <|start_filename|>components/activecampaign/sources/new-automation-webhook/new-automation-webhook.js<|end_filename|> const activecampaign = require("../../activecampaign.app.js"); const common = require("../common.js"); module.exports = { ...common, name: "New Automation Webhook", key: "activecampaign-new-automation-webhook", description: "Emits an event each time an automation sends out webhook data.", version: "0.0.1", props: { ...common.props, timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 15, }, }, automations: { propDefinition: [activecampaign, "automations"] }, }, methods: { isWatchedAutomation(automation) { return ( this.automations.length === 0 || this.automations.includes(automation.id) ); }, isAutomationRelevant(automation) { if (!this.isWatchedAutomation(automation)) return false; const entered = this.db.get(automation.id) || 0; // number of times automation has run if (parseInt(automation.entered) <= entered) return false; this.db.set(automation.id, parseInt(automation.entered)); return true; }, getMeta(automation) { return { id: `${automation.id}${automation.entered}`, summary: automation.name, ts: Date.now(), }; }, }, async run() { let prevContext = { offset: 0 }; let total = 1; let count = 0; while (count < total) { const { results, context } = await this.activecampaign._getNextOptions( this.activecampaign.listAutomations.bind(this), prevContext ); prevContext = context; total = results.meta.total; if (total == 0) continue; for (const automation of results.automations) { count++; if (!this.isAutomationRelevant(automation)) continue; const { id, summary, ts } = this.getMeta(automation); this.$emit(automation, { id, summary, ts, }); } } }, }; <|start_filename|>components/twitch/actions/check-channel-subscription/check-channel-subscription.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, name: "Check Channel Subscription", key: "twitch-check-channel-subscription", description: "Checks if you are subscribed to the specified user's channel", version: "0.0.1", type: "action", props: { ...common.props, user: { propDefinition: [ common.props.twitch, "user", ], description: "User ID of the channel to check for a subscription to", }, }, async run() { // get the userID of the authenticated user const userId = await this.getUserId(); const params = { broadcaster_id: this.user, user_id: userId, }; try { return (await this.twitch.checkUserSubscription(params)).data.data; } catch (err) { // if no subscription is found, a 404 error is returned if (err.message.includes("404")) return `${userId} has no subscription to ${this.user}`; return err; } }, }; <|start_filename|>components/slack/actions/find-user-by-email/find-user-by-email.js<|end_filename|> const slack = require("../../slack.app.js"); module.exports = { key: "slack-find-user-by-email", name: "Find User by Email", description: "Find a user by matching against their email", version: "0.0.1", type: "action", props: { slack, email: { propDefinition: [ slack, "email", ], }, }, async run() { return await this.slack.sdk().users.lookupByEmail({ email: this.email, }); }, }; <|start_filename|>components/pipefy/sources/common.js<|end_filename|> const pipefy = require("../pipefy.app.js"); module.exports = { dedupe: "unique", props: { pipefy, db: "$.service.db", pipeId: { type: "integer", label: "Pipe ID", description: "ID of the Pipe, found in the URL when viewing the Pipe.", }, }, }; <|start_filename|>components/aws/.upm/store.json<|end_filename|> {"version":2,"languages":{"nodejs-npm":{"guessedImports":["aws-sdk","axios","shortid"],"guessedImportsHash":"08190b61ee0169fd35ea81dce6f4754d"}}} <|start_filename|>components/datadog/datadog.app.js<|end_filename|> const axios = require("axios"); const { v4: uuid } = require("uuid"); module.exports = { type: "app", app: "datadog", methods: { _apiKey() { return this.$auth.api_key; }, _applicationKey() { return this.$auth.application_key; }, _baseUrl() { return ( this.$auth.base_url || "https://api.datadoghq.com/api/v1" ); }, _webhooksUrl(name) { const baseUrl = this._baseUrl(); const basePath = "/integration/webhooks/configuration/webhooks"; const path = name ? `${basePath}/${name}` : basePath; return `${baseUrl}${path}`; }, _monitorsUrl(id) { const baseUrl = this._baseUrl(); const basePath = "/monitor"; const path = id ? `${basePath}/${id}` : basePath; return `${baseUrl}${path}`; }, _monitorsSearchUrl() { const baseUrl = this._baseUrl(); return `${baseUrl}/monitor/search`; }, _makeRequestConfig() { const apiKey = this._apiKey(); const applicationKey = this._applicationKey(); const headers = { "DD-API-KEY": apiKey, "DD-APPLICATION-KEY": applicationKey, "User-Agent": "@PipedreamHQ/pipedream v0.1", }; return { headers, }; }, _webhookSecretKeyHeader() { return "x-webhook-secretkey"; }, _webhookTagPattern(webhookName) { return `@webhook-${webhookName}`; }, isValidSource(event, secretKey) { const { headers } = event; return headers[this._webhookSecretKeyHeader()] === secretKey; }, async _getMonitor(monitorId) { const apiUrl = this._monitorsUrl(monitorId); const requestConfig = this._makeRequestConfig(); const { data } = await axios.get(apiUrl, requestConfig); return data; }, async _editMonitor(monitorId, monitorChanges) { const apiUrl = this._monitorsUrl(monitorId); const requestConfig = this._makeRequestConfig(); await axios.put(apiUrl, monitorChanges, requestConfig); }, async *_searchMonitors(query) { const apiUrl = this._monitorsSearchUrl(); const baseRequestConfig = this._makeRequestConfig(); let page = 0; let pageCount; let perPage; do { const params = { page, query, }; const requestConfig = { ...baseRequestConfig, params, }; const { data: { monitors, metadata, }, } = await axios.get(apiUrl, requestConfig); for (const monitor of monitors) { yield monitor; } ++page; pageCount = metadata.page_count; perPage = metadata.per_page; } while (pageCount === perPage); }, async listMonitors(page, pageSize) { const apiUrl = this._monitorsUrl(); const baseRequestConfig = this._makeRequestConfig(); const params = { page, page_size: pageSize, }; const requestConfig = { ...baseRequestConfig, params, }; const { data } = await axios.get(apiUrl, requestConfig); return data; }, async createWebhook( url, payloadFormat = null, secretKey = uuid(), ) { const apiUrl = this._webhooksUrl(); const requestConfig = this._makeRequestConfig(); const name = `pd-${uuid()}`; const customHeaders = { [this._webhookSecretKeyHeader()]: secretKey, }; const requestData = { custom_headers: JSON.stringify(customHeaders), payload: JSON.stringify(payloadFormat), name, url, }; await axios.post(apiUrl, requestData, requestConfig); return { name, secretKey, }; }, async deleteWebhook(webhookName) { const apiUrl = this._webhooksUrl(webhookName); const requestConfig = this._makeRequestConfig(); await axios.delete(apiUrl, requestConfig); }, async addWebhookNotification(webhookName, monitorId) { const { message } = await this._getMonitor(monitorId); const webhookTagPattern = this._webhookTagPattern(webhookName); if (new RegExp(webhookTagPattern).test(message)) { // Monitor is already notifying this webhook return; } const newMessage = `${message}\n${webhookTagPattern}`; const monitorChanges = { message: newMessage, }; await this._editMonitor(monitorId, monitorChanges); }, async removeWebhookNotifications(webhookName) { // Users could have manually added this webhook in other monitors, or // removed the webhook from the monitors specified as user props. Hence, // we need to search through all the monitors that notify this webhook and // remove the notification. const webhookTagPattern = new RegExp( `\n?${this._webhookTagPattern(webhookName)}` ); const monitorSearchResults = this._searchMonitors(webhookName); for await (const monitorInfo of monitorSearchResults) { const { id: monitorId } = monitorInfo; const { message } = await this._getMonitor(monitorId); if (!new RegExp(webhookTagPattern).test(message)) { // Monitor is not notifying this webhook, skip it... return; } const newMessage = message.replace(webhookTagPattern, ""); const monitorChanges = { message: newMessage, }; await this._editMonitor(monitorId, monitorChanges); } }, }, }; <|start_filename|>components/mailgun/actions/verify-email/verify-email.js<|end_filename|> const mailgun = require("../../mailgun.app.js"); module.exports = { key: "mailgun-verify-email", name: "Mailgun Verify Email", description: "Verify email address deliverability with Mailgun.", version: "0.0.1", type: "action", props: { mailgun, email: { propDefinition: [ mailgun, "email", ], }, haltOnError: { propDefinition: [ mailgun, "haltOnError", ], }, }, async run () { try { return await this.mailgun.api("validate").get(this.email); } catch (err) { if (this.haltOnError) { throw err; } return err; } }, }; <|start_filename|>components/twilio/twilio.app.js<|end_filename|> const twilioClient = require("twilio"); module.exports = { type: "app", app: "twilio", propDefinitions: { authToken: { type: "string", secret: true, label: "Twilio Auth Token", description: "Your Twilio auth token, found [in your Twilio console](https://www.twilio.com/console). Required for validating Twilio events.", }, body: { type: 'string', label: 'Message Body', description: 'The text of the message you want to send, limited to 1600 characters.' }, from: { type: "string", label: "From", async options() { const client = this.getClient(); const numbers = await client.incomingPhoneNumbers.list(); return numbers.map((number) => { return number.friendlyName }); }, }, incomingPhoneNumber: { type: "string", label: "Incoming Phone Number", description: "The Twilio phone number where you'll receive messages. This source creates a webhook tied to this incoming phone number, **overwriting any existing webhook URL**.", async options() { const numbers = await this.listIncomingPhoneNumbers(); return numbers.map((number) => { return { label: number.friendlyName, value: number.sid }; }); }, }, mediaUrl: { type: 'string[]', label: 'Media URL', description: 'The URL of the media you wish to send out with the message. The media size limit is `5MB`. You may provide up to 10 media URLs per message.', optional: true }, responseMessage: { type: "string", optional: true, label: "Response Message", description: "The message you want to send in response to incoming messages. Leave this blank if you don't need to issue a response.", }, to: { type: 'string', label: 'To', description: 'The destination phone number in E.164 format. Format with a `+` and country code (e.g., `+16175551212`).' }, }, methods: { getClient() { return twilioClient(this.$auth.Sid, this.$auth.Secret, { accountSid: this.$auth.AccountSid, }); }, async setWebhookURL(phoneNumberSid, params) { const client = this.getClient(); return await client.incomingPhoneNumbers(phoneNumberSid).update(params); }, async setIncomingSMSWebhookURL(phoneNumberSid, url) { const params = { smsMethod: "POST", smsUrl: url, }; return await this.setWebhookURL(phoneNumberSid, params); }, async setIncomingCallWebhookURL(phoneNumberSid, url) { const params = { statusCallbackMethod: "POST", statusCallback: url, }; return await this.setWebhookURL(phoneNumberSid, params); }, async listIncomingPhoneNumbers(params) { const client = this.getClient(); return await client.incomingPhoneNumbers.list(params); }, async listRecordings(params) { const client = this.getClient(); return await client.recordings.list(params); }, async listTranscriptions(params) { const client = this.getClient(); return await client.transcriptions.list(params); }, }, }; <|start_filename|>components/strava/strava.app.js<|end_filename|> // Strava API app file const axios = require("axios"); module.exports = { type: "app", app: "strava", methods: { async _makeAPIRequest(opts) { if (!opts.headers) opts.headers = {}; opts.headers["Authorization"] = `Bearer ${this.$auth.oauth_access_token}`; opts.headers["Content-Type"] = "application/json"; opts.headers["user-agent"] = "@PipedreamHQ/pipedream v0.1"; const { path } = opts; delete opts.path; opts.url = `https://www.strava.com/api/v3${ path[0] === "/" ? "" : "/" }${path}`; return await axios(opts); }, async getActivity(id) { return ( await this._makeAPIRequest({ path: `/activities/${id}`, }) ).data; }, async getAuthenticatedAthlete() { return ( await this._makeAPIRequest({ path: "/athlete", }) ).data; }, }, }; <|start_filename|>components/slack/actions/delete_file/delete_file.js<|end_filename|> const slack = require("../../slack.app.js"); module.exports = { key: "slack-delete-file", name: "Delete File", description: "Delete a file", version: "0.0.1", type: "action", props: { slack, file: { propDefinition: [ slack, "file", ], }, }, async run() { return await this.slack.sdk().files.delete({ file: this.file, }); }, }; <|start_filename|>components/twitch/sources/followed-streams/followed-streams.js<|end_filename|> const common = require("../common-polling.js"); module.exports = { ...common, name: "Followed Streams", key: "twitch-followed-streams", description: "Emits an event when a followed stream is live.", version: "0.0.3", methods: { ...common.methods, getMeta(item) { const { id, started_at: startedAt, title: summary } = item; const ts = new Date(startedAt).getTime(); return { id, summary, ts, }; }, }, hooks: { async deploy() { // get the authenticated user const { data: authenticatedUserData } = await this.twitch.getUsers(); this.db.set("authenticatedUserId", authenticatedUserData[0].id); }, }, async run() { const params = { from_id: this.db.get("authenticatedUserId"), }; // get the user_ids of the streamers followed by the authenticated user const follows = await this.paginate( this.twitch.getUserFollows.bind(this), params ); const followedIds = []; for await (const follow of follows) { followedIds.push(follow.to_id); } // get and emit streams for the followed streamers const streams = await this.paginate(this.twitch.getStreams.bind(this), { user_id: followedIds, }); for await (const stream of streams) { this.$emit(stream, this.getMeta(stream)); } }, }; <|start_filename|>components/calendly/sources/common-webhook.js<|end_filename|> const calendly = require("../calendly.app.js"); const get = require("lodash/get"); module.exports = { props: { calendly, db: "$.service.db", http: { type: "$.interface.http", customResponse: true, }, }, hooks: { async activate() { const events = this.getEvents(); const body = { url: this.http.endpoint, events, }; const resp = await this.calendly.createHook(body); this.db.set("hookId", resp.data.id); }, async deactivate() { await this.calendly.deleteHook(this.db.get("hookId")); }, }, methods: { generateMeta() { throw new Error("generateMeta is not implemented"); }, generateInviteeMeta(body) { const eventId = get(body, "payload.event.uuid"); const inviteeId = get(body, "payload.invitee.uuid"); const summary = get(body, "payload.event_type.name"); const ts = Date.parse(get(body, "time")); return { id: `${eventId}${inviteeId}`, summary, ts, }; }, }, async run(event) { const { body, headers } = event; if (headers["x-calendly-hook-id"] != this.db.get("hookId")) { return this.http.respond({ status: 404 }); } this.http.respond({ status: 200 }); const meta = this.generateMeta(body); this.$emit(body, meta); }, }; <|start_filename|>components/hubspot/sources/common.js<|end_filename|> const hubspot = require("../hubspot.app.js"); module.exports = { props: { hubspot, db: "$.service.db", timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 15, }, }, }, hooks: { async deploy() { // By default, only a limited set of properties are returned from the API. // Get all possible contact properties to request for each contact. const properties = await this.hubspot.createPropertiesArray(); this.db.set("properties", properties); }, }, methods: { _getAfter() { return this.db.get("after") || Date.parse(this.hubspot.monthAgo()); }, _setAfter(after) { this.db.set("after", after); }, async paginate(params, resourceFn, resultType = null, after = null) { let results = null; let done = false; while ((!results || params.after) && !done) { results = await resourceFn(params); if (results.paging) params.after = results.paging.next.after; else delete params.after; if (resultType) results = results[resultType]; for (const result of results) { if (this.isRelevant(result, after)) { this.emitEvent(result); } else { done = true; } } } }, // pagination for endpoints that return hasMore property of true/false async paginateUsingHasMore( params, resourceFn, resultType = null, after = null ) { let hasMore = true; let results, items; while (hasMore) { results = await resourceFn(params); hasMore = results.hasMore; if (hasMore) params.offset = results.offset; if (resultType) items = results[resultType]; else items = results; for (const item of items) { if (this.isRelevant(item, after)) this.emitEvent(item); } } }, emitEvent(result) { const meta = this.generateMeta(result); this.$emit(result, meta); }, isRelevant(result, after) { return true; }, }, }; <|start_filename|>components/twitter/sources/new-unfollower-of-user/new-unfollower-of-user.js<|end_filename|> const base = require("../new-unfollower-of-me/new-unfollower-of-me"); module.exports = { ...base, key: "twitter-new-unfollower-of-user", name: "New Unfollower of User", description: "Emit an event when a specific user loses a follower on Twitter", version: "0.0.5", props: { ...base.props, screen_name: { propDefinition: [ base.props.twitter, "screen_name", ], }, }, methods: { ...base.methods, getScreenName() { return this.screen_name; }, }, }; <|start_filename|>components/twitch/sources/new-videos/new-videos.js<|end_filename|> const common = require("../common-polling.js"); const twitch = require("../../twitch.app.js"); module.exports = { ...common, name: "New Videos", key: "twitch-new-videos", description: "Emits an event when there is a new video from channels you follow.", version: "0.0.1", props: { ...common.props, max: { propDefinition: [twitch, "max"] }, }, methods: { ...common.methods, getMeta({ id, title: summary, created_at: createdAt }) { const ts = new Date(createdAt).getTime(); return { id, summary, ts, }; }, }, async run() { // get the authenticated user const { data: authenticatedUserData } = await this.twitch.getUsers(); const params = { from_id: authenticatedUserData[0].id, }; // get the channels followed by the authenticated user const followedUsers = await this.paginate( this.twitch.getUserFollows.bind(this), params ); // get and emit new videos from each followed user let count = 0; for await (const followed of followedUsers) { const videos = await this.paginate( this.twitch.getVideos.bind(this), { user_id: followed.to_id, period: "day", // Period during which the video was created. Valid values: "all", "day", "week", "month". }, this.max ); for await (const video of videos) { this.$emit(video, this.getMeta(video)); count++; if (count >= this.max) return; } } }, }; <|start_filename|>components/twitch/actions/get-my-followers/get-my-followers.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, name: "Get My Followers", key: "twitch-get-my-followers", description: "Retrieves a list of users who follow the authenticated user", version: "0.0.1", type: "action", async run() { // get the userID of the authenticated user const userId = await this.getUserId(); const params = { to_id: userId, }; // get the users who follow the authenticated user const follows = await this.paginate( this.twitch.getUserFollows.bind(this), params, ); return await this.getPaginatedResults(follows); }, }; <|start_filename|>components/netlify/sources/new-deploy-success/new-deploy-success.js<|end_filename|> const common = require("../../common"); module.exports = { ...common, key: "netlify-new-deploy-success", name: "New Deploy Success (Instant)", description: "Emits an event when a new deployment is completed", version: "0.0.1", dedupe: "unique", methods: { ...common.methods, getHookEvent() { return "deploy_created"; }, getMetaSummary(data) { const { commit_ref } = data; return `Deploy succeeded for commit ${commit_ref}`; }, }, }; <|start_filename|>components/uservoice/sources/new-nps-ratings/new-nps-ratings.js<|end_filename|> const uservoice = require("../../uservoice.app.js"); const NUM_SAMPLE_RESULTS = 10; module.exports = { name: "New NPS Ratings", version: "0.0.2", key: "uservoice-new-nps-ratings", description: `Emits new NPS ratings submitted through the UserVoice NPS widget. On first run, emits up to ${NUM_SAMPLE_RESULTS} sample NPS ratings users have previously submitted.`, dedupe: "unique", props: { uservoice, timer: { label: "Polling schedule", description: "Pipedream will poll the UserVoice API for new NPS ratings on this schedule", type: "$.interface.timer", default: { intervalSeconds: 60 * 15, // by default, run every 15 minutes }, }, db: "$.service.db", }, hooks: { async deploy() { // Emit sample records on the first run const { npsRatings } = await this.uservoice.listNPSRatings({ numSampleResults: NUM_SAMPLE_RESULTS, }); this.emitWithMetadata(npsRatings); }, }, methods: { emitWithMetadata(ratings) { for (const rating of ratings) { const { id, rating: score, body, created_at } = rating; const summary = body && body.length ? `${score} - ${body}` : `${score}`; this.$emit(rating, { summary, id, ts: +new Date(created_at), }); } }, }, async run() { let updated_after = this.db.get("updated_after") || new Date().toISOString(); const { npsRatings, maxUpdatedAt } = await this.uservoice.listNPSRatings({ updated_after, }); this.emitWithMetadata(npsRatings); if (maxUpdatedAt) { updated_after = maxUpdatedAt; } this.db.set("updated_after", updated_after); }, }; <|start_filename|>components/activecampaign/sources/campaign-bounce/campaign-bounce.js<|end_filename|> const activecampaign = require("../../activecampaign.app.js"); const common = require("../common-campaign.js"); module.exports = { ...common, name: "New Campaign Bounce (Instant)", key: "activecampaign-campaign-bounce", description: "Emits an event when a contact email address bounces from a sent campaign.", version: "0.0.1", methods: { ...common.methods, getEvents() { return ["bounce"]; }, }, }; <|start_filename|>components/github/actions/search-issues-and-pull-requests/search-issues-and-pull-requests.js<|end_filename|> const github = require('../../github.app.js') const { Octokit } = require('@octokit/rest') module.exports = { key: "github-search-issues-and-pull-requests", name: "Search Issues and Pull Requests", description: "Find issues by state and keyword.", version: "0.0.15", type: "action", props: { github, q: { propDefinition: [github, "q_issues_and_pull_requests"] }, sort: { propDefinition: [github, "sortIssues"] }, order: { propDefinition: [github, "order"] }, paginate: { propDefinition: [github, "paginate"] }, }, async run() { const octokit = new Octokit({ auth: this.github.$auth.oauth_access_token }) if(this.paginate) { return await octokit.paginate(octokit.search.issuesAndPullRequests, { q: this.q, sort: this.sort, order: this.order, per_page: 100, }) } else { return (await octokit.search.issuesAndPullRequests({ q: this.q, sort: this.sort, order: this.order, per_page: 100, })).data.items } }, } <|start_filename|>components/intercom/sources/lead-added-email/lead-added-email.js<|end_filename|> const intercom = require("../../intercom.app.js"); module.exports = { key: "intercom-lead-added-email", name: "Lead Added Email", description: "Emits an event each time a lead adds their email address.", version: "0.0.1", dedupe: "unique", props: { intercom, db: "$.service.db", timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 15, }, }, }, async run(event) { const monthAgo = this.intercom.monthAgo(); let lastLeadUpdatedAt = this.db.get("lastLeadUpdatedAt") || Math.floor(monthAgo / 1000); const data = { query: { operator: "AND", value: [ { field: "updated_at", operator: ">", value: lastLeadUpdatedAt, }, { field: "role", operator: "=", value: "lead", }, { field: "email", operator: "!=", value: null, }, ], }, }; const results = await this.intercom.searchContacts(data); for (const lead of results) { if (lead.updated_at > lastLeadUpdatedAt) lastLeadUpdatedAt = lead.updated_at; this.$emit(lead, { id: lead.id, summary: lead.email, ts: lead.updated_at, }); } this.db.set("lastLeadUpdatedAt", lastLeadUpdatedAt); }, }; <|start_filename|>components/google_docs/google_docs.app.js<|end_filename|> const { google } = require("googleapis"); const googleDrive = require("../google_drive/google_drive.app"); module.exports = { type: "app", app: "google_docs", propDefinitions: { ...googleDrive.propDefinitions, docId: { type: "string", label: "Document", description: "Select a document or disable structured mode to pass a value exported from a previous step (e.g., `{{steps.foo.$return_value.documentId}}`) or to manually enter a static ID (e.g., `1KuEN7k8jVP3Qi0_svM5OO8oEuiLkq0csihobF67eat8`).", async options({ prevContext, driveId, }) { const { nextPageToken } = prevContext; return this.listDocsOptions(driveId, nextPageToken); }, }, }, methods: { ...googleDrive.methods, docs() { const auth = new google.auth.OAuth2(); auth.setCredentials({ access_token: this.$auth.oauth_access_token, }); return google.docs({ version: "v1", auth, }); }, async listDocsOptions(driveId, pageToken = null) { const q = "mimeType='application/vnd.google-apps.document'"; let request = { q, }; if (driveId) { request = { ...request, corpora: "drive", driveId, pageToken, includeItemsFromAllDrives: true, supportsAllDrives: true, }; } return this.listFilesOptions(pageToken, request); }, }, }; <|start_filename|>components/bandwidth/bandwidth.app.js<|end_filename|> const bandwidthMessaging = require("@bandwidth/messaging"); module.exports = { type: "app", app: "bandwidth", propDefinitions: { messageTo: { type: "string", label: "To", description: "The number the message will be sent to, in E164 format ex `+19195551234`", }, from: { type: "string", label: "From", description: "The number the call or message event will come from, in E164 format ex `+19195551234`", }, message: { type: "string", label: "Message", description: "The text message content", }, messagingApplicationId: { type: "string", label: "Messaging Application ID", description: "The ID from the messaging application created in the [Bandwidth Dashboard](https://dashboard.bandwidth.com).\n\nThe application must be associated with the location that the `from` number lives on.", }, mediaUrl: { type: "string[]", label: "Media URL", description: "Publicly addressible URL of the media you would like to send with the SMS", }, }, methods: { getMessagingClient() { return new bandwidthMessaging.Client({ basicAuthUserName: this.$auth.username, basicAuthPassword: this.$auth.password, }); }, async sendSms(to, from, message, messagingApplicationId) { const controller = new bandwidthMessaging.ApiController(this.getMessagingClient()); const data = { applicationId: messagingApplicationId, to: [ to, ], from: from, text: message, }; return await controller.createMessage(this.$auth.accountId, data); }, }, }; <|start_filename|>components/webflow/sources/common.js<|end_filename|> const { v4: uuidv4 } = require("uuid"); const webflow = require("../webflow.app"); module.exports = { props: { db: "$.service.db", http: "$.interface.http", webflow, siteId: { type: "string", label: "Site", description: "The site from which to listen events", async options(context) { const { page } = context; if (page !== 0) { return { options: [] }; } const sites = await this.webflow.listSites(); const options = sites.map(site => ({ label: site.name, value: site._id, })); return { options, }; }, }, }, methods: { getWebhookTriggerType() { throw new Error('getWebhookTriggerType is not implemented'); }, getWebhookFilter() { return {}; }, isEventRelevant(event) { return true; }, generateMeta(data) { return { id: uuidv4(), summary: "New event", ts: Date.now(), }; }, processEvent(event) { if (!this.isEventRelevant(event)) { return; } const { body } = event; const meta = this.generateMeta(body); this.$emit(body, meta); }, }, hooks: { async activate() { const { endpoint } = this.http; const triggerType = this.getWebhookTriggerType(); const filter = this.getWebhookFilter(); const webhook = await this.webflow.createWebhook( this.siteId, endpoint, triggerType, filter); const { _id: webhookId } = webhook; this.db.set("webhookId", webhookId); }, async deactivate() { const webhookId = this.db.get("webhookId"); await this.webflow.removeWebhook(this.siteId, webhookId); }, }, async run(event) { await this.processEvent(event); }, }; <|start_filename|>components/twitter_developer_app/twitter_developer_app.app.js<|end_filename|> const TwitterV1 = require("twit"); const TwitterV2 = require("twitter-v2"); module.exports = { type: "app", app: "twitter_developer_app", methods: { _newClientV1() { return new TwitterV1({ consumer_key: this.$auth.api_key, consumer_secret: this.$auth.api_secret_key, access_token: this.$auth.access_token, access_token_secret: this.$auth.access_token_secret, }); }, _newClientV2() { return new TwitterV2({ consumer_key: this.$auth.api_key, consumer_secret: this.$auth.api_secret_key, access_token_key: this.$auth.access_token, access_token_secret: this.$auth.access_token_secret, }); }, async getAccountId() { const client = this._newClientV1(); const path = "account/verify_credentials"; const params = { skip_status: true, }; const { data } = await client.get(path, params); return data.id_str; }, /** * This function retrieves the list of Twitter Direct Messages sent to the * authenticated account. The function will perform an exhaustive retrieval * of all the available messages unless a `lastMessageId` argument is * provided, in which case the function will retrieve messages up until the * specified ID (exclusive). * * The function calls this API internally: * https://developer.twitter.com/en/docs/twitter-api/v1/direct-messages/sending-and-receiving/api-reference/list-events * * @param {object} opts parameters for the retrieval of new direct messages * @param {string} [opts.lastMessageId] the ID of the direct message to use * as a lower bound for the retrieval * @returns a list of direct message objects */ async getNewDirectMessages({ lastMessageId }) { const client = this._newClientV1(); const path = "direct_messages/events/list"; const result = []; let cursor; do { const params = { cursor, }; const { data } = await client.get(path, params); const { events: messages = [], next_cursor: nextCursor, } = data; for (const message of messages) { if (message.id == lastMessageId) return result; result.push(message); } cursor = nextCursor; } while (cursor); return result; }, /** * This function retrieves the metrics for a list of Tweet ID's. By default, * it retrieves the public, non-public and organic metrics, but these can be * excluded by providing different values for the flag arguments. * * For more information about the specific metrics, see the API docs: * https://developer.twitter.com/en/docs/twitter-api/metrics * * @param {object} opts parameters for the retrieval of Tweets metrics * @param {string[]} opts.tweetIds the list of Tweet ID's for which to * retrieve the metrics * @param {boolean} [opts.excludePublic=false] if set, the public metrics * will not be retrieved * @param {boolean} [opts.excludeNonPublic=false] if set, the non-public * metrics will not be retrieved * @param {boolean} [opts.excludeOrganic=false] if set, the organic * metrics will not be retrieved * @returns a metrics object containing the metrics for the specified Tweet * ID's */ async getMetricsForIds({ tweetIds, excludePublic = false, excludeNonPublic = false, excludeOrganic = false, }) { if (!tweetIds) { throw new Error("The 'tweetIds' argument is mandatory"); } const client = this._newClientV2(); const path = "tweets"; const metrics = [ excludePublic ? undefined : "public_metrics", excludeNonPublic ? undefined : "non_public_metrics", excludeOrganic ? undefined : "organic_metrics", ].filter(i => i); const params = { "ids": tweetIds, "expansions": [ "attachments.media_keys", ], "media.fields": metrics, "tweet.fields": metrics, }; return client.get(path, params); }, }, }; <|start_filename|>components/twist/sources/common.js<|end_filename|> const twist = require("../twist.app.js"); module.exports = { dedupe: "unique", props: { twist, db: "$.service.db", http: { type: "$.interface.http", customResponse: true, }, workspace: { propDefinition: [twist, "workspace"], }, }, hooks: { async activate() { const data = this.getHookActivationData(); await this.twist.createHook(data); }, async deactivate() { await this.twist.deleteHook(this.http.endpoint); }, }, async run(event) { const { body } = event; if (!body) return; this.http.respond({ status: 200, }); const meta = this.getMeta(body); this.$emit(body, meta); }, }; <|start_filename|>components/pagerduty/package.json<|end_filename|> { "name": "@pipedream/pagerduty", "version": "0.3.3", "description": "Pipedream Pagerduty Components", "main": "pagerduty.app.js", "keywords": [ "pipedream", "pagerduty" ], "homepage": "https://pipedream.com/apps/pagerduty", "author": "Pipedream <<EMAIL>> (https://pipedream.com/)", "license": "MIT", "dependencies": { "axios": "^0.21.1" }, "gitHead": "e12480b94cc03bed4808ebc6b13e7fdb3a1ba535", "publishConfig": { "access": "public" } } <|start_filename|>components/shopify/sources/new-order/new-order.js<|end_filename|> const shopify = require("../../shopify.app.js"); module.exports = { key: "shopify-new-order", name: "New Order", description: "Emits an event for each new order submitted to a store.", version: "0.0.4", dedupe: "unique", props: { db: "$.service.db", timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 15, }, }, shopify, }, async run() { const sinceId = this.db.get("since_id") || null; let results = await this.shopify.getOrders("any", true, sinceId); for (const order of results) { this.$emit(order, { id: order.id, summary: `Order ${order.name}`, ts: Date.now(), }); } if (results[results.length - 1]) this.db.set("since_id", results[results.length - 1].id); }, }; <|start_filename|>components/activecampaign/sources/contact-added-to-list/contact-added-to-list.js<|end_filename|> const activecampaign = require("../../activecampaign.app.js"); const common = require("../common-webhook.js"); module.exports = { ...common, name: "New Contact Added to List", key: "activecampaign-contact-added-to-list", description: "Emits an event each time a new contact is added to a list.", version: "0.0.2", props: { ...common.props, lists: { propDefinition: [activecampaign, "lists"] }, }, hooks: { async activate() { const sources = this.sources.length > 0 ? this.sources : this.activecampaign.getAllSources(); const hookIds = []; const events = this.getEvents(); if (this.lists.length > 0) { try { for (const list of this.lists) { const { webhook } = await this.activecampaign.createHook( events, this.http.endpoint, sources, list ); hookIds.push(webhook.id); } } catch (err) { // if webhook creation fails, delete all hooks created so far for (const id of hookIds) { await this.activecampaign.deleteHook(id); } this.db.set("hookIds", []); throw new Error(err); } } // if no lists specified, create a webhook to watch all lists else { const { webhook } = await this.activecampaign.createHook( events, this.http.endpoint, sources ); hookIds.push(webhook.id); } this.db.set("hookIds", hookIds); }, async deactivate() { const hookIds = this.db.get("hookIds"); for (const id of hookIds) { await this.activecampaign.deleteHook(id); } }, }, methods: { ...common.methods, getEvents() { return ["subscribe"]; }, async getMeta(body) { const { list } = await this.activecampaign.getList(body.list); const { date_time: dateTimeIso } = body; const ts = Date.parse(dateTimeIso); return { id: `${body["contact[id]"]}${list.id}${ts}`, summary: `${body["contact[email]"]} added to ${list.name}`, ts, }; }, }, }; <|start_filename|>components/eventbrite/sources/new-event-ended/new-event-ended.js<|end_filename|> const common = require("../common/event.js"); module.exports = { ...common, key: "eventbrite-new-event-ended", name: "New Event Ended", description: "Emits an event when an event has ended", version: "0.0.1", dedupe: "unique", props: { ...common.props, timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 15, }, }, }, hooks: { ...common.hooks, async deploy() { const params = { orgId: this.organization, params: { status: "ended,completed", }, }; const eventStream = await this.resourceStream( this.eventbrite.listEvents.bind(this), "events", params ); for await (const event of eventStream) { this.emitEvent(event); } }, activate() {}, deactivate() {}, }, async run(event) { const params = { orgId: this.organization, params: { status: "ended,completed", }, }; const eventStream = await this.resourceStream( this.eventbrite.listEvents.bind(this), "events", params ); for await (const newEvent of eventStream) { this.emitEvent(newEvent); } }, }; <|start_filename|>components/todoist/sources/new-or-modified-task/new-or-modified-task.js<|end_filename|> const common = require("../common-task.js"); module.exports = { ...common, key: "todoist-new-or-modified-task", name: "New or Modified Task", description: "Emit an event for each new or modified task", version: "0.0.1", methods: { ...common.methods, isElementRelevant(element) { return true; }, }, }; <|start_filename|>components/twitch/sources/common-webhook.js<|end_filename|> const common = require("./common.js"); const { v4: uuidv4 } = require("uuid"); const subscriptionExpiration = 864000; // seconds until webhook subscription expires, maximum 10 days (864000 seconds) module.exports = { ...common, props: { ...common.props, http: { type: "$.interface.http", customResponse: true, }, timer: { type: "$.interface.timer", default: { // set timer to refresh subscription halfway until the expiration intervalSeconds: subscriptionExpiration / 2, }, }, }, hooks: { async activate() { const topics = await this.getTopics(); this.db.set("topics", topics); await this.manageHookForTopics("subscribe", topics); }, async deactivate() { const topics = this.db.get("topics"); await this.manageHookForTopics("unsubscribe", topics); }, }, methods: { ...common.methods, async manageHookForTopics(mode, topics) { const secretToken = uuidv4(); this.db.set("secretToken", secretToken); for (const topic of topics) try { await this.twitch.manageHook( mode, this.http.endpoint, topic, subscriptionExpiration, secretToken ); } catch (err) { console.log(err); } }, }, async run(event) { const { query, body, bodyRaw, headers, interval_seconds: intervalSeconds, } = event; // if event was invoked by timer, renew the subscription if (intervalSeconds) { await this.manageHookForTopics("subscribe", this.db.get("topics")); return; } // Respond with success response const response = { status: 200, }; // Twitch will send a request immediately after creating the hook. We must respond back // with the hub.challenge provided in the headers. if (query["hub.challenge"]) response.body = query["hub.challenge"]; this.http.respond(response); if (!body) return; // verify that the incoming webhook request is valid const secretToken = this.db.get("secretToken"); if (!this.twitch.verifyWebhookRequest(headers, bodyRaw, secretToken)) return; const { data } = body; if (data.length === 0) return; for (const item of data) { const meta = this.getMeta(item, headers); this.$emit(item, meta); } }, }; <|start_filename|>components/ringcentral/ringcentral.app.js<|end_filename|> const axios = require("axios"); module.exports = { type: "app", app: "ringcentral", propDefinitions: { extensionId: { type: "string", label: "Extension", description: "The extension (or user) that will trigger the event source", async options(context) { const { page } = context; const { records: extensions } = await this._getExtensionList({ // Pages in the RingCentral API are 1-indexed page: page + 1, perPage: 10, status: "Enabled", }); const options = extensions.map((extension) => { const { id: value, extensionNumber, contact: { firstName, lastName, }, } = extension; const label = `${firstName} ${lastName} (ext: ${extensionNumber})`; return { label, value, }; }); return { options, context: { nextPage: page + 1, }, }; }, }, deviceId: { type: "string", label: "Device", description: "The extension's device that will trigger the event source", default: "", async options(context) { const { page, extensionId, } = context; const { records: devices } = await this._getDeviceList(extensionId, { // Pages in the RingCentral API are 1-indexed page: page + 1, perPage: 10, }); const options = devices.map((extension) => { const { id: value, type, name, } = extension; const label = `${name} (type: ${type})`; return { label, value, }; }); return { options, context: { nextPage: page + 1, extensionId, }, }; }, }, }, methods: { _authToken() { return this.$auth.oauth_access_token; }, _apiUrl() { const { base_url: baseUrl = "https://platform.ringcentral.com/restapi/v1.0", } = this.$auth; return baseUrl; }, _accountUrl() { const baseUrl = this._apiUrl(); return `${baseUrl}/account/~`; }, _extensionUrl() { const baseUrl = this._accountUrl(); return `${baseUrl}/extension`; }, _deviceUrl(extensionId = "~") { const baseUrl = this._extensionUrl(); return `${baseUrl}/${extensionId}/device`; }, _callLogUrl(extensionId = "~") { const baseUrl = this._extensionUrl(); return `${baseUrl}/${extensionId}/call-log`; }, _subscriptionUrl(id) { const baseUrl = this._apiUrl(); const basePath = "/subscription"; const path = id ? `${basePath}/${id}` : basePath; return `${baseUrl}${path}`; }, _makeRequestConfig() { const authToken = this._authToken(); const headers = { "Authorization": `Bearer ${authToken}`, "User-Agent": "@PipedreamHQ/pipedream v0.1", }; return { headers, }; }, async _getExtensionList(params) { // `params` refers to the query params listed in the API docs: // https://developers.ringcentral.com/api-reference/Extensions/listExtensions const url = this._extensionUrl(); const requestConfig = { ...this._makeRequestConfig(), params, }; const { data } = await axios.get(url, requestConfig); return data; }, async _getDeviceList(extensionId, params) { // `params` refers to the query params listed in the API docs: // https://developers.ringcentral.com/api-reference/Devices/listExtensionDevices const url = this._deviceUrl(extensionId); const requestConfig = { ...this._makeRequestConfig(), params, }; const { data } = await axios.get(url, requestConfig); return data; }, async _getExtensionCallLog(extensionId, params, nextPage = {}) { // `params` refers to the query params listed in the API docs: // https://developers.ringcentral.com/api-reference/Call-Log/readUserCallLog const { uri: url = this._callLogUrl(extensionId), } = nextPage; const requestConfig = { ...this._makeRequestConfig(), params, }; const { data } = await axios.get(url, requestConfig); return data; }, async *getCallRecordings(extensionId, dateFrom, dateTo) { const params = { dateFrom, dateTo, withRecording: true, }; let nextPage = {}; do { const { records, navigation, } = await this._getExtensionCallLog(extensionId, params, nextPage); for (const record of records) { yield record; } nextPage = navigation.nextPage; } while (nextPage); }, async createHook({ address, eventFilters, verificationToken, }) { const url = this._subscriptionUrl(); const requestConfig = this._makeRequestConfig(); // Details about the different webhook parameters can be found in the // RingCentral API docs: // https://developers.ringcentral.com/api-reference/Subscriptions/createSubscription const requestData = { eventFilters, deliveryMode: { transportType: "WebHook", address, verificationToken, expiresIn: 630720000, // 20 years (max. allowed by the API) }, }; const { data } = await axios.post(url, requestData, requestConfig); return { ...data, verificationToken, }; }, deleteHook(hookId) { const url = this._subscriptionUrl(hookId); const requestConfig = this._makeRequestConfig(); return axios.delete(url, requestConfig); }, }, }; <|start_filename|>components/todoist/sources/new-project/new-project.js<|end_filename|> const common = require("../common-project.js"); module.exports = { ...common, key: "todoist-new-project", name: "New Project", description: "Emit an event for each new project", version: "0.0.1", dedupe: "greatest", }; <|start_filename|>components/twist/sources/new-comment/new-comment.js<|end_filename|> const twist = require("../../twist.app.js"); const common = require("../common.js"); module.exports = { ...common, name: "New Comment (Instant)", version: "0.0.1", key: "twist-new-comment", description: "Emits an event for any new comment in a workspace", props: { ...common.props, channel: { propDefinition: [twist, "channel", (c) => ({ workspace: c.workspace })], }, thread: { propDefinition: [twist, "thread", (c) => ({ channel: c.channel })], }, }, methods: { getHookActivationData() { return { target_url: this.http.endpoint, event: "comment_added", workspace_id: this.workspace, channel_id: this.channel, thread_id: this.thread, }; }, getMeta(body) { const { id, content, posted } = body; return { id, summary: content, ts: Date.parse(posted), }; }, }, }; <|start_filename|>components/bitbucket/bitbucket.app.js<|end_filename|> const axios = require("axios"); module.exports = { type: "app", app: "bitbucket", propDefinitions: { workspaceId: { type: "string", label: "Workspace", description: "The workspace that contains the repositories to work with", async options(context) { const url = this._userWorkspacesEndpoint(); const params = { sort: "name", fields: [ "next", "values.name", "values.slug", ], }; const data = await this._propDefinitionsOptions(url, params, context); const options = data.values.map(workspace => ({ label: workspace.name, value: workspace.slug, })); return { options, context: { // https://developer.atlassian.com/bitbucket/api/2/reference/meta/pagination nextPageUrl: data.next, }, }; }, }, repositoryId: { type: "string", label: "Repository", description: "The repository for which the events will be processed", async options(context) { const { workspaceId } = context; const url = this._workspaceRepositoriesEndpoint(workspaceId); const params = { sort: "slug", fields: [ "next", "values.slug", ], }; const data = await this._propDefinitionsOptions(url, params, context); const options = data.values.map(repository => ({ label: repository.slug, value: repository.slug, })); return { options, context: { // https://developer.atlassian.com/bitbucket/api/2/reference/meta/pagination nextPageUrl: data.next, }, }; }, }, branchName: { type: "string", label: "Branch Name", description: "The name of the branch", async options(context) { const { workspaceId, repositoryId } = context; const url = this._repositoryBranchesEndpoint(workspaceId, repositoryId); const params = { sort: "name", fields: [ "next", "values.name", ], }; const data = await this._propDefinitionsOptions(url, params, context); const options = data.values.map(branch => ({ label: branch.name, value: branch.name, })); return { options, context: { // https://developer.atlassian.com/bitbucket/api/2/reference/meta/pagination nextPageUrl: data.next, }, }; }, }, eventTypes: { type: "string[]", label: "Event Types", description: "The type of events to watch", async options(context) { const { subjectType } = context; const url = this._eventTypesEndpoint(subjectType); const params = { fields: [ "next", "values.category", "values.event", "values.label", ], }; const data = await this._propDefinitionsOptions(url, params, context); const options = data.values.map(this._formatEventTypeOption); return { options, context: { // https://developer.atlassian.com/bitbucket/api/2/reference/meta/pagination nextPageUrl: data.next, }, }; }, }, }, methods: { _apiUrl() { return "https://api.bitbucket.org/2.0"; }, _userWorkspacesEndpoint() { const baseUrl = this._apiUrl(); return `${baseUrl}/workspaces`; }, _workspaceRepositoriesEndpoint(workspaceId) { const baseUrl = this._apiUrl(); return `${baseUrl}/repositories/${workspaceId}`; }, _eventTypesEndpoint(subjectType) { const baseUrl = this._apiUrl(); return `${baseUrl}/hook_events/${subjectType}`; }, _repositoryBranchesEndpoint(workspaceId, repositoryId) { const baseUrl = this._apiUrl(); return `${baseUrl}/repositories/${workspaceId}/${repositoryId}/refs`; }, _branchCommitsEndpoint(workspaceId, repositoryId, branchName) { const baseUrl = this._apiUrl(); return `${baseUrl}/repositories/${workspaceId}/${repositoryId}/commits/${branchName}`; }, _hooksEndpointUrl(hookPathProps) { const { workspaceId, repositoryId } = hookPathProps; return repositoryId ? this._repositoryHooksEndpointUrl(workspaceId, repositoryId) : this._workspaceHooksEndpointUrl(workspaceId); }, _hookEndpointUrl(hookPathProps, hookId) { const { workspaceId, repositoryId } = hookPathProps; return repositoryId ? this._repositoryHookEndpointUrl(workspaceId, repositoryId, hookId) : this._workspaceHookEndpointUrl(workspaceId, hookId); }, _workspaceHooksEndpointUrl(workspaceId) { const baseUrl = this._userWorkspacesEndpoint(); return `${baseUrl}/${workspaceId}/hooks`; }, _workspaceHookEndpointUrl(workspaceId, hookId) { const baseUrl = this._workspaceHooksEndpointUrl(workspaceId); // https://developer.atlassian.com/bitbucket/api/2/reference/meta/uri-uuid#uuid return `${baseUrl}/{${hookId}}`; }, _repositoryHooksEndpointUrl(workspaceId, repositoryId) { const baseUrl = this._workspaceRepositoriesEndpoint(workspaceId); return `${baseUrl}/${repositoryId}/hooks`; }, _repositoryHookEndpointUrl(workspaceId, repositoryId, hookId) { const baseUrl = this._repositoryHooksEndpointUrl(workspaceId, repositoryId); // https://developer.atlassian.com/bitbucket/api/2/reference/meta/uri-uuid#uuid return `${baseUrl}/{${hookId}}`; }, _formatEventTypeOption(eventType) { const { category, label, event } = eventType; const optionLabel = `${category} ${label}`; return { label: optionLabel, value: event, }; }, async _propDefinitionsOptions(url, params, { page, prevContext }) { let requestConfig = this._makeRequestConfig(); // Basic axios request config if (page === 0) { // First time the options are being retrieved. // // In such case, we include the query parameters provided // as arguments to this function. // // For subsequent pages, the "next page" URL's (provided by // the BitBucket API) will already include these parameters, // so we don't need to explicitly provide them again. requestConfig = { ...requestConfig, params, }; } else if (prevContext.nextPageUrl) { // Retrieve next page of options. url = prevContext.nextPageUrl; } else { // No more options available. return { values: [] }; } const { data } = await axios.get(url, requestConfig); return data; }, async *getCommits(opts) { const { workspaceId, repositoryId, branchName, lastProcessedCommitHash, } = opts; const requestConfig = this._makeRequestConfig(); let url = this._branchCommitsEndpoint(workspaceId, repositoryId, branchName); do { const { data } = await axios.get(url, requestConfig); const { values, next } = data; // Yield the retrieved commits in a serial manner, until // we exhaust the response from the BitBucket API, or we reach // the last processed commit, whichever comes first. for (const commit of values) { if (commit.hash === lastProcessedCommitHash) return; yield commit; } url = next; } while (url); }, _authToken() { return this.$auth.oauth_access_token; }, _makeRequestConfig() { const authToken = this._authToken(); const headers = { "Authorization": `Bearer ${authToken}`, "User-Agent": "@PipedreamHQ/pipedream v0.1", }; return { headers, }; }, async createHook(opts) { const { hookParams, hookPathProps } = opts; const url = this._hooksEndpointUrl(hookPathProps); const requestConfig = this._makeRequestConfig(); const response = await axios.post(url, hookParams, requestConfig); const hookId = response.data.uuid.match(/^{(.*)}$/)[1]; return { hookId, }; }, async deleteHook(opts) { const { hookId, hookPathProps } = opts; const url = this._hookEndpointUrl(hookPathProps, hookId); const requestConfig = this._makeRequestConfig(); return axios.delete(url, requestConfig); }, }, }; <|start_filename|>components/yahoo_fantasy_sports/sources/new-football-league-transactions/new-football-league-transactions.js<|end_filename|> const yfs = require('../../yahoo_fantasy_sports.app.js') function displayPlayer(p) { return `${p.name.full}, ${p.editorial_team_abbr} - ${p.display_position}` } module.exports = { key: "yahoo_fantasy_sports-new-football-league-transactions", name: "New Football League Transactions", version: "0.0.1", props: { yfs, league: { type: "string", async options() { return await this.yfs.getLeagueOptions() }, }, eventTypes: { type: "string[]", options: ["*", "add", "drop", "commish", "trade"], // not type with team_key optional: true, default: ["*"], }, timer: "$.interface.timer", }, dedupe: "unique", async run() { let eventTypes = [] if (this.eventTypes.includes("*")) { eventTypes.push("add", "drop", "commish", "trade") } else { eventTypes = this.eventTypes } const transactions = await this.yfs.getLeagueTransactions(this.league, eventTypes) // XXX figure out count... field any integer greater than 0 but nothing about default limit or pagination? for (const txn of transactions) { txn._summary = this.yfs.transactionSummary(txn) this.$emit(txn, { id: txn.transaction_key, ts: (+txn.timestamp)*1000, summary: txn._summary, }) } }, } <|start_filename|>components/gitlab/sources/new-branch/new-branch.js<|end_filename|> const gitlab = require("../../gitlab.app.js"); module.exports = { key: "gitlab-new-branch", name: "New Branch (Instant)", description: "Emits an event when a new branch is created", version: "0.0.1", dedupe: "unique", props: { gitlab, projectId: { propDefinition: [gitlab, "projectId"] }, http: { type: "$.interface.http", customResponse: true, }, db: "$.service.db", }, hooks: { async activate() { const hookParams = { push_events: true, url: this.http.endpoint, }; const opts = { hookParams, projectId: this.projectId, }; const { hookId, token } = await this.gitlab.createHook(opts); console.log( `Created "push events" webhook for project ID ${this.projectId}. (Hook ID: ${hookId}, endpoint: ${hookParams.url})` ); this.db.set("hookId", hookId); this.db.set("token", token); }, async deactivate() { const hookId = this.db.get("hookId"); const opts = { hookId, projectId: this.projectId, }; await this.gitlab.deleteHook(opts); console.log( `Deleted webhook for project ID ${this.projectId}. (Hook ID: ${hookId})` ); }, }, methods: { isNewBranch(body) { // Logic based on https://gitlab.com/gitlab-org/gitlab-foss/-/issues/31723. const { before } = body; const expectedBeforeValue = "0000000000000000000000000000000000000000"; return before === expectedBeforeValue; }, generateMeta(data) { const newBranchName = data.ref; const summary = `New Branch: ${newBranchName}`; const ts = +new Date(); return { id: newBranchName, summary, ts, }; }, }, async run(event) { const { headers, body } = event; // Reject any calls not made by the proper Gitlab webhook. if (!this.gitlab.isValidSource(headers, this.db)) { this.http.respond({ status: 404, }); return; } // Acknowledge the event back to Gitlab. this.http.respond({ status: 200, }); // Gitlab doesn't offer a specific hook for "new branch" events, // but such event can be deduced from the payload of "push" events. if (this.isNewBranch(body)) { const meta = this.generateMeta(body); this.$emit(body, meta); } }, }; <|start_filename|>components/pipefy/sources/card-created/card-created.js<|end_filename|> const common = require("../common-webhook.js"); module.exports = { ...common, name: "Card Created (Instant)", key: "pipefy-card-created", description: "Emits an event for each new card created in a Pipe.", version: "0.0.2", methods: { ...common.methods, getActions() { return ["card.create"]; }, getMeta(card, cardData) { return { body: { card, cardData }, id: card.id, summary: card.title, }; }, }, }; <|start_filename|>components/formstack/formstack.app.js<|end_filename|> const axios = require("axios"); module.exports = { type: "app", app: "formstack", propDefinitions: { formId: { type: "string", label: "Forms", optional: true, async options({ page, prevContext }) { const options = []; const per_page = 100; let results = []; page = prevContext.page || 1; let total = prevContext.total >= 0 ? prevContext.total : per_page; if (total === per_page) { results = await this.getForms(page, per_page); for (const form of results) { options.push({ label: form.name, value: form.id }); } } total = results.length; page++; return { options, context: { page, total }, }; }, }, }, methods: { monthAgo() { const monthAgo = new Date(); monthAgo.setMonth(monthAgo.getMonth() - 1); return monthAgo; }, _getBaseURL() { return "https://www.formstack.com/api/v2"; }, _getAuthHeaders() { return { Authorization: `Bearer ${this.$auth.oauth_access_token}`, "Content-Type": "application/json", }; }, async createHook({ id, url }) { const config = { method: "POST", url: `${this._getBaseURL()}/form/${id}/webhook.json`, headers: this._getAuthHeaders(), params: { url, content_type: "json", handshake_key: this.$auth.oauth_refresh_token, }, }; return (await axios(config)).data; }, async deleteHook({ hookId }) { const config = { method: "DELETE", url: `${this._getBaseURL()}/webhook/${hookId}.json`, headers: this._getAuthHeaders(), }; return await axios(config); }, async getForms(page, per_page) { const config = { method: "GET", url: `${this._getBaseURL()}/form.json`, headers: this._getAuthHeaders(), params: { page, per_page, folders: false, }, }; return (await axios(config)).data.forms; }, }, }; <|start_filename|>components/slack/actions/send-custom-message/send-custom-message.js<|end_filename|> const slack = require("../../slack.app.js"); module.exports = { key: "slack-send-custom-message", name: "Send a Custom Message", description: "Customize advanced setttings and send a message to a channel, group or user", version: "0.1.0", type: "action", props: { slack, conversation: { propDefinition: [ slack, "conversation", ], }, text: { propDefinition: [ slack, "text", ], }, attachments: { propDefinition: [ slack, "attachments", ], }, unfurl_links: { propDefinition: [ slack, "unfurl_links", ], }, unfurl_media: { propDefinition: [ slack, "unfurl_media", ], }, parse: { propDefinition: [ slack, "parse", ], }, as_user: { propDefinition: [ slack, "as_user", ], }, username: { propDefinition: [ slack, "username", ], }, icon_emoji: { propDefinition: [ slack, "icon_emoji", ], }, icon_url: { propDefinition: [ slack, "icon_url", ], }, mrkdwn: { propDefinition: [ slack, "mrkdwn", ], }, blocks: { propDefinition: [ slack, "blocks", ], }, link_names: { propDefinition: [ slack, "link_names", ], }, reply_broadcast: { propDefinition: [ slack, "reply_broadcast", ], }, thread_ts: { propDefinition: [ slack, "thread_ts", ], }, }, async run() { return await this.slack.sdk().chat.postMessage({ text: this.text, channel: this.conversation, attachments: this.attachments, unfurl_links: this.unfurl_links, unfurl_media: this.unfurl_media, parse: this.parse, as_user: this.as_user, username: this.username, icon_emoji: this.icon_emoji, icon_url: this.icon_url, mrkdwn: this.mrkdwn, blocks: this.blocks, link_names: this.link_names, reply_broadcast: this.reply_broadcast, thread_ts: this.thread_ts, }); }, }; <|start_filename|>components/twitter/sources/my-tweets/my-tweets.js<|end_filename|> const base = require("../common/tweets"); module.exports = { ...base, key: "twitter-my-tweets", name: "My Tweets", description: "Emit new Tweets you post to Twitter", version: "0.0.5", props: { ...base.props, q: { propDefinition: [ base.props.twitter, "keyword_filter", ], }, result_type: { propDefinition: [ base.props.twitter, "result_type", ], }, includeRetweets: { propDefinition: [ base.props.twitter, "includeRetweets", ], }, includeReplies: { propDefinition: [ base.props.twitter, "includeReplies", ], }, lang: { propDefinition: [ base.props.twitter, "lang", ], }, locale: { propDefinition: [ base.props.twitter, "locale", ], }, geocode: { propDefinition: [ base.props.twitter, "geocode", ], }, enrichTweets: { propDefinition: [ base.props.twitter, "enrichTweets", ], }, }, methods: { ...base.methods, async getSearchQuery() { const account = await this.twitter.verifyCredentials(); const from = `from:${account.screen_name}`; return this.q ? `${from} ${this.q}` : from; }, async retrieveTweets() { const { lang, locale, geocode, result_type, enrichTweets, includeReplies, includeRetweets, maxRequests, count, } = this; const since_id = this.getSinceId(); const limitFirstPage = !since_id; const q = await this.getSearchQuery(); // run paginated search return this.twitter.paginatedSearch({ q, since_id, lang, locale, geocode, result_type, enrichTweets, includeReplies, includeRetweets, maxRequests, count, limitFirstPage, }); }, }, }; <|start_filename|>components/gitlab/sources/new-review-request/new-review-request.js<|end_filename|> const gitlab = require("../../gitlab.app.js"); module.exports = { key: "gitlab-new-review-request", name: "New Review Request (Instant)", description: "Emits an event when a reviewer is added to a merge request", version: "0.0.1", dedupe: "unique", props: { gitlab, projectId: { propDefinition: [gitlab, "projectId"] }, http: { type: "$.interface.http", customResponse: true, }, db: "$.service.db", }, hooks: { async activate() { const hookParams = { merge_requests_events: true, push_events: false, url: this.http.endpoint, }; const opts = { hookParams, projectId: this.projectId, }; const { hookId, token } = await this.gitlab.createHook(opts); console.log( `Created "merge request events" webhook for project ID ${this.projectId}. (Hook ID: ${hookId}, endpoint: ${hookParams.url})` ); this.db.set("hookId", hookId); this.db.set("token", token); }, async deactivate() { const hookId = this.db.get("hookId"); const opts = { hookId, projectId: this.projectId, }; await this.gitlab.deleteHook(opts); console.log( `Deleted webhook for project ID ${this.projectId}. (Hook ID: ${hookId})` ); }, }, methods: { getNewReviewers(body) { const { action, title } = body.object_attributes; // When a merge request is first created, any assignees // in it are interpreted as new review requests. if (action === "open" || action === "reopen") { const { assignees = [] } = body; return assignees; } // Gitlab API provides any merge request update diff // as part of their response. We can check the presence of // the `assignees` attribute within those changes to verify // if there are new review requests. const { assignees } = body.changes; if (!assignees) { console.log(`No new assignees in merge request "${title}"`); return []; } // If the assignees of the merge request changed, we need to compute // the difference in order to extract the new reviewers. const previousAssigneesUsernames = new Set(assignees.previous.map(a => a.username)); const newAssignees = assignees.current.filter(a => !previousAssigneesUsernames.has(a.username)); if (newAssignees.length > 0) { console.log( `Assignees added to merge request "${title}": ${newAssignees.map(a => a.username).join(', ')}` ); } return newAssignees; }, generateMeta(data, reviewer) { const { id, title, updated_at } = data.object_attributes; const summary = `New reviewer for "${title}": ${reviewer.username}`; const ts = +new Date(updated_at); const compositeId = `${id}-${ts}-${reviewer.username}`; return { id: compositeId, summary, ts, }; }, }, async run(event) { const { headers, body } = event; // Reject any calls not made by the proper Gitlab webhook. if (!this.gitlab.isValidSource(headers, this.db)) { this.http.respond({ status: 404, }); return; } // Acknowledge the event back to Gitlab. this.http.respond({ status: 200, }); // Gitlab doesn't offer a specific hook for "new merge request reviewers" events, // but such event can be deduced from the payload of "merge request" events. this.getNewReviewers(body).forEach(reviewer => { const meta = this.generateMeta(body, reviewer); const event = { ...body, reviewer, }; this.$emit(event, meta); }); }, }; <|start_filename|>components/clickup/actions/create-subtask/create-subtask.js<|end_filename|> const clickup = require("../../clickup.app.js"); const { props, run, } = require("../create-task/create-task.js"); module.exports = { key: "clickup-create-subtask", name: "Create Subtask", description: "Creates a new subtask", version: "0.0.2", type: "action", props: { ...props, parent: { propDefinition: [ clickup, "parent", (c) => ({ list: c.list, }), ], }, }, run, }; <|start_filename|>components/hubspot/sources/new-blog-article/new-blog-article.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, key: "hubspot-new-blog-article", name: "New Blog Posts", description: "Emits an event for each new blog post.", version: "0.0.2", dedupe: "unique", hooks: {}, methods: { ...common.methods, generateMeta(blogpost) { const { id, name: summary, created } = blogpost; const ts = Date.parse(blogpost.created); return { id, summary, ts, }; }, }, async run(event) { const createdAfter = this._getAfter(); const params = { limit: 100, createdAfter, // return entries created since event last ran }; await this.paginate( params, this.hubspot.getBlogPosts.bind(this), "results" ); this._setAfter(Date.now()); }, }; <|start_filename|>components/microsoft_onedrive/sources/new-file-in-folder/new-file-in-folder.js<|end_filename|> const base = require("../new-file/new-file"); module.exports = { ...base, key: "microsoft_onedrive-new-file-in-folder", name: "New File in Folder (Instant)", description: "Emit an event when a new file is added to a specific folder in a OneDrive drive", version: "0.0.1", dedupe: "unique", props: { ...base.props, folder: { type: "string", label: "Folder", description: "The OneDrive folder to watch for new files", async options(context) { const { page } = context; if (page !== 0) { return []; } const foldersStream = this.microsoft_onedrive.listFolders(); const result = []; for await (const folder of foldersStream) { const { name: label, id: value, } = folder; result.push({ label, value, }); } return result; }, }, }, methods: { ...base.methods, getDeltaLinkParams() { return { folderId: this.folder, }; }, }, }; <|start_filename|>components/activecampaign/sources/new-contact-task/new-contact-task.js<|end_filename|> const activecampaign = require("../../activecampaign.app.js"); const common = require("../common-webhook.js"); module.exports = { ...common, name: "New Contact Task", key: "activecampaign-new-contact-task", description: "Emits an event each time a new contact task is created.", version: "0.0.1", props: { ...common.props, contacts: { propDefinition: [activecampaign, "contacts"] }, }, methods: { getEvents() { return ["contact_task_add"]; }, isRelevant(body) { return ( this.contacts.length === 0 || this.contacts.includes(body["contact[id]"]) ); }, getMeta(body) { const { date_time: dateTimeIso } = body; const ts = Date.parse(dateTimeIso); return { id: body["task[id]"], summary: `${body["task[title]"]}`, ts }; }, }, }; <|start_filename|>components/webflow/sources/new-collection-item/new-collection-item.js<|end_filename|> const common = require("../collection-common"); module.exports = { ...common, key: "webflow-new-collection-item", name: "New Collection Item (Instant)", description: "Emit an event when a collection item is created", version: "0.0.1", methods: { ...common.methods, getWebhookTriggerType() { return "collection_item_created"; }, generateMeta(data) { const { _id: id, "created-on": createdOn, slug, } = data; const summary = `Collection item created: ${slug}`; const ts = Date.parse(createdOn); return { id, summary, ts, }; }, }, }; <|start_filename|>components/firebase_admin_sdk/firebase_admin_sdk.app.js<|end_filename|> const admin = require("firebase-admin"); const axios = require("axios"); module.exports = { type: "app", app: "firebase_admin_sdk", propDefinitions: { path: { type: "string", label: "Path", description: "A [relative path](https://firebase.google.com/docs/reference/rules/rules.Path) to the location of child data", }, query: { type: "string", label: "Structured Query", description: "Enter a [structured query](https://cloud.google.com/firestore/docs/reference/rest/v1beta1/StructuredQuery) that returns new records from your target collection. Example: `{ \"select\": { \"fields\": [] }, \"from\": [ { \"collectionId\": \"<YOUR COLLECTION>\", \"allDescendants\": \"true\" } ] }`", }, apiKey: { type: "string", label: "Web API Key", description: "You can find the Web API key in the **Project Settings** of your Firebase admin console", secret: true, }, }, methods: { /** * Creates and initializes a Firebase app instance. */ async initializeApp() { const { projectId, clientEmail, privateKey, } = this.$auth; const formattedPrivateKey = privateKey.replace(/\\n/g, "\n"); return await admin.initializeApp({ credential: admin.credential.cert({ projectId, clientEmail, privateKey: formattedPrivateKey, }), databaseURL: `https://${projectId}-default-rtdb.firebaseio.com/`, }); }, /** * Renders this app instance unusable and frees the resources of all associated services. */ async deleteApp() { return await this.getApp().delete(); }, /** * Retrieves the default Firebase app instance. */ getApp() { return admin.app(); }, _getHeaders(token) { const defaultHeader = { "Content-Type": "applicaton/json", }; const headers = token ? { ...defaultHeader, Authorization: `Bearer ${token}`, } : defaultHeader; return headers; }, async _makeRequest(method, url, data, params = {}, token = null) { const config = { method, url, headers: this._getHeaders(token), data, params, }; return (await axios(config)).data; }, /** * Retrieves a Bearer token for use with the Firebase REST API. * @param {string} apiKey - the Web API Key, which is obtained from the project * settings page in the admin console * @returns {object} returns an object containing a new token and refresh token */ async _getToken(apiKey) { const { clientEmail } = this.$auth; const newCustomToken = await admin .auth() .createCustomToken(clientEmail) .catch((error) => { console.log("Error creating custom token:", error); }); const data = { token: newCustomToken, returnSecureToken: true, }; const params = { key: apiKey, }; return await this._makeRequest( "POST", "https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken", data, params, ); }, /** * @param {string} structuredQuery - A structured query in the format specified in * this documentation: * https://cloud.google.com/firestore/docs/reference/rest/v1/StructuredQuery * @param {string} apiKey - the Web API Key, which is obtained from the project settings * page in the admin console * @returns {array} an array of the documents returned from the structured query */ async runQuery(structuredQuery, apiKey) { const { idToken } = await this._getToken(apiKey); const { projectId } = this.$auth; const parent = `projects/${projectId}/databases/(default)/documents`; const data = { structuredQuery, }; return await this._makeRequest( "POST", `https://firestore.googleapis.com/v1/${parent}:runQuery`, data, null, idToken, ); }, }, }; <|start_filename|>components/netlify/sources/new-form-submission/new-form-submission.js<|end_filename|> const common = require("../../common"); module.exports = { ...common, key: "netlify-new-form-submission", name: "New Form Submission (Instant)", description: "Emits an event when a user submits a form", version: "0.0.1", dedupe: "unique", methods: { ...common.methods, getHookEvent() { return "submission_created"; }, getMetaSummary(data) { const { form_name } = data; return `New form submission for ${form_name}`; }, }, }; <|start_filename|>components/eventbrite/actions/locales.js<|end_filename|> module.exports = [ { label: "German (Austria)", value: "de_AT", }, { label: "German (Switzerland)", value: "de_CH", }, { label: "German (Germany)", value: "de_DE", }, { label: "English (Australia)", value: "en_AU", }, { label: "English (Canada)", value: "en_CA", }, { label: "English (Denmark)", value: "en_DK", }, { label: "English (Finland)", value: "en_FI", }, { label: "English (United Kingdom)", value: "en_GB", }, { label: "English (Hong Kong)", value: "en_KH", }, { label: "English (Ireland)", value: "en_IE", }, { label: "English (India)", value: "en_IN", }, { label: "English (New Zealand)", value: "en_NZ", }, { label: "English (Sweden)", value: "en_SE", }, { label: "English (U.S.A.)", value: "en_US", }, { label: "Spanish (Argentina)", value: "es_AR", }, { label: "Spanish (Chile)", value: "es_CL", }, { label: "Spanish (Colombia)", value: "es_CO", }, { label: "Spanish (Spain)", value: "es_ES", }, { label: "French (Belgium)", value: "fr_BE", }, { label: "French (Canada)", value: "fr_CA", }, { label: "German (Switzerland)", value: "fr_CH", }, { label: "French (France)", value: "fr_FR", }, { label: "Hindi (India)", value: "hi_IN", }, { label: "Italian (Italy)", value: "it_IT", }, { label: "Dutch (Belgium)", value: "nl_BE", }, { label: "Dutch (Netherlands)", value: "nl_NL", }, { label: "Portuguese (Brazil)", value: "pt_BR", }, { label: "Portuguese (Portugal)", value: "pt_PT", }, ]; <|start_filename|>components/netlify/sources/new-deploy-start/new-deploy-start.js<|end_filename|> const common = require("../../common"); module.exports = { ...common, key: "netlify-new-deploy-start", name: "New Deploy Start (Instant)", description: "Emits an event when a new deployment is started", version: "0.0.1", dedupe: "unique", methods: { ...common.methods, getHookEvent() { return "deploy_building"; }, getMetaSummary(data) { const { commit_ref } = data; return `Deploy started for commit ${commit_ref}`; }, }, }; <|start_filename|>components/todoist/sources/new-or-modified-project/new-or-modified-project.js<|end_filename|> const common = require("../common-project.js"); module.exports = { ...common, key: "todoist-new-or-modified-project", name: "New or Modified Project", description: "Emit an event for each new or modified project", version: "0.0.1", }; <|start_filename|>components/twitch/sources/common.js<|end_filename|> const twitch = require("../twitch.app.js"); const { promisify } = require("util"); const pause = promisify((delay, fn) => setTimeout(fn, delay)); module.exports = { dedupe: "unique", props: { twitch, db: "$.service.db", }, methods: { async *paginate(resourceFn, params, max = null) { const items = []; let done = false; let count = 0; do { const { data, pagination } = await this.retryFn(resourceFn, params); for (const item of data) { yield item; count++; if (max && count >= max) { return; } } // pass cursor to get next page of results; if no cursor, no more pages const { cursor } = pagination; params.after = cursor; done = !cursor; } while (!done); }, async retryFn(resourceFn, params, retries = 3) { let response; try { response = await resourceFn(params); return response.data; } catch (err) { if (retries <= 1) { throw new Error(err); } delay = response ? response.headers["ratelimit-limit"] : 500; await pause(delay); return await this.retryFn(resourceFn, params, retries - 1); } }, }, }; <|start_filename|>components/clickup/actions/create-list/create-list.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, key: "clickup-create-list", name: "Create List", description: "Creates a new list", version: "0.0.4", type: "action", props: { ...common.props, name: { propDefinition: [ common.props.clickup, "name", ], description: "New list name", }, content: { type: "string", label: "Content", description: "New list content", optional: true, }, dueDate: { propDefinition: [ common.props.clickup, "dueDate", ], description: `The date by which you must complete the tasks in this list. Use [UTC time](https://www.epochconverter.com/) in milliseconds (e.g. \`1508369194377\`)`, }, dueDateTime: { propDefinition: [ common.props.clickup, "dueDateTime", ], description: "Set to `true` if you want to enable the due date time for the tasks in this list", }, assignee: { propDefinition: [ common.props.clickup, "assignees", (c) => ({ workspace: c.workspace, }), ], type: "string", label: "Assignee", description: "Assignee to be added to this list", optional: true, }, status: { type: "string", label: "Status", description: "The status refers to the List color rather than the task Statuses available in the List", optional: true, }, }, async run() { const data = { name: this.name, content: this.content, due_date: this.dueDate, due_date_time: this.dueDateTime, priority: this.priority, assignee: this.assignee, status: this.status, }; return this.folder ? await this.clickup.createList(this.folder, data) : await this.clickup.createFolderlessList(this.space, data); }, }; <|start_filename|>components/activecampaign/sources/updated-contact/updated-contact.js<|end_filename|> const activecampaign = require("../../activecampaign.app.js"); const common = require("../common-webhook.js"); module.exports = { ...common, name: "Updated Contact (Instant)", key: "activecampaign-updated-contact", description: "Emits an event each time a contact is updated.", version: "0.0.1", methods: { ...common.methods, getEvents() { return ["update"]; }, getMeta(body) { const { date_time: dateTimeIso } = body; const ts = Date.parse(dateTimeIso); return { id: `${body["contact[id]"]}${new Date(body.date_time).getTime()}`, summary: body["contact[email]"], ts }; }, }, }; <|start_filename|>components/intercom/sources/new-admin-reply/new-admin-reply.js<|end_filename|> const intercom = require("../../intercom.app.js"); const get = require("lodash.get"); module.exports = { key: "intercom-new-admin-reply", name: "New Reply From Admin", description: "Emits an event each time an admin replies to a conversation.", version: "0.0.1", dedupe: "unique", props: { intercom, db: "$.service.db", timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 15, }, }, }, async run(event) { const monthAgo = this.intercom.monthAgo(); let lastAdminReplyAt = this.db.get("lastAdminReplyAt") || Math.floor(monthAgo / 1000); lastAdminReplyAt = Math.floor(monthAgo / 1000); const data = { query: { field: "statistics.last_admin_reply_at", operator: ">", value: lastAdminReplyAt, }, }; const results = await this.intercom.searchConversations(data); for (const conversation of results) { if (conversation.statistics.last_admin_reply_at > lastAdminReplyAt) lastAdminReplyAt = conversation.statistics.last_admin_reply_at; const conversationData = ( await this.intercom.getConversation(conversation.id) ).data; const total_count = conversationData.conversation_parts.total_count; const conversationBody = get( conversationData, `conversation_parts.conversation_parts[${total_count - 1}].body` ); if (total_count > 0 && conversationBody) { // emit id & summary from last part/reply added this.$emit(conversationData, { id: conversationData.conversation_parts.conversation_parts[ total_count - 1 ].id, summary: conversationBody, ts: conversation.statistics.last_admin_reply_at, }); } } this.db.set("lastAdminReplyAt", lastAdminReplyAt); }, }; <|start_filename|>components/twitter/sources/watch-retweets-of-my-tweet/watch-retweets-of-my-tweet.js<|end_filename|> const base = require("../common/tweets"); module.exports = { ...base, key: "twitter-watch-retweets-of-my-tweet", name: "Watch Retweets of My Tweet", description: "Emit an event when a specific Tweet from the authenticated user is retweeted", version: "0.0.1", props: { ...base.props, tweetId: { type: "string", label: "Tweet", description: "The Tweet to watch for retweets", options(context) { return this.tweetIdOptions(context); }, }, }, methods: { ...base.methods, async getScreenName() { const { screen_name: screenName } = await this.twitter.verifyCredentials(); return screenName; }, generateMeta(tweet) { const baseMeta = base.methods.generateMeta.bind(this)(tweet); const { screen_name: screenName = "N/A" } = tweet.user; const summary = `Retweet by @${screenName}`; return { ...baseMeta, summary, }; }, retrieveTweets() { return this.twitter.getRetweets({ id: this.tweetId, count: this.count, since_id: this.getSinceId(), }); }, }, }; <|start_filename|>components/intercom/sources/new-company/new-company.js<|end_filename|> const intercom = require("../../intercom.app.js"); module.exports = { key: "intercom-new-company", name: "New Companies", description: "Emits an event each time a new company is added.", version: "0.0.1", dedupe: "unique", props: { intercom, db: "$.service.db", timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 15, }, }, }, async run(event) { const monthAgo = this.intercom.monthAgo(); let lastCompanyCreatedAt = this.db.get("lastCompanyCreatedAt") || Math.floor(monthAgo / 1000); const companies = await this.intercom.getCompanies(lastCompanyCreatedAt); for (const company of companies) { if (company.created_at > lastCompanyCreatedAt) lastCompanyCreatedAt = company.created_at; this.$emit(company, { id: company.id, summary: company.name, ts: company.created_at, }); } this.db.set("lastCompanyCreatedAt", lastCompanyCreatedAt); }, }; <|start_filename|>components/todoist/sources/sync-resources/sync-resources.js<|end_filename|> const todoist = require("../../todoist.app.js"); const common = require("../common-project.js"); module.exports = { ...common, key: "todoist-sync-resources", name: "Sync Resources", description: "Emit updates for your selected resources", version: "0.0.1", props: { ...common.props, includeResourceTypes: { propDefinition: [todoist, "includeResourceTypes"] }, }, async run(event) { let emitCount = 0; const syncResult = await this.todoist.syncResources( this.db, this.includeResourceTypes ); for (const property in syncResult) { if (Array.isArray(syncResult[property])) { syncResult[property].forEach((element) => { let data = {}; data.resource = property; data.data = element; this.$emit(data, { summary: property, }); emitCount++; }); } } console.log(`Emitted ${emitCount} events.`); }, }; <|start_filename|>components/slack/actions/add_star/add_star.js<|end_filename|> const slack = require("../../slack.app.js"); module.exports = { key: "slack-add-star", name: "Add Star", description: "Add a star to an item on behalf of the authenticated user", version: "0.0.1", type: "action", props: { slack, conversation: { propDefinition: [ slack, "conversation", ], optional: true, description: "Channel to add star to, or channel where the message to add star to was posted (used with timestamp).", }, timestamp: { propDefinition: [ slack, "timestamp", ], optional: true, description: "Timestamp of the message to add star to.", }, file: { propDefinition: [ slack, "file", ], optional: true, description: "File to add star to.", }, }, async run() { return await this.slack.sdk().stars.add({ conversation: this.conversation, timestamp: this.timestamp, file: this.file, }); }, }; <|start_filename|>components/slack/actions/delete-message/delete-message.js<|end_filename|> const slack = require("../../slack.app.js"); module.exports = { key: "slack-delete-message", name: "Delete Message", description: "Delete a message", version: "0.0.1", type: "action", props: { slack, conversation: { propDefinition: [ slack, "conversation", ], }, timestamp: { propDefinition: [ slack, "timestamp", ], }, as_user: { propDefinition: [ slack, "as_user", ], description: "Pass true to update the message as the authed user. Bot users in this context are considered authed users.", }, }, async run() { return await this.slack.sdk().chat.delete({ channel: this.conversation, ts: this.timestamp, as_user: this.as_user, }); }, }; <|start_filename|>components/gorgias/sources/new-events/new-events.js<|end_filename|> const gorgias = require('../../gorgias.app.js') const moment = require('moment') const axios = require('axios') module.exports = { key: "gorgias-new-events", name: "New Events", description: "Emit when there is a new event", version: "0.0.1", props: { db: "$.service.db", timer: { type: "$.interface.timer", default: { intervalSeconds: 60, }, }, gorgias, }, dedupe: "greatest", async run(event) { const url = `https://${this.gorgias.$auth.domain}.gorgias.com/api/events/?per_page=100` const data = (await axios({ method: "get", url, auth: { username: `${this.gorgias.$auth.email}`, password: <PASSWORD>}`, }, })).data data.data.forEach(gorgias_event=>{ this.$emit(gorgias_event,{ id: gorgias_event.id, ts: moment(gorgias_event.created_datetime).valueOf(), summary: gorgias_event.type, }) }) }, } <|start_filename|>components/pagerduty/sources/new-oncall-rotation/new-oncall-rotation.js<|end_filename|> const differenceBy = require("lodash.differenceby"); const pagerduty = require("../../pagerduty.app.js"); module.exports = { key: "pagerduty-new-on-call-rotation", name: "New On-Call Rotation", version: "0.0.1", description: "Emits an event each time a new user rotates onto an on-call rotation", props: { pagerduty, db: "$.service.db", escalationPolicies: { propDefinition: [pagerduty, "escalationPolicies"] }, timer: { type: "$.interface.timer", label: "Interval to poll for new rotations", description: "The PagerDuty API doesn't support webhook notifications for on-call rotations, so we must poll the API to check for these changes. Change this interval according to your needs.", default: { intervalSeconds: 60 * 10, }, }, }, async run(event) { // If the user didn't watch specific escalation policies, // iterate through all of the policies on the account const escalationPolicies = this.escalationPolicies && this.escalationPolicies.length ? this.escalationPolicies : (await this.pagerduty.listEscalationPolicies()).map(({ id }) => id); // Since we can watch multiple escalation policies for rotations, we must // keep track of the last users who were on-call for a given policy. const onCallUsersByEscalationPolicy = this.db.get("onCallUsersByEscalationPolicy") || {}; for (const policy of escalationPolicies) { // Multiple users can technically be on-call at the same time if the account // has multiple schedules attached to an escalation policy, so we must watch // for any new users in the list of on-call users who were not in the list of // users previously on-call. See // https://community.pagerduty.com/forum/t/how-do-i-add-more-than-one-person-on-call-for-a-schedule/751 const onCallUsers = await this.pagerduty.listOnCallUsers({ escalation_policy_ids: [policy], }); const usersPreviouslyOnCall = onCallUsersByEscalationPolicy[policy] || []; // Retrieve the list of users who were previously not on-call, // but now entered the rotation const newOnCallUsers = differenceBy( onCallUsers, usersPreviouslyOnCall, "id" ); onCallUsersByEscalationPolicy[policy] = onCallUsers; if (!newOnCallUsers.length) { console.log( `No change to on-call users for escalation policy ${policy}` ); continue; } // Include escalation policy metadata in emit const escalationPolicy = await this.pagerduty.getEscalationPolicy(policy); for (const user of newOnCallUsers) { this.$emit( { user, escalationPolicy }, { summary: `${user.summary} is now on-call for escalation policy ${escalationPolicy.name}`, } ); } } // Persist the new set of on-call users for the next run this.db.set("onCallUsersByEscalationPolicy", onCallUsersByEscalationPolicy); }, }; <|start_filename|>components/zoom_admin/zoom_admin.app.js<|end_filename|> const axios = require("axios"); const sortBy = require("lodash/sortBy"); module.exports = { type: "app", app: "zoom_admin", propDefinitions: { webinars: { type: "string[]", label: "Webinars", optional: true, description: "Webinars you want to watch for new events. **Leave blank to watch all webinars**.", async options({ nextPageToken }) { const { webinars, next_page_token } = await this.listWebinars({ nextPageToken, }); if (!webinars.length) { return []; } const rawOptions = webinars.map((w) => ({ label: w.topic, value: w.id, })); const options = sortBy(rawOptions, ["label"]); return { options, context: { nextPageToken: next_page_token, }, }; }, }, }, methods: { _apiUrl() { return `https://api.zoom.us/v2`; }, _accessToken() { return this.$auth.oauth_access_token; }, async _makeRequest(opts) { if (!opts.headers) opts.headers = {}; opts.headers["Accept"] = "application/json"; opts.headers["Content-Type"] = "application/json"; opts.headers["Authorization"] = `Bearer ${this._accessToken()}`; opts.headers["user-agent"] = "@PipedreamHQ/pipedream v0.1"; const { path } = opts; delete opts.path; opts.url = `${this._apiUrl()}${path[0] === "/" ? "" : "/"}${path}`; return await axios(opts); }, async listWebinars({ pageSize, nextPageToken }) { const { data } = await this._makeRequest({ path: `/users/me/webinars`, params: { page_size: pageSize || 300, next_page_token: nextPageToken, }, }); return data; }, async listWebinarPanelists(webinarID) { const { data } = await this._makeRequest({ path: `/webinars/${webinarID}/panelists`, }); return data; }, }, }; <|start_filename|>components/snowflake/snowflake.app.js<|end_filename|> const { promisify } = require("util"); const snowflake = require("snowflake-sdk"); module.exports = { app: "snowflake", type: "app", methods: { async _getConnection() { if (this.connection) { return this.connection; } this.connection = snowflake.createConnection(this.$auth); await promisify(this.connection.connect).bind(this.connection)(); return this.connection; }, async getRows(statement) { const connection = await this._getConnection(); const executedStatement = connection.execute(statement); return executedStatement.streamRows(); }, async collectRows(statement) { const rowStream = await this.getRows(statement); const rows = []; for await (const row of rowStream) { rows.push(row); } return rows; }, async *collectRowsPaginated(statement, pageSize = 1) { const rowStream = await this.getRows(statement); let rows = []; for await (const row of rowStream) { rows.push(row); if (rows.length === pageSize) { yield rows; rows = []; } } yield rows; }, async listTables() { const sqlText = "SHOW TABLES"; return this.collectRows({ sqlText }); }, async listFieldsForTable(tableName) { const sqlText = "DESCRIBE TABLE IDENTIFIER(:1)"; const binds = [ tableName, ]; const statement = { sqlText, binds, }; return this.collectRows(statement); }, }, }; <|start_filename|>components/bitbucket/sources/new-pipeline-event/new-pipeline-event.js<|end_filename|> const isEmpty = require("lodash/isEmpty"); const common = require("../../common"); const { bitbucket } = common.props; const EVENT_SOURCE_NAME = "New Pipeline Event (Instant)"; module.exports = { ...common, name: EVENT_SOURCE_NAME, key: "bitbucket-new-pipeline-event", description: "Emits an event when a pipeline event occurs.", version: "0.0.1", props: { ...common.props, repositoryId: { optional: true, propDefinition: [ bitbucket, "repositoryId", c => ({ workspaceId: c.workspaceId }), ], }, eventTypes: { type: "string[]", label: "Pipeline Event Types", description: "The type of pipeline events that will trigger this event source", optional: true, options: [ // See https://support.atlassian.com/bitbucket-cloud/docs/event-payloads/ { label: 'Build started', value: 'INPROGRESS' }, { label: 'Build succeeded', value: 'SUCCESSFUL' }, { label: 'Build failed', value: 'FAILED' }, ], }, }, methods: { ...common.methods, getEventSourceName() { return EVENT_SOURCE_NAME; }, getHookEvents() { return [ 'repo:commit_status_created', 'repo:commit_status_updated', ]; }, getHookPathProps() { return { workspaceId: this.workspaceId, repositoryId: this.repositoryId, }; }, isEventRelevant(event) { const { state: eventType } = event.body.commit_status; return ( isEmpty(this.eventTypes) || this.eventTypes.some(i => i === eventType) ); }, generateMeta(data) { const { "x-request-uuid": id, "x-event-time": eventDate, } = data.headers; const { repository, state: eventType, } = data.body.commit_status; const summary = `New pipeline event in ${repository.name}: ${eventType}`; const ts = +new Date(eventDate); return { id, summary, ts, }; }, processEvent(event) { if (this.isEventRelevant(event)) { const parent = common.methods.processEvent.bind(this); return parent(event); } }, }, }; <|start_filename|>components/eventbrite/actions/get-event-attendees/get-event-attendees.js<|end_filename|> const eventbrite = require("../../eventbrite.app"); module.exports = { key: "eventbrite-get-event-attendees", name: "Get Event Attendees", description: "Get event attendees for a specified event.", version: "0.0.1", type: "action", props: { eventbrite, eventId: { propDefinition: [ eventbrite, "eventId", ], }, }, methods: { async *attendeeStream(params = {}) { let hasMoreItems; do { const { attendees, pagination = {}, } = await this.eventbrite.getEventAttendees(this.eventId, params); for (const attendee of attendees) { yield attendee; } hasMoreItems = !!pagination.has_more_items; params.continuation = pagination.continuation; } while (hasMoreItems); }, }, async run() { const attendeeStream = await this.attendeeStream(); const attendees = []; for await (const attendee of attendeeStream) { attendees.push(attendee); } return attendees; }, }; <|start_filename|>components/slack/actions/send-message-public-channel/send-message-public-channel.js<|end_filename|> const slack = require("../../slack.app.js"); module.exports = { key: "slack-send-message-public-channel", name: "Send Message to a Public Channel", description: "Send a message to a public channel and customize the name and avatar of the bot that posts the message", version: "0.1.0", type: "action", props: { slack, conversation: { propDefinition: [ slack, "publicChannel", ], }, text: { propDefinition: [ slack, "text", ], }, as_user: { propDefinition: [ slack, "as_user", ], }, username: { propDefinition: [ slack, "username", ], description: "Optionally customize your bot's username (default is `Pipedream`).", }, icon_emoji: { propDefinition: [ slack, "icon_emoji", ], description: "Optionally use an emoji as the bot icon for this message (e.g., `:fire:`). This value overrides `icon_url` if both are provided.", }, icon_url: { propDefinition: [ slack, "icon_url", ], description: "Optionally provide an image URL to use as the bot icon for this message.", }, }, async run() { return await this.slack.sdk().chat.postMessage({ channel: this.conversation, text: this.text, as_user: this.as_user, username: this.username, icon_emoji: this.icon_emoji, icon_url: this.icon_url, }); }, }; <|start_filename|>components/eventbrite/sources/new-event/new-event.js<|end_filename|> const common = require("../common/event.js"); module.exports = { ...common, key: "eventbrite-new-event", name: "New Event (Instant)", description: "Emits an event when an event has been created", version: "0.0.1", dedupe: "unique", methods: { ...common.methods, getActions() { return "event.created"; }, async getData(event) { return event; }, }, }; <|start_filename|>components/npm/sources/download-counts/download-counts.js<|end_filename|> const npm = require('../../npm.app.js') const axios = require('axios') module.exports = { key: "npm-download-counts", name: "npm Download Counts", description: "Emit an event with the latest count of downloads for an npm package", version: "0.0.1", props: { db: "$.service.db", timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 60 * 24, }, }, period: { type: "string", label: "Period", description: "Select last-day, last-week or last-month.", optional: false, default: "last-day", options: ["last-day", "last-week", "last-month"], }, package: { type: "string", label: "Package", description: "Enter an npm package name. Leave blank for all", optional: true, default: '@pipedreamhq/platform', }, npm, }, async run(event) { const npm_event = (await axios({ method: "get", url: `https://api.npmjs.org/downloads/point/${encodeURIComponent(this.period)}/${encodeURIComponent(this.package)}`, })).data this.$emit(npm_event, { summary: ""+npm_event.downloads, }) }, } <|start_filename|>interfaces/timer/examples/create-component/api-payload.json<|end_filename|> { "component_code": "module.exports = { name: 'cronjob', version: '0.0.1', props: { timer: { type: '$.interface.timer', default: { intervalSeconds: 60, } }, }, run() { console.log('Run any Node.js code here'); }, };", "name": "cronjob-api-test" } <|start_filename|>components/clickup/clickup.app.js<|end_filename|> const axios = require("axios"); const axiosRetry = require("axios-retry"); module.exports = { type: "app", app: "clickup", propDefinitions: { workspace: { type: "string", label: "Workspace", description: "Workspace", async options() { const workspaces = (await this.getWorkspaces()).teams; return workspaces.map((workspace) => ({ label: workspace.name, value: workspace.id, })); }, }, space: { type: "string", label: "Space", description: "Space", async options({ workspace }) { const spaces = (await this.getSpaces(workspace)).spaces; return spaces.map((space) => ({ label: space.name, value: space.id, })); }, }, folder: { type: "string", label: "Folder", description: "Folder", async options({ space }) { const folders = (await this.getFolders(space)).folders; return folders.map((folder) => ({ label: folder.name, value: folder.id, })); }, optional: true, }, list: { type: "string", label: "List", description: "List", async options({ folder, space, }) { const lists = folder ? (await this.getLists(folder)).lists : (await this.getFolderlessLists(space)).lists; return lists.map((list) => ({ label: list.name, value: list.id, })); }, }, assignees: { type: "string[]", label: "Assignees", description: "Select the assignees for the task", async options({ workspace }) { const members = await this.getWorkspaceMembers(workspace); return members.map((member) => ({ label: member.user.username, value: member.user.id, })); }, optional: true, }, tags: { type: "string[]", label: "Tags", description: "Select the tags for the task to filter when searching for the tasks", async options({ space }) { const tags = (await this.getTags(space)).tags; return tags.map((tag) => tag.name); }, optional: true, }, status: { type: "string", label: "Status", description: "Select the status of the task", async options({ list }) { const statuses = (await this.getList(list)).statuses; return statuses.map((status) => status.status); }, optional: true, }, task: { type: "string", label: "Task", description: "Task", async options({ list, page, }) { const tasks = (await this.getTasks(list, page)).tasks; return tasks.map((task) => ({ label: task.name, value: task.id, })); }, }, priority: { type: "integer", label: "Priority", description: `1 is Urgent 2 is High 3 is Normal 4 is Low`, optional: true, }, name: { type: "string", label: "Name", description: "Name", }, dueDate: { type: "integer", label: "Due Date", description: "Due Date", optional: true, }, dueDateTime: { type: "boolean", label: "Due Date Time", description: "Due Date Time", optional: true, }, parent: { type: "string", label: "Parent", description: `Pass an existing task ID in the parent property to make the new task a subtask of that parent. The parent you pass must not be a subtask itself, and must be part of the specified list.`, async options({ list, page, }) { const tasks = (await this.getTasks(list, page)).tasks; return tasks.map((task) => ({ label: task.name, value: task.id, })); }, }, }, methods: { async _makeRequest(method, endpoint, data = null, params = null) { axiosRetry(axios, { retries: 3, }); const config = { headers: { "content-type": "application/json", "Authorization": this.$auth.oauth_access_token, }, method, url: `https://api.clickup.com/api/v2/${endpoint}`, params, }; if (data) config.data = data; const response = await axios(config).catch((err) => { if (err.response.status !== 200) { throw new Error(`API call failed with status code: ${err.response.status} after 3 retry attempts`); } }); return response.data; }, async getWorkspaces() { return await this._makeRequest("GET", "team"); }, async getSpaces(workspaceId) { return await this._makeRequest( "GET", `team/${workspaceId}/space?archived=false`, ); }, async getFolders(spaceId) { return await this._makeRequest( "GET", `space/${spaceId}/folder?archived=false`, ); }, async getList(listId) { return await this._makeRequest("GET", `list/${listId}`); }, async getLists(folderId) { return await this._makeRequest( "GET", `folder/${folderId}/list?archived=false`, ); }, async getFolderlessLists(spaceId) { return await this._makeRequest( "GET", `space/${spaceId}/list?archived=false`, ); }, async getWorkspaceMembers(workspaceId) { const { teams } = (await this.getWorkspaces()); const workspace = teams.filter( (workspace) => workspace.id == workspaceId, ); return workspace ? workspace[0].members : []; }, async getTags(spaceId) { return await this._makeRequest("GET", `space/${spaceId}/tag`); }, async getTasks(listId, page = 0) { return await this._makeRequest( "GET", `list/${listId}/task?archived=false&page=${page}`, ); }, async createTask(listId, data) { return await this._makeRequest("POST", `list/${listId}/task`, data); }, async createList(folderId, data) { return await this._makeRequest("POST", `folder/${folderId}/list`, data); }, async createFolderlessList(spaceId, data) { return await this._makeRequest("POST", `space/${spaceId}/list`, data); }, }, }; <|start_filename|>components/hubspot/hubspot.app.js<|end_filename|> const axios = require("axios"); module.exports = { type: "app", app: "hubspot", propDefinitions: { lists: { type: "string[]", label: "Lists", description: "Select the lists to watch for new contacts.", async options(prevContext) { const { offset = 0 } = prevContext; const params = { count: 250, offset, }; const results = await this.getLists(params); const options = results.map((result) => { const { name: label, listId } = result; return { label, value: JSON.stringify({ label, value: listId }), }; }); return { options, context: { offset: params.offset + params.count, }, }; }, }, stages: { type: "string[]", label: "Stages", description: "Select the stages to watch for new deals in.", async options() { const results = await this.getDealStages(); const options = results.results[0].stages.map((result) => { const { label, stageId } = result; return { label, value: JSON.stringify({ label, value: stageId }), }; }); return options; }, }, objectType: { type: "string", label: "Object Type", description: "Watch for new events concerning the object type specified.", async options(opts) { return [ { label: "Companies", value: "company", }, { label: "Contacts", value: "contact", }, { label: "Deals", value: "deal", }, { label: "Tickets", value: "ticket", }, ]; }, }, objectIds: { type: "string[]", label: "Object", description: "Watch for new events concerning the objects selected.", async options(opts) { let objectType = null; if (opts.objectType == "company") objectType = "companies"; else objectType = `${opts.objectType}s`; const results = await this.getObjects(objectType); const options = results.map((result) => { const { id, properties } = result; switch (objectType) { case "companies": label = properties.name; break; case "contacts": label = `${properties.firstname} ${properties.lastname}`; break; case "deals": label = properties.dealname; break; case "tickets": label = properties.subject; break; } return { label, value: id }; }); return options; }, }, forms: { type: "string[]", label: "Form", description: "Watch for new submissions of the specified forms.", async options(prevContext) { const { offset } = prevContext; const params = { count: 50, offset: offset || 0, }; const results = await this.getForms(); const options = results.map((result) => { const { name: label, guid } = result; return { label, value: JSON.stringify({ label, value: guid }), }; }); return { options, context: { offset: params.offset + params.count, }, }; }, }, }, methods: { _getBaseURL() { return "https://api.hubapi.com"; }, _getHeaders() { return { Authorization: `Bearer ${this.$auth.oauth_access_token}`, "Content-Type": "application/json", }; }, monthAgo() { const monthAgo = new Date(); monthAgo.setMonth(monthAgo.getMonth() - 1); return monthAgo; }, async makeGetRequest(endpoint, params = null) { const config = { method: "GET", url: `${this._getBaseURL()}${endpoint}`, headers: this._getHeaders(), params, }; return (await axios(config)).data; }, async searchCRM({ object, ...data }) { const config = { method: "POST", url: `${this._getBaseURL()}/crm/v3/objects/${object}/search`, headers: this._getHeaders(), data, }; return (await axios(config)).data; }, async getBlogPosts(params) { return await this.makeGetRequest("/cms/v3/blogs/posts", params); }, async getCalendarTasks(endDate) { params = { startDate: Date.now(), endDate, }; return await this.makeGetRequest("/calendar/v1/events/task", params); }, async getContactProperties() { return await this.makeGetRequest("/properties/v1/contacts/properties"); }, async createPropertiesArray() { const allProperties = await this.getContactProperties(); return allProperties.map((property) => property.name); }, async getDealProperties() { return await this.makeGetRequest("/properties/v1/deals/properties"); }, async getDealStages() { return await this.makeGetRequest("/crm-pipelines/v1/pipelines/deal"); }, async getEmailEvents(params) { return await this.makeGetRequest("/email/public/v1/events", params); }, async getEngagements(params) { return await this.makeGetRequest( "/engagements/v1/engagements/paged", params ); }, async getEvents(params) { return await this.makeGetRequest("/events/v3/events", params); }, async getForms(params) { return await this.makeGetRequest("/forms/v2/forms", params); }, async getFormSubmissions(params) { const { formId } = params; delete params.formId; return await this.makeGetRequest( `/form-integrations/v1/submissions/forms/${formId}`, params ); }, async getLists(params) { const { lists } = await this.makeGetRequest("/contacts/v1/lists", params); return lists; }, async getListContacts(params, listId) { return await this.makeGetRequest( `/contacts/v1/lists/${listId}/contacts/all`, params ); }, async getObjects(objectType) { const params = { limit: 100, }; let results = null; const objects = []; while (!results || params.next) { results = await this.makeGetRequest( `/crm/v3/objects/${objectType}`, params ); if (results.paging) params.next = results.paging.next.after; else delete params.next; for (const result of results.results) { objects.push(result); } } return objects; }, async getContact(contactId, properties) { const params = { properties, }; return await this.makeGetRequest( `/crm/v3/objects/contacts/${contactId}`, params ); }, }, }; <|start_filename|>components/twist/sources/new-thread/new-thread.js<|end_filename|> const twist = require("../../twist.app.js"); const common = require("../common.js"); module.exports = { ...common, name: "New Thread (Instant)", version: "0.0.1", key: "twist-new-thread", description: "Emits an event for any new thread in a workspace", props: { ...common.props, channel: { propDefinition: [twist, "channel", (c) => ({ workspace: c.workspace })], }, }, methods: { getHookActivationData() { return { target_url: this.http.endpoint, event: "thread_added", workspace_id: this.workspace, channel_id: this.channel, }; }, getMeta(body) { const { id, title, posted } = body; return { id, summary: title, ts: Date.parse(posted), }; }, }, }; <|start_filename|>components/supersaas/sources/changed-appointments.js<|end_filename|> const dayjs = require('dayjs'); const makeEventSummary = require('../utils/makeEventSummary.js'); const supersaas = require('../supersaas.app.js'); module.exports = { key: 'supersaas-changed-appointments', name: 'New or changed appointments', description: `Emits an event for every changed appointments from the selected schedules.`, version: '0.0.1', props: { supersaas, schedules: { propDefinition: [supersaas, 'schedules'] }, db: "$.service.db", http: '$.interface.http', }, hooks: { async activate() { const { http, schedules } = this; this.db.set('activeHooks', await this.supersaas.createHooks(schedules.map(x => ({ event: 'C', // change_appointment parent_id: Number(x), target_url: http.endpoint, })))); }, async deactivate() { await this.supersaas.destroyHooks(this.db.get('activeHooks') || []); this.db.set('activeHooks', []); }, }, async run(ev) { const outEv = { meta: { summary: makeEventSummary(ev), ts: dayjs(ev.body.created_on).valueOf(), }, body: ev.body, }; console.log('Emitting:', outEv); this.$emit(outEv, outEv.meta); }, }; <|start_filename|>components/yotpo/sources/new-reviews/new-reviews.js<|end_filename|> const _get = require("lodash.get") const _truncate = require("lodash.truncate") const he = require("he") const moment = require('moment') const yotpo = require('../../yotpo.app.js') module.exports = { name: "New Reviews", description: "Emits a new event any time a Yotpo review is created or updated", key: "yotpo-new-reviews", version: '0.0.1', dedupe: "unique", props: { http: { type: "$.interface.http", }, yotpo, }, hooks: { async activate() { await this.yotpo.createWebhook("review_create", this.http.endpoint) await this.yotpo.createWebhook("review_updated", this.http.endpoint) }, async deactivate() { await this.yotpo.deleteWebhook("review_create", this.http.endpoint) await this.yotpo.deleteWebhook("review_updated", this.http.endpoint) }, }, async run(event) { const id = _get(event, "body.data.id") const updatedAt = _get(event, "body.data.updated_at") if (id && updatedAt) { const dedupeId = `${id}-${updatedAt}` const flag = _get(event, "body.data.new") ? "" : " [UPDATED]" const score = _get(event, "body.data.score", "?") const text = _truncate(he.decode(_get(event, "body.data.title", _get(event, "body.data.content", "- no content -")))) const summary = `${score} stars:${flag} ${text}` const ts = moment(updatedAt).valueOf() this.$emit(event.body, { id: dedupeId, summary, ts }) } }, } <|start_filename|>components/hubspot/sources/new-form-submission/new-form-submission.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, key: "hubspot-new-form-submission", name: "New Form Submission", description: "Emits an event for each new submission of a form.", version: "0.0.2", dedupe: "unique", props: { ...common.props, forms: { propDefinition: [common.props.hubspot, "forms"] }, }, hooks: {}, methods: { ...common.methods, generateMeta(result) { const { pageUrl, submittedAt: ts } = result; const submitted = new Date(ts); return { id: `${pageUrl}${ts}`, summary: `Form submitted at ${submitted.toLocaleDateString()} ${submitted.toLocaleTimeString()}`, ts, }; }, isRelevant(result, submittedAfter) { return result.submittedAt > submittedAfter; }, }, async run(event) { const submittedAfter = this._getAfter(); const baseParams = { limit: 50, }; await Promise.all( this.forms .map(JSON.parse) .map(({ value }) => ({ ...baseParams, formId: value, })) .map((params) => this.paginate( params, this.hubspot.getFormSubmissions.bind(this), "results", submittedAfter ) ) ); this._setAfter(Date.now()); }, }; <|start_filename|>components/twilio/sources/new-phone-number/new-phone-number.js<|end_filename|> const common = require("../common-polling.js"); module.exports = { ...common, key: "twilio-new-phone-number", name: "New Phone Number", description: "Emits an event when you add a new phone number to your account", version: "0.0.1", dedupe: "unique", methods: { ...common.methods, async listResults(...args) { return await this.twilio.listIncomingPhoneNumbers(...args); }, generateMeta(number) { const { sid: id, friendlyName: summary, dateCreated } = number; return { id, summary, ts: Date.parse(dateCreated), }; }, }, }; <|start_filename|>components/ringcentral/sources/new-voicemail-message/new-voicemail-message.js<|end_filename|> const common = require("../common/http-based"); module.exports = { ...common, key: "ringcentral-new-voicemail-message", name: "New Voicemail Message (Instant)", description: "Emits an event when a new voicemail message is received", version: "0.0.1", props: { ...common.props, extensionId: { propDefinition: [common.props.ringcentral, "extensionId"] }, }, methods: { ...common.methods, getSupportedNotificationTypes() { return new Set([ "voicemail-message-event", ]); }, generateMeta(data) { const { uuid: id, timestamp, body: eventDetails, } = data; const { from: { phoneNumber: callerPhoneNumber, }, } = eventDetails; const maskedCallerNumber = this.getMaskedNumber(callerPhoneNumber); const summary = `New voicemail from ${maskedCallerNumber}`; const ts = Date.parse(timestamp); return { id, summary, ts, }; }, }, }; <|start_filename|>components/calendly/sources/invitee-created/invitee-created.js<|end_filename|> const common = require("../common-webhook.js"); module.exports = { ...common, key: "calendly-invitee-created", name: "Invitee Created (Instant)", description: "Emits an event when an invitee schedules an event", version: "0.0.2", dedupe: "unique", methods: { ...common.methods, getEvents() { return ["invitee.created"]; }, generateMeta(body) { return this.generateInviteeMeta(body); }, }, }; <|start_filename|>components/ahrefs/actions/get-backlinks/get-backlinks.js<|end_filename|> const ahrefs = require('../../ahrefs.app.js') const axios = require('axios') module.exports = { name: 'Get Backlinks', key: "ahrefs-get-backlinks", description: "Get the backlinks for a domain or URL with details for the referring pages (e.g., anchor and page title).", version: '0.0.8', type: "action", props: { ahrefs, target: { propDefinition: [ahrefs, "target"] }, mode: { propDefinition: [ahrefs, "mode"] }, limit: { propDefinition: [ahrefs, "limit"] }, }, async run() { return (await axios({ url: `https://apiv2.ahrefs.com`, params: { token: this.ahrefs.$auth.oauth_access_token, from: "backlinks", target: this.target, mode: this.mode, limit: this.limit, order_by: "ahrefs_rank:desc", output: "json" }, })).data }, } <|start_filename|>components/hacker_news/hacker_news.app.js<|end_filename|> module.exports = { type: "app", app: "hacker_news", } <|start_filename|>components/calendly/sources/common-polling.js<|end_filename|> const calendly = require("../calendly.app.js"); module.exports = { props: { calendly, db: "$.service.db", timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 15, }, }, }, methods: { _getLastEvent() { const lastEvent = this.db.get("lastEvent") || this.calendly.monthAgo(); return lastEvent; }, _setLastEvent(lastEvent) { this.db.set("lastEvent", lastEvent); }, }, async run(event) { const lastEvent = this._getLastEvent(); const results = await this.getResults(); for (const result of results) { if (this.isRelevant(result, lastEvent)) { const meta = this.generateMeta(result); this.$emit(result, meta); } } this._setLastEvent(Date.now()); }, }; <|start_filename|>components/webflow/sources/collection-common.js<|end_filename|> const common = require("./common"); module.exports = { ...common, dedupe: "unique", props: { ...common.props, collectionIds: { type: "string[]", label: "Collections", description: "The collections to monitor for item changes", optional: true, async options(context) { const { page } = context; if (page !== 0) { return { options: [], }; } const collections = await this.webflow.listCollections(this.siteId); const options = collections.map(collection => ({ label: collection.name, value: collection._id, })); return { options, }; }, }, }, methods: { ...common.methods, isEventRelevant(event) { const { body: { _cid: collectionId } } = event; return this.collectionIds.includes(collectionId); }, }, }; <|start_filename|>components/todoist/sources/completed-task/completed-task.js<|end_filename|> const common = require("../common-task.js"); module.exports = { ...common, key: "todoist-completed-task", name: "Completed Task", description: "Emit an event for each completed task", version: "0.0.1", dedupe: "unique", methods: { ...common.methods, isElementRelevant(element) { return element.checked === 1; }, }, }; <|start_filename|>components/google_drive/sources/new-or-modified-files/new-or-modified-files.js<|end_filename|> // This source processes changes to any files in a user's Google Drive, // implementing strategy enumerated in the Push Notifications API docs: // https://developers.google.com/drive/api/v3/push and here: // https://developers.google.com/drive/api/v3/manage-changes // // This source has two interfaces: // // 1) The HTTP requests tied to changes in the user's Google Drive // 2) A timer that runs on regular intervals, renewing the notification channel as needed const common = require("../common-webhook.js"); const { GOOGLE_DRIVE_NOTIFICATION_ADD, GOOGLE_DRIVE_NOTIFICATION_CHANGE, GOOGLE_DRIVE_NOTIFICATION_UPDATE, } = require("../../constants"); module.exports = { ...common, key: "google_drive-new-or-modified-files", name: "New or Modified Files", description: "Emits a new event any time any file in your linked Google Drive is added, modified, or deleted", version: "0.0.14", type: "source", // Dedupe events based on the "x-goog-message-number" header for the target channel: // https://developers.google.com/drive/api/v3/push#making-watch-requests dedupe: "unique", methods: { ...common.methods, getUpdateTypes() { return [ GOOGLE_DRIVE_NOTIFICATION_ADD, GOOGLE_DRIVE_NOTIFICATION_CHANGE, GOOGLE_DRIVE_NOTIFICATION_UPDATE, ]; }, generateMeta(data, headers) { const { id: fileId, name: summary, modifiedTime: tsString, } = data; const { "x-goog-message-number": eventId } = headers; return { id: `${fileId}-${eventId}`, summary, ts: Date.parse(tsString), }; }, async processChanges(changedFiles, headers) { for (const file of changedFiles) { const eventToEmit = { file, change: { state: headers["x-goog-resource-state"], resourceURI: headers["x-goog-resource-uri"], changed: headers["x-goog-changed"], // "Additional details about the changes. Possible values: content, parents, children, permissions" }, }; const meta = this.generateMeta(file, headers); this.$emit(eventToEmit, meta); } }, }, }; <|start_filename|>components/mysql/mysql.app.js<|end_filename|> const mysqlClient = require("mysql2/promise"); module.exports = { type: "app", app: "mysql", propDefinitions: { table: { type: "string", label: "Table", description: "The database table to watch for changes", async options() { const { database } = this.$auth; const connection = await this.getConnection(); const tables = await this.listTables(connection); await this.closeConnection(connection); return tables.map((table) => { return table[`Tables_in_${database}`]; }); }, }, column: { type: "string", label: "Column", description: "The name of a column in the table to use for deduplication. Defaults to the table's primary key", async options(opts) { return this.listColumnNames(opts.table); }, }, query: { type: "string", label: "SQL Query", description: "Your custom SQL query", }, }, methods: { async getConnection() { const { host, port, username, password, database } = this.$auth; return await mysqlClient.createConnection({ host, port, user: username, password, database, }); }, async closeConnection(connection) { const connectionClosed = new Promise((resolve) => { connection.connection.stream.on("close", resolve); }); await connection.end(); await connectionClosed; }, async executeQuery(connection, query) { const results = await connection.execute(query); return results[0]; }, async listTables(connection) { const options = { sql: "SHOW FULL TABLES", }; return await this.executeQuery(connection, options); }, async listBaseTables(connection, lastResult) { const options = { sql: ` SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND CREATE_TIME > ? ORDER BY CREATE_TIME DESC `, values: [lastResult], }; return await this.executeQuery(connection, options); }, async listTopTables(connection, maxCount = 10) { const options = { sql: ` SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' ORDER BY CREATE_TIME DESC LIMIT ? `, values: [maxCount], }; return await this.executeQuery(connection, options); }, async listColumns(connection, table) { const options = { sql: `SHOW COLUMNS FROM \`${table}\``, }; return await this.executeQuery(connection, options); }, async listNewColumns(connection, table, previousColumns) { const options = { sql: ` SHOW COLUMNS FROM \`${table}\` WHERE Field NOT IN (?) `, values: [previousColumns.join()], }; return await this.executeQuery(connection, options); }, /** * Returns rows from a specified table. * @param {object} connection - The database connection. * @param {string} table - Name of the table to search. * @param {string} column - Name of the table column to order by * @param {string} lastResult - Maximum result in the specified table column that has been previously returned. */ async listRows(connection, table, column, lastResult) { const options = { sql: ` SELECT * FROM \`${table}\` WHERE \`${column}\` > ? ORDER BY \`${column}\` DESC `, values: [lastResult], }; return await this.executeQuery(connection, options); }, /** * Returns rows from a specified table. Used when lastResult has not yet been set. Returns a maximum of 10 results * ordered by the specified column. * @param {object} connection - The database connection. * @param {string} table - Name of the table to search. * @param {string} column - Name of the table column to order by */ async listMaxRows(connection, table, column, maxCount = 10) { const options = { sql: ` SELECT * FROM \`${table}\` ORDER BY \`${column}\` DESC LIMIT ? `, values: [maxCount], }; return await this.executeQuery(connection, options); }, async getPrimaryKey(connection, table) { const options = { sql: `SHOW KEYS FROM ? WHERE Key_name = 'PRIMARY'`, values: [table], }; return await this.executeQuery(connection, options); }, async listColumnNames(table) { const connection = await this.getConnection(); const columns = await this.listColumns(connection, table); await this.closeConnection(connection); return columns.map((column) => column.Field); }, }, }; <|start_filename|>components/ringcentral/sources/common/message-types.js<|end_filename|> module.exports = [ "Fax", "Pager", "SMS", "Voicemail", ]; <|start_filename|>components/swapi/actions/get-film/get-film.js<|end_filename|> const swapi = require('../../swapi.app.js') const axios = require('axios') module.exports = { key: "swapi-get-film", name: "Get Film", version: "0.0.12", type: "action", props: { swapi, film: { propDefinition: [swapi, "film"] }, }, async run() { return (await axios({ url: `https://swapi.dev/api/films/${this.film}` })).data }, } <|start_filename|>components/activecampaign/sources/new-or-updated-deal/new-or-updated-deal.js<|end_filename|> const activecampaign = require("../../activecampaign.app.js"); const common = require("../common-webhook.js"); module.exports = { ...common, name: "New Deal Added or Updated (Instant)", key: "activecampaign-new-or-updated-deal", description: "Emits an event each time a deal is added or updated.", version: "0.0.1", methods: { ...common.methods, getEvents() { return ["deal_add", "deal_update"]; }, getMeta(body) { const { date_time: dateTimeIso } = body; const ts = Date.parse(dateTimeIso); return { id: `${body["deal[id]"]}${new Date(body.date_time).getTime()}`, summary: body["deal[title]"], ts }; }, }, }; <|start_filename|>components/twilio/actions/send-mms/send-mms.js<|end_filename|> // Read the Twilio docs at https://www.twilio.com/docs/sms/api/message-resource#create-a-message-resource const twilio = require("../../twilio.app.js"); const { phone } = require("phone"); module.exports = { key: "twilio-send-mms", name: "Send MMS", description: "Send an SMS with text and media files.", type: "action", version: "0.0.4", props: { twilio, from: { propDefinition: [ twilio, "from", ], }, to: { propDefinition: [ twilio, "to", ], }, body: { propDefinition: [ twilio, "body", ], }, mediaUrl: { propDefinition: [ twilio, "mediaUrl", ], }, }, async run() { // Parse the given number into its E.164 equivalent // The E.164 phone number will be included in the first element // of the array, but the array will be empty if parsing fails. // See https://www.npmjs.com/package/phone const toParsed = phone(this.to); if (!toParsed || !toParsed.phoneNumber) { throw new Error(`Phone number ${this.to} couldn't be parsed as a valid number.`); } const data = { to: toParsed.phoneNumber, from: this.from, body: this.body, mediaUrl: this.mediaUrl, }; return await this.twilio.getClient().messages.create(data); }, }; <|start_filename|>components/twilio/sources/new-call/new-call.js<|end_filename|> const common = require("../common-webhook.js"); module.exports = { ...common, key: "twilio-new-call", name: "New Call (Instant)", description: "Configures a webhook in Twilio, tied to a phone number, and emits an event each time a call to that number is completed", version: "0.0.1", dedupe: "unique", methods: { ...common.methods, async setWebhook(...args) { return await this.twilio.setIncomingCallWebhookURL(...args); }, generateMeta(body, headers) { return { /** if Twilio retries a message, but we've already emitted, dedupe */ id: headers["i-twilio-idempotency-token"], summary: `New call from ${this.getMaskedNumber(body.From)}`, ts: Date.now(), }; }, isRelevant(body) { return body.CallStatus == "completed"; }, getMaskedNumber(number) { const { length: numberLength } = number; return number.slice(numberLength - 4).padStart(numberLength, "#"); }, }, }; <|start_filename|>components/supersaas/supersaas.app.js<|end_filename|> const envConf = require('./envConf.js'); module.exports = { type: 'app', app: 'supersaas', propDefinitions: { schedules: { type: 'string[]', label: 'Schedules', description: `The schedules you'd like to watch for changes`, async options() { return await this.getSchedules(); }, }, }, methods: { async axios(path, opts = {}) { const { axios } = await require('@pipedreamhq/platform'); return await axios(this, { url: `${envConf.urlPrefix}${path}`, ...opts, params: { account: this.$auth.account, api_key: this.$auth.api_key, ...opts.params || {}, }, }); }, async getSchedules() { const xs = await this.axios('/api/schedules.json'); return xs.map(x => ({ value: x.id, label: x.name })); }, async createHooks(hookParams) { const { axios } = this; console.log('Creating hooks:', hookParams); return await Promise.all(hookParams.map( x => axios('/api/hooks', { method: 'POST', params: x }), )); }, // TODO: Better error handling. Dylan suggested retries with a backoff // algorithm, but that sounds a little overkill to me; but I guess we // could at least remember failed hook destructions and retry on every // activate/deactivate cycle? async destroyHooks(activeHooks) { const { axios } = this; console.log('Destroying hooks:', activeHooks || []); if (!activeHooks || !activeHooks.length) { return; } return await Promise.all(activeHooks.map(x => axios('/api/hooks', { method: 'DELETE', params: { id: x.id, parent_id: x.parent_id }, }))); }, }, }; <|start_filename|>components/hubspot/sources/deal-updated/deal-updated.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, key: "hubspot-deal-updated", name: "Deal Updated", description: "Emits an event each time a deal is updated.", version: "0.0.2", hooks: {}, methods: { ...common.methods, generateMeta(deal) { const { id, properties, updatedAt } = deal; const ts = Date.parse(updatedAt); return { id: `${id}${ts}`, summary: properties.dealname, ts, }; }, isRelevant(deal, updatedAfter) { return Date.parse(deal.updatedAt) > updatedAfter; }, }, async run(event) { const updatedAfter = this._getAfter(); const data = { limit: 100, sorts: [ { propertyName: "hs_lastmodifieddate", direction: "DESCENDING", }, ], object: "deals", }; await this.paginate( data, this.hubspot.searchCRM.bind(this), "results", updatedAfter ); this._setAfter(Date.now()); }, }; <|start_filename|>components/twitch/actions/get-channel-editors/get-channel-editors.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, name: "Get Channel Editors", key: "twitch-get-channel-editors", description: "Gets a list of users who are editors for your channel", version: "0.0.1", type: "action", async run() { // get the userID of the authenticated user const userId = await this.getUserId(); const params = { broadcaster_id: userId, }; return (await this.twitch.getChannelEditors(params)).data.data; }, }; <|start_filename|>components/eventbrite/sources/common/base.js<|end_filename|> const eventbrite = require("../../eventbrite.app.js"); module.exports = { props: { eventbrite, db: "$.service.db", organization: { propDefinition: [eventbrite, "organization"] }, }, methods: { generateMeta() { throw new Error("generateMeta is not implemented"); }, emitEvent(data) { const meta = this.generateMeta(data); this.$emit(data, meta); }, async *resourceStream(resourceFn, resource, params = null) { let hasMoreItems; do { const { [resource]: items, pagination = {} } = await resourceFn(params); for (const item of items) { yield item; } hasMoreItems = !!pagination.has_more_items; params.continuation = pagination.continuation; } while (hasMoreItems); }, }, }; <|start_filename|>components/mailgun/actions/suppress-email/suppress-email.js<|end_filename|> const mailgun = require("../../mailgun.app.js"); module.exports = { key: "mailgun-suppress-email", name: "Mailgun Suppress Email", description: "Add email to the Mailgun suppression list.", version: "0.0.1", type: "action", props: { mailgun, domain: { propDefinition: [ mailgun, "domain", ], }, email: { propDefinition: [ mailgun, "email", ], }, category: { type: "string", options: [ "bounces", "unsubscribes", "complaints", ], }, bounceErrorCode: { type: "string", label: "Bounce Error Code", default: "550", optional: true, }, bounceErrorMessage: { type: "string", label: "Bounce Error Message", optional: true, }, unsubscribeFrom: { type: "string", label: "Tag to unsubscribe from", description: "Use * to unsubscribe an address from all domain’s correspondence", default: "*", optional: true, }, haltOnError: { propDefinition: [ mailgun, "haltOnError", ], }, }, async run () { try { const suppression = { address: this.email, }; switch (this.category) { case "bounces": suppression.code = this.bounceErrorCode; suppression.error = this.bounceErrorMessage; break; case "unsubscribes": suppression.tag = this.unsubscribeFrom; break; } return await this.mailgun.suppress(this.domain, this.category, suppression); } catch (err) { if (this.haltOnError) { throw err; } if (err.response) { return err.response.data; } return err; } }, }; <|start_filename|>components/google_drive/actions/google-mime-types.js<|end_filename|> module.exports = [ "application/vnd.google-apps.audio", "application/vnd.google-apps.document", "application/vnd.google-apps.drive-sdk", "application/vnd.google-apps.drawing", "application/vnd.google-apps.file", "application/vnd.google-apps.folder", "application/vnd.google-apps.form", "application/vnd.google-apps.fusiontable", "application/vnd.google-apps.map", "application/vnd.google-apps.photo", "application/vnd.google-apps.presentation", "application/vnd.google-apps.script", "application/vnd.google-apps.shortcut", "application/vnd.google-apps.site", "application/vnd.google-apps.spreadsheet", "application/vnd.google-apps.unknown", "application/vnd.google-apps.video", ]; <|start_filename|>components/twitch/actions/get-channel-teams/get-channel-teams.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, name: "Get Channel Teams", key: "twitch-get-channel-teams", description: "Gets a list of teams to which a specified channel belongs", version: "0.0.1", type: "action", props: { ...common.props, broadcaster: { propDefinition: [ common.props.twitch, "broadcaster", ], description: "The broadcaster ID of the channel to get teams for", }, }, async run() { const params = { broadcaster_id: this.broadcaster, }; return (await this.twitch.getChannelTeams(params)).data.data; }, }; <|start_filename|>components/dropbox/sources/new-folder/new-folder.js<|end_filename|> const dropbox = require("../../dropbox.app.js"); module.exports = { key: "dropbox-new-folder", name: "New Folder", version: "0.0.4", description: "Emits an event when a new folder is created. Make sure the number of files/folders in the watched folder does not exceed 4000.", props: { dropbox, path: { propDefinition: [dropbox, "path"] }, recursive: { propDefinition: [dropbox, "recursive"] }, dropboxApphook: { type: "$.interface.apphook", appProp: "dropbox", static: [], }, db: "$.service.db", }, hooks: { async activate() { await this.dropbox.initState(this); }, }, async run(event) { const updates = await this.dropbox.getUpdates(this); for (update of updates) { if (update[".tag"] == "folder") { this.$emit(update); } } }, }; <|start_filename|>components/twitter/sources/user-tweets/user-tweets.js<|end_filename|> const base = require("../common/tweets"); module.exports = { ...base, key: "twitter-user-tweets", name: "User Tweets", description: "Emit new Tweets posted by a user", version: "0.0.5", props: { ...base.props, screen_name: { propDefinition: [ base.props.twitter, "screen_name", ], }, includeRetweets: { propDefinition: [ base.props.twitter, "includeRetweets", ], }, includeReplies: { propDefinition: [ base.props.twitter, "includeReplies", ], }, }, methods: { ...base.methods, shouldExcludeReplies() { return this.includeReplies === "exclude"; }, shouldIncludeRetweets() { return this.includeRetweets !== "exclude"; }, retrieveTweets() { return this.twitter.getUserTimeline({ screen_name: this.screen_name, count: this.count, since_id: this.getSinceId(), exclude_replies: this.shouldExcludeReplies(), include_rts: this.shouldIncludeRetweets(), }); }, }, }; <|start_filename|>components/intercom/sources/new-event/new-event.js<|end_filename|> const intercom = require("../../intercom.app.js"); module.exports = { key: "intercom-new-event", name: "New Event", description: "Emits an event for each new Intercom event for a user.", version: "0.0.1", dedupe: "unique", props: { intercom, userIds: { type: "string[]", label: "Users", async options(opts) { const data = { query: { field: "role", operator: "=", value: "user", }, }; const results = await this.intercom.searchContacts(data); return results.map((user) => { return { label: user.name || user.id, value: user.id }; }); }, }, db: "$.service.db", timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 15, }, }, }, async run(event) { for (const userId of this.userIds) { let since = this.db.get(userId) || null; const results = await this.intercom.getEvents(userId, since); for (const result of results.events) { this.$emit(result, { id: result.id, summary: result.event_name, ts: result.created_at, }); } // store the latest 'since' url by the userId if (results.since) this.db.set(userId, results.since); } }, }; <|start_filename|>components/ongage/actions/find-subscriber/find-subscriber.js<|end_filename|> const ongage = require("../../ongage.app.js"); module.exports = { key: "ongage-find-subscriber", name: "Ongage Find Subscriber", description: "Find a list subscriber in Ongage.", version: "0.0.1", type: "action", props: { ongage, email: { propDefinition: [ ongage, "email", ], }, haltOnError: { propDefinition: [ ongage, "haltOnError", ], }, }, async run () { try { return await this.ongage.findSubscriber( this.email, ); } catch (err) { if (this.haltOnError) { throw err; } if (err.response) { return err.response.data; } return err; } }, }; <|start_filename|>components/docusign/sources/new-folder/new-folder.js<|end_filename|> const docusign = require("../../docusign.app.js"); module.exports = { key: "docusign-new-folder", name: "New Folder", description: "Emits an event when a new folder is created", version: "0.0.2", dedupe: "unique", props: { docusign, db: "$.service.db", timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 15, }, }, account: { propDefinition: [ docusign, "account", ], }, include: { type: "string[]", label: "Folder types", description: "Folder types to include in the response", options: [ "envelope_folders", "template_folders", "shared_template_folders", ], default: [ "envelope_folders", "template_folders", "shared_template_folders", ], }, }, methods: { async processFolders(baseUri, params, folders, ts) { for (const folder of folders) { if (folder.hasSubFolders == "true") { for (const subfolder of folder.folders) { let done = false; do { const { folders: subfolders, nextUri, resultSetSize, } = await this.docusign.listFolderItems(baseUri, params, subfolder.folderId); await this.processFolders(baseUri, params, subfolders, ts); if (nextUri) params.start_postion += resultSetSize + 1; else done = true; } while (!done); } } const meta = this.generateMeta(folder, ts); this.$emit(folder, meta); } }, generateMeta({ folderId: id, name: summary, }, ts) { return { id, summary, ts, }; }, }, async run(event) { const { timestamp: ts } = event; const baseUri = await this.docusign.getBaseUri(this.account); let done = false; const params = { start_position: 0, include: (this.include).join(), include_items: true, }; do { const { folders = [], nextUri, resultSetSize, } = await this.docusign.listFolders(baseUri, params); if (nextUri) params.start_position += resultSetSize + 1; else done = true; await this.processFolders(baseUri, params, folders, ts); } while (!done); }, }; <|start_filename|>components/google_drive/sources/new-files-instant/new-files-instant.js<|end_filename|> const common = require("../common-webhook.js"); const { GOOGLE_DRIVE_NOTIFICATION_ADD, GOOGLE_DRIVE_NOTIFICATION_CHANGE, } = require("../../constants"); module.exports = { ...common, key: "google_drive-new-files-instant", name: "New Files (Instant)", description: "Emits a new event any time a new file is added in your linked Google Drive", version: "0.0.8", type: "source", dedupe: "unique", props: { ...common.props, folders: { type: "string[]", label: "Folders", description: "(Optional) The folders you want to watch for changes. Leave blank to watch for any new file in the Drive.", optional: true, default: [], options({ prevContext }) { const { nextPageToken } = prevContext; const baseOpts = { q: "mimeType = 'application/vnd.google-apps.folder'", }; const opts = this.isMyDrive() ? baseOpts : { ...baseOpts, corpora: "drive", driveId: this.getDriveId(), includeItemsFromAllDrives: true, supportsAllDrives: true, }; return this.googleDrive.listFilesOptions(nextPageToken, opts); }, }, }, hooks: { ...common.hooks, async activate() { await common.hooks.activate.bind(this)(); this._setLastFileCreatedTime(Date.now()); }, }, methods: { ...common.methods, _getLastFileCreatedTime() { return this.db.get("lastFileCreatedTime"); }, _setLastFileCreatedTime(lastFileCreatedTime) { this.db.set("lastFileCreatedTime", lastFileCreatedTime); }, shouldProcess(file) { const watchedFolders = new Set(this.folders); return ( watchedFolders.size == 0 || (file.parents && file.parents.some((p) => watchedFolders.has(p))) ); }, getUpdateTypes() { return [ GOOGLE_DRIVE_NOTIFICATION_ADD, GOOGLE_DRIVE_NOTIFICATION_CHANGE, ]; }, async processChanges(changedFiles) { const lastFileCreatedTime = this._getLastFileCreatedTime(); let maxCreatedTime = lastFileCreatedTime; for (const file of changedFiles) { const fileInfo = await this.googleDrive.getFile(file.id); const createdTime = Date.parse(fileInfo.createdTime); if ( !this.shouldProcess(fileInfo) || createdTime < lastFileCreatedTime ) { continue; } this.$emit(fileInfo, { summary: `New File ID: ${file.id}`, id: file.id, ts: createdTime, }); maxCreatedTime = Math.max(createdTime, maxCreatedTime); this._setLastFileCreatedTime(maxCreatedTime); } }, }, }; <|start_filename|>components/slack/actions/delete_reminder/delete-reminder.js<|end_filename|> const slack = require("../../slack.app.js"); module.exports = { key: "slack-delete-reminder", name: "Delete Reminder", description: "Delete a reminder", version: "0.0.1", type: "action", props: { slack, reminder: { propDefinition: [ slack, "reminder", ], }, }, async run() { return await this.slack.sdk().reminders.delete({ reminder: this.reminder, }); }, }; <|start_filename|>components/pipefy/sources/common-polling.js<|end_filename|> const common = require("./common.js"); module.exports = { ...common, props: { ...common.props, timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 15, }, }, }, async run(event) { const cards = await this.pipefy.listCards(this.pipeId); for (const edge of cards.edges) { const { node } = edge; if (!this.isCardRelevant({ node, event })) continue; const meta = this.getMeta({ node, event }); this.$emit(node, meta); } }, }; <|start_filename|>components/twitch/actions/block-user/block-user.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, name: "Block User", key: "twitch-block-user", description: "Blocks a user; that is, adds a specified target user to your blocks list", version: "0.0.1", type: "action", props: { ...common.props, user: { propDefinition: [ common.props.twitch, "user", ], description: "User ID of the user to be blocked", }, sourceContext: { type: "string", label: "Source Context", description: "Source context for blocking the user. Valid values: \"chat\", \"whisper\".", optional: true, options: [ "chat", "whisper", ], }, reason: { type: "string", label: "Reason", description: "Reason for blocking the user. Valid values: \"spam\", \"harassment\", or \"other\".", optional: true, options: [ "spam", "harassment", "other", ], }, }, async run() { const params = { target_user_id: this.user, source_context: this.sourceContext, reason: this.reason, }; const { status, statusText, } = await this.twitch.blockUser(params); return status == 204 ? "User Blocked Successfully" : `${status} ${statusText}`; }, }; <|start_filename|>components/hubspot/sources/new-email-event/new-email-event.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, key: "hubspot-new-email-event", name: "New Email Event", description: "Emits an event for each new Hubspot email event.", version: "0.0.2", dedupe: "unique", hooks: {}, methods: { ...common.methods, generateMeta(emailEvent) { const { id, recipient, type, created } = emailEvent; const ts = Date.parse(created); return { id, summary: `${recipient} - ${type}`, ts, }; }, }, async run(event) { const startTimestamp = this._getAfter(); const params = { limit: 100, startTimestamp, }; await this.paginateUsingHasMore( params, this.hubspot.getEmailEvents.bind(this), "events" ); }, }; <|start_filename|>components/mailgun/mailgun.app.js<|end_filename|> const axios = require("axios"); const formData = require("form-data"); const Mailgun = require("mailgun.js"); module.exports = { type: "app", app: "mailgun", methods: { api (api) { const mailgun = new Mailgun(formData); const mg = mailgun.client({ username: "api", key: this.$auth.api_key, public_key: this.$auth.api_key, }); return mg[api]; }, async suppress (domain, type, suppression) { const res = await axios({ url: `https://api.mailgun.net/v3/${encodeURIComponent(domain)}/${encodeURIComponent(type)}`, method: "POST", auth: { username: "api", password: <PASSWORD>, }, headers: { "content-type": "application/json", }, // eslint-disable-next-line multiline-ternary, array-bracket-newline data: JSON.stringify(Array.isArray(suppression) ? suppression : [suppression]), }); return res.data; }, }, propDefinitions: { domain: { type: "string", label: "Domain Name", async options ({ page }) { const query = { limit: 50, skip: 50 * page, }; const domains = await this.api("domains").list(query); return domains.map(domain => domain.name); }, }, email: { type: "string", label: "Email Address", }, haltOnError: { type: "boolean", label: "Halt on error?", default: true, }, }, }; <|start_filename|>components/pipefy/sources/card-late/card-late.js<|end_filename|> const common = require("../common-polling.js"); module.exports = { ...common, name: "Card Late", key: "pipefy-card-late", description: "Emits an event each time a card becomes late in a Pipe.", version: "0.0.1", methods: { isCardRelevant({ node }) { return ( node.late && !node.done ); }, getMeta({ node, event }) { const { id: nodeId, title: summary, current_phase: { id: currentPhaseId }, } = node; const id = `${nodeId}${currentPhaseId}`; const { timestamp: ts } = event; return { id, summary, ts, }; }, }, }; <|start_filename|>components/twist/twist.app.js<|end_filename|> const events = require("./event-types.js"); const axios = require("axios"); module.exports = { type: "app", app: "twist", propDefinitions: { workspace: { type: "string", label: "Workspace", description: "The workspace to watch for new events.", optional: true, async options() { const workspaces = await this.getWorkspaces(); return workspaces.map((workspace) => { return { label: workspace.name, value: workspace.id, }; }); }, }, channel: { type: "string", label: "Channel", description: "The channel to watch for new events.", optional: true, async options(opts) { if (!opts.workspace) return [{ label: "No Channels Found", value: "none" }]; const channels = await this.getChannels(opts.workspace); return channels.map((channel) => { return { label: channel.name, value: channel.id, }; }); }, }, thread: { type: "string", label: "Thread", description: "The thread to watch for new events.", optional: true, async options(opts) { if (!opts.channel) return [{ label: "No Threads Found", value: "none" }]; const threads = await this.getThreads(opts.channel); return threads.map((thread) => { return { label: thread.title, value: thread.id, }; }); }, }, conversation: { type: "string", label: "Conversation", description: "The conversation to watch for new messages.", optional: true, async options(opts) { if (!opts.workspace) return [{ label: "No Conversations Found", value: "none" }]; const conversations = await this.getConversations(opts.workspace); return conversations.map((conversation) => { return { label: conversation.title || `Conversation ID ${conversation.id}`, value: conversation.id, }; }); }, }, eventType: { type: "string", label: "Event Type", description: "Watch for the selected event type.", options: events, }, }, methods: { async _getBaseUrl() { return "https://api.twist.com/api/v3"; }, async _getHeaders() { return { Accept: "application/json", Authorization: `Bearer ${this.$auth.oauth_access_token}`, }; }, async _makePostRequest(endpoint, data = null) { config = { method: "POST", url: `${await this._getBaseUrl()}/${endpoint}`, headers: await this._getHeaders(), data, }; return (await axios(config)).data; }, async _makeGetRequest(endpoint, params = null) { config = { method: "GET", url: `${await this._getBaseUrl()}/${endpoint}`, headers: await this._getHeaders(), params, }; return (await axios(config)).data; }, async createHook(data) { return await this._makePostRequest("hooks/subscribe", data); }, async deleteHook(target_url) { return await this._makePostRequest("hooks/unsubscribe", { target_url }); }, async getWorkspaces() { return await this._makeGetRequest("workspaces/get"); }, async getChannels(workspace_id) { return await this._makeGetRequest("channels/get", { workspace_id }); }, async getThreads(channel_id) { return await this._makeGetRequest("threads/get", { channel_id }); }, async getConversations(workspace_id) { return await this._makeGetRequest("conversations/get", { workspace_id }); }, }, }; <|start_filename|>components/ongage/actions/update-subscriber/update-subscriber.js<|end_filename|> const ongage = require("../../ongage.app.js"); module.exports = { key: "ongage-update-subscriber", name: "Ongage Update Subscriber", description: "Update a list subscriber in Ongage.", version: "0.0.1", type: "action", props: { ongage, listId: { propDefinition: [ ongage, "listId", ], optional: true, }, email: { propDefinition: [ ongage, "email", ], }, fields: { propDefinition: [ ongage, "fields", ], optional: true, }, haltOnError: { propDefinition: [ ongage, "haltOnError", ], }, }, async run () { try { return await this.ongage.updateSubscriber( this.listId, this.email, this.fields, ); } catch (err) { if (this.haltOnError) { throw err; } if (err.response) { return err.response.data; } return err; } }, }; <|start_filename|>components/slack/actions/set-channel-topic/set-channel-topic.js<|end_filename|> const slack = require("../../slack.app.js"); module.exports = { key: "slack-set-channel-topic", name: "Set Channel Topic", description: "Set the topic on a selected channel", version: "0.0.1", type: "action", props: { slack, conversation: { propDefinition: [ slack, "conversation", ], }, topic: { propDefinition: [ slack, "topic", ], }, }, async run() { return await this.slack.sdk().conversations.setTopic({ channel: this.conversation, topic: this.topic, }); }, }; <|start_filename|>components/slack/actions/create-reminder/create-reminder.js<|end_filename|> const slack = require("../../slack.app.js"); module.exports = { key: "slack-create-reminder", name: "Create Reminder", description: "Create a reminder", version: "0.0.1", type: "action", props: { slack, text: { propDefinition: [ slack, "text", ], }, timestamp: { propDefinition: [ slack, "timestamp", ], description: "When this reminder should happen: the Unix timestamp (up to five years from now), the number of seconds until the reminder (if within 24 hours), or a natural language description (Ex. in 15 minutes, or every Thursday)", }, team_id: { propDefinition: [ slack, "team_id", ], optional: true, }, user: { propDefinition: [ slack, "user", ], optional: true, }, }, async run() { return await this.slack.sdk().reminders.add({ text: this.text, team_id: this.team_id, time: this.timestamp, user: this.user, }); }, }; <|start_filename|>components/twilio/sources/new-transcription/new-transcription.js<|end_filename|> const common = require("../common-polling.js"); module.exports = { ...common, key: "twilio-new-transcription", name: "New Transcription", description: "Emits an event when a new call transcription is created", version: "0.0.1", dedupe: "unique", methods: { ...common.methods, async listResults(...args) { return await this.twilio.listTranscriptions(...args); }, generateMeta(transcription) { const { sid: id, dateCreated } = transcription; return { id, summary: `New transcription ${id}`, ts: Date.parse(dateCreated), }; }, }, }; <|start_filename|>components/slack/actions/get-file/get-file.js<|end_filename|> const slack = require("../../slack.app.js"); module.exports = { key: "slack-get-file", name: "Get File", description: "Return information about a file", version: "0.0.1", type: "action", props: { slack, file: { propDefinition: [ slack, "file", ], }, count: { propDefinition: [ slack, "count", ], }, }, async run() { return await this.slack.sdk().files.info({ file: this.file, count: this.count, }); }, }; <|start_filename|>components/airtable/actions/create-multiple-records/create-multiple-records.js<|end_filename|> const chunk = require("lodash.chunk"); const airtable = require("../../airtable.app.js"); const common = require("../common.js"); const BATCH_SIZE = 10; // The Airtable API allows us to update up to 10 rows per request. module.exports = { key: "airtable-create-multiple-records", name: "Create Multiple Records", description: "Create one or more records in a table by passing an array of objects containing field names and values as key/value pairs.", version: "0.1.1", type: "action", props: { ...common.props, records: { propDefinition: [ airtable, "records", ], }, typecast: { propDefinition: [ airtable, "typecast", ], }, }, async run() { const table = this.airtable.base(this.baseId)(this.tableId); let data = this.records; if (!Array.isArray(data)) { data = JSON.parse(data); } data = data.map((fields) => ({ fields, })); if (!data.length) { throw new Error("No Airtable record data passed to step. Please pass at least one record"); } const params = { typecast: this.typecast, }; const responses = []; for (const c of chunk(data, BATCH_SIZE)) { try { responses.push(...(await table.create(c, params))); } catch (err) { this.airtable.throwFormattedError(err); } } return responses; }, }; <|start_filename|>components/cliniko/actions/get-patient/get-patient.js<|end_filename|> const cliniko = require("../../cliniko.app.js"); module.exports = { name: "Get Patient", key: "cliniko-get-patient", description: "Get the details of a patient by patient ID.", version: "0.0.1", type: "action", props: { cliniko, patientId: { propDefinition: [ cliniko, "patientId", ], }, }, async run() { return await this.cliniko.getPatient(this.patientId); }, }; <|start_filename|>components/slack/actions/list-files/list-files.js<|end_filename|> const slack = require("../../slack.app.js"); module.exports = { key: "slack-list-files", name: "List Files", description: "Return a list of files within a team", version: "0.0.29", type: "action", props: { slack, conversation: { propDefinition: [ slack, "conversation", ], }, count: { propDefinition: [ slack, "count", ], optional: true, }, team_id: { propDefinition: [ slack, "team_id", ], optional: true, }, user: { propDefinition: [ slack, "user", ], optional: true, }, }, async run() { return await this.slack.sdk().files.list({ channel: this.conversation, count: this.count, user: this.user, team_id: this.team_id, }); }, }; <|start_filename|>components/procore/procore.app.js<|end_filename|> const axios = require("axios"); const eventTypes = [ { label: "Create", value: "create" }, { label: "Update", value: "update" }, { label: "Delete", value: "delete" }, ]; const resourceNames = [ "Budget View Snapshots", "Change Events", "Change Order Packages", "Projects", "Prime Contracts", "Purchase Order Contracts", "RFIs", "Submittals", ]; module.exports = { type: "app", app: "procore", propDefinitions: { company: { type: "integer", label: "Company", description: "Select the company to watch for changes in.", async options({ page, prevContext }) { const limit = 100; const { offset = 0 } = prevContext; const results = await this.listCompanies(limit, offset); const options = results.map((c) => ({ label: c.name, value: c.id, })); return { options, context: { limit, offset: offset + limit }, }; }, }, project: { type: "integer", label: "Project", description: "Select the project to watch for changes in. Leave blank for company-level resources (eg. Projects).", optional: true, async options({ page, prevContext, company }) { const limit = 100; const { offset = 0 } = prevContext; const results = await this.listProjects(company, limit, offset); const options = results.map((p) => ({ label: p.name, value: p.id, })); return { options, context: { limit, offset: offset + limit, company }, }; }, }, resourceName: { type: "string", label: "Resource", description: "The type of resource on which to trigger events.", options: resourceNames, }, eventTypes: { type: "string[]", label: "Event Type", description: "Only events of the selected event type will be emitted.", options: eventTypes, }, }, methods: { getEventTypes() { return eventTypes.map(({ value }) => value); }, _getBaseUrl() { return "https://api.procore.com/rest/v1.0"; }, _getHeaders(companyId = null) { let headers = { Authorization: `Bearer ${this.$auth.oauth_access_token}`, }; if (companyId) headers["Procore-Company-Id"] = companyId; return headers; }, async _makeRequest( method, endpoint, companyId = null, params = null, data = null ) { const config = { method, url: `${this._getBaseUrl()}/${endpoint}`, headers: this._getHeaders(companyId), }; if (params) config.params = params; else if (data) config.data = data; return (await axios(config)).data; }, async createHook(destinationUrl, companyId, projectId) { const data = { hook: { api_version: "v1.0", destination_url: destinationUrl, }, }; if (projectId) data.project_id = projectId; else if (companyId) data.company_id = companyId; return await this._makeRequest( "POST", "webhooks/hooks", companyId, null, data ); }, async createHookTrigger( hookId, companyId, projectId, resourceName, eventType ) { const data = { api_version: "v1.0", trigger: { resource_name: resourceName, event_type: eventType, }, }; if (projectId) data.project_id = projectId; else if (companyId) data.company_id = companyId; return await this._makeRequest( "POST", `webhooks/hooks/${hookId}/triggers`, companyId, null, data ); }, async deleteHook(id, companyId, projectId) { const params = projectId ? { project_id: projectId } : { company_id: companyId }; return await this._makeRequest( "DELETE", `webhooks/hooks/${id}`, companyId, params ); }, async deleteHookTrigger(hookId, triggerId, companyId, projectId) { const params = projectId ? { project_id: projectId } : { company_id: companyId }; return await this._makeRequest( "DELETE", `webhooks/hooks/${hookId}/triggers/${triggerId}`, companyId, params ); }, async listCompanies(perPage, page) { return await this._makeRequest("GET", "companies", null, { per_page: perPage, page, }); }, async listProjects(companyId, perPage, page) { return await this._makeRequest("GET", "projects", companyId, { company_id: companyId, per_page: perPage, page, }); }, async getBudgetViewSnapshot( companyId, projectId, budgetViewSnapshotId, perPage, page ) { return await this._makeRequest( "GET", `budget_view_snapshots/${budgetViewSnapshotId}/detail_rows`, companyId, { project_id: projectId, per_page: perPage, page } ); }, async getChangeEvent(companyId, projectId, changeEventId) { return await this._makeRequest( "GET", `change_events/${changeEventId}`, companyId, { project_id: projectId } ); }, async getChangeOrderPackage(companyId, projectId, changeOrderPackageId) { return await this._makeRequest( "GET", `change_order_packages/${changeOrderPackageId}`, companyId, { project_id: projectId } ); }, async getPrimeContract(companyId, projectId, primeContractId) { return await this._makeRequest( "GET", `prime_contract/${primeContractId}`, companyId, { project_id: projectId } ); }, async getPurchaseOrder(companyId, projectId, poId) { return await this._makeRequest( "GET", `purchase_order_contracts/${poId}`, companyId, { project_id: projectId } ); }, async getRFI(companyId, projectId, rfiId) { return await this._makeRequest( "GET", `projects/${projectId}/rfis/${rfiId}`, companyId ); }, async getSubmittal(companyId, projectId, submittalId) { return await this._makeRequest( "GET", `projects/${projectId}/submittals/${submittalId}`, companyId ); }, }, }; <|start_filename|>components/threads/threads.app.js<|end_filename|> // See API docs here: // https://gist.github.com/gauravmk/c9263120b9309c24d6f14df6668e5326 const axios = require("axios"); module.exports = { type: "app", app: "threads", propDefinitions: { forumID: { type: "integer", label: "Forum ID", description: "The ID of the forum you want to post to. Navigate to your forum on the Threads website. The URL will be threads.com/${forum_id}", }, title: { type: "string", label: "Thread Title", description: "The title of your thread (max 60 characters)", }, body: { type: "string", label: "Thread Body", description: "The body of your thread. Supports Markdown", }, threadID: { type: "string", label: "Thread ID", description: "Navigate to your thread on the Threads website. The URL will be threads.com/${thread_id}", }, }, methods: { _apiUrl() { return "https://threads.com/api/public"; }, _apiKey() { return this.$auth.api_key; }, async _makeRequest(opts) { if (!opts.headers) opts.headers = {}; opts.headers["Content-Type"] = "application/json"; opts.headers["Authorization"] = `Bearer ${this._apiKey()}`; opts.headers["user-agent"] = "@PipedreamHQ/pipedream v0.1"; const { path } = opts; delete opts.path; opts.url = `${this._apiUrl()}${path[0] === "/" ? "" : "/"}${path}`; const { status, data, } = await axios({ ...opts, validateStatus: () => true, }); if (status >= 400) { throw new Error(JSON.stringify(data, null, 2)); } return data; }, async postThread({ forumID, title, body, }) { return await this._makeRequest({ path: "/postThread", method: "POST", data: { forumID, title, body, }, }); }, async deleteThread({ threadID }) { return await this._makeRequest({ path: "/deleteThread", method: "POST", data: { threadID, }, }); }, }, }; <|start_filename|>components/twitter/sources/common/followers.js<|end_filename|> const twitter = require("../../twitter.app"); module.exports = { props: { db: "$.service.db", twitter, timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 15, }, }, }, hooks: { async activate() { await this._provisionFollowersCache(); }, }, deactivate() { this._clearFollowersCache(); }, methods: { /** * This method returns the size of the internal cache used by the event * source to keep track of the latest Twitter followers of the corresponding * account. * * The size represents the maximum amount of entries/ID's that will be * cached at any given time (or 0 for unlimited). Keep in mind that the * Pipedream platform itself imposes size limits as well in terms of DB * usage. * * @returns The maximum amount of Twitter followers entries to be cached at * any given moment (or 0 for unlimited). */ getFollowersCacheSize() { return 0; }, getScreenName() { // When screen name is not explicitly provided, the Twitter API defaults // it to the user making the API request return undefined; }, /** * This function provides the list of relevant, follower-related, user ID's * that are used by the event source to emit events. How each event source * that implements it depends on the purpose of the event source itself. For * example, an event source that emits an event for every new follower will * implement this function in such a way that its result is a list of user * ID's for each new follower detected. * * @returns the list of relevant user ID's for this event source to process */ getRelevantIds() { return []; }, generateMeta(data) { const { timestamp, user, } = data; const { id_str: id, screen_name: summary, } = user; // Event timestamp is expressed in seconds, whereas Javascript timestamps // are expressed in milliseconds const ts = timestamp * 1000; return { id, summary, ts, }; }, _clearFollowersCache() { this.setFollowersCache([]); }, async _provisionFollowersCache() { const screenName = this.getScreenName(); const followerIdsGen = this.twitter.scanFollowerIds(screenName); const maxFollowerListSize = Math.max(this.getFollowersCacheSize(), 0); const result = []; for await (const id of followerIdsGen) { if (maxFollowerListSize !== 0 && maxFollowerListSize === result.length) { break; } result.push(id); } this.setFollowersCache(result); return result; }, getFollowersCache() { return this.db.get("followers"); }, setFollowersCache(followers) { const followersCacheSize = Math.max(this.getFollowersCacheSize(), 0); const trimmedFollowers = followersCacheSize !== 0 ? followers.slice(0, followersCacheSize) : followers; this.db.set("followers", trimmedFollowers); console.log(` Updated followers cache: ${trimmedFollowers.length} records `); }, /** * This generator method scans the list of Twitter followers until it finds * the ID of a follower that was already processed. * * @param {string[]} processedFollowerIds a list of the ID's of the most * recent Twitter followers processed by the event source * @yields the ID of a new Twitter follower */ async *scanNewFollowers(processedFollowerIds = []) { const processeedFollowerIdsSet = new Set(processedFollowerIds); const screenName = this.getScreenName(); const followerIdsGen = this.twitter.scanFollowerIds(screenName); for await (const id of followerIdsGen) { if (processeedFollowerIdsSet.has(id)) { break; } yield id; } }, async getUnfollowers() { const prevFollowers = this.getFollowersCache(); const currFollowers = await this._provisionFollowersCache(); const currFollowersSet = new Set(currFollowers); return prevFollowers.filter(pf => !currFollowersSet.has(pf)); }, }, async run(event) { const { timestamp } = event; const relevantIds = await this.getRelevantIds(); if (relevantIds.length <= 0) { console.log(` No changes in followers data for this event source to emit a new event `); return; } const users = await this.twitter.lookupUsers(relevantIds); users.forEach(user => { const data = { timestamp, user, }; user.profile_url = `https://twitter.com/${user.screen_name}/` const meta = this.generateMeta(data); this.$emit(user, meta); }); }, }; <|start_filename|>components/twitch/actions/delete-video/delete-video.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, name: "Delete Video", key: "twitch-delete-video", description: "Deletes a specified video", version: "0.0.1", type: "action", props: { ...common.props, id: { type: "string", label: "Video ID", description: "ID of the video to be deleted", optional: true, }, }, async run() { const params = { id: this.id, }; return (await this.twitch.deleteVideo(params)).data.data; }, }; <|start_filename|>components/slack/actions/update-profile/update-profile.js<|end_filename|> const slack = require("../../slack.app.js"); module.exports = { key: "slack-update-profile", name: "Update Profile", description: "Update basic profile field such as name or title", version: "0.0.1", type: "action", props: { slack, name: { propDefinition: [ slack, "name", ], }, value: { propDefinition: [ slack, "value", ], }, }, async run() { return await this.slack.sdk().users.profile.set({ name: this.name, value: this.value, }); }, }; <|start_filename|>components/calendly/sources/new-event/new-event.js<|end_filename|> const common = require("../common-polling.js"); const get = require("lodash/get"); module.exports = { ...common, key: "calendly-new-event", name: "New Event", description: "Emits an event for each new event created", version: "0.0.2", dedupe: "unique", methods: { ...common.methods, async getResults() { return await this.calendly.getEvents(); }, isRelevant(event, lastEvent) { const createdAt = this.getCreatedAt(event); return createdAt > lastEvent; }, generateMeta(event) { const { id } = event; const createdAt = this.getCreatedAt(event); const startTime = new Date(get(event, "attributes.start_time")); return { id, summary: `New Event at ${startTime.toLocaleString()}`, ts: Date.parse(createdAt), }; }, getCreatedAt(event) { return Date.parse(get(event, "attributes.created_at")); }, }, }; <|start_filename|>components/activecampaign/sources/campaign-opened/campaign-opened.js<|end_filename|> const activecampaign = require("../../activecampaign.app.js"); const common = require("../common-campaign.js"); module.exports = { ...common, name: "Campaign Opened (Instant)", key: "activecampaign-campaign-opened", description: "Emits an event when a contact opens a campaign (will trigger once per contact per campaign).", version: "0.0.1", methods: { ...common.methods, getEvents() { return ["open"]; }, }, }; <|start_filename|>components/activecampaign/activecampaign.app.js<|end_filename|> const axios = require("axios"); const { humanize } = require("inflection"); module.exports = { type: "app", app: "activecampaign", propDefinitions: { eventType: { type: "string", label: "Event Type", description: "Emit events for the selected event type. See the official docs for more information on event types. https://developers.activecampaign.com/page/webhooks", async options({ page }) { if (page !== 0) { return []; } const results = await this.listWebhookEvents(); return results.webhookEvents.map((e) => ({ label: humanize(e), value: e, })); }, }, sources: { type: "string[]", label: "Sources", description: "The sources causing an event to occur. Leave blank to include all sources.", optional: true, default: [], options() { return this.getAllSources(); }, }, automations: { type: "string[]", label: "Automations", description: "Emit events for the selected webhooks only. Leave blank to watch all available webhooks.", optional: true, default: [], async options({ prevContext }) { const { results, context } = await this._getNextOptions( this.listAutomations.bind(this), prevContext ); const options = results.automations.map((a) => ({ label: a.name, value: a.id, })); return { options, context, }; }, }, campaigns: { type: "string[]", label: "Campaigns", description: "Watch the selected campaigns for updates. Leave blank to watch all available campaigns.", optional: true, default: [], async options({ prevContext }) { const { results, context } = await this._getNextOptions( this.listCampaigns.bind(this), prevContext ); const options = results.campaigns.map((c) => ({ label: c.name, value: c.id, })); return { options, context, }; }, }, contacts: { type: "string[]", label: "Contacts", description: "Watch the selected contacts for updates. Leave blank to watch all available contacts.", optional: true, default: [], async options({ prevContext }) { const { results, context } = await this._getNextOptions( this.listContacts.bind(this), prevContext ); const options = results.contacts.map((c) => ({ label: c.email, value: c.id, })); return { options, context, }; }, }, deals: { type: "string[]", label: "Deals", description: "Watch the selected deals for updates. Leave blank to watch all available deals.", optional: true, default: [], async options({ prevContext }) { const { results, context } = await this._getNextOptions( this.listDeals.bind(this), prevContext ); const options = results.deals.map((d) => ({ label: d.title, value: d.id, })); return { options, context, }; }, }, lists: { type: "string[]", label: "Lists", description: "Watch the selected lists for updates. Leave blank to watch all available lists.", optional: true, default: [], async options({ prevContext }) { const { results, context } = await this._getNextOptions( this.listLists.bind(this), prevContext ); const options = results.lists.map((d) => ({ label: d.name, value: d.id, })); return { options, context, }; }, }, }, methods: { _getHeaders() { return { "Api-Token": this.$auth.api_key }; }, async createHook(events, url, sources, listid = null) { const componentId = process.env.PD_COMPONENT; const webhookName = `Pipedream Hook (${componentId})`; const config = { method: "POST", url: `${this.$auth.base_url}/api/3/webhooks`, headers: this._getHeaders(), data: { webhook: { name: webhookName, url, events, sources, listid, }, }, }; return (await axios(config)).data; }, async deleteHook(hookId) { const config = { method: "DELETE", url: `${this.$auth.base_url}/api/3/webhooks/${hookId}`, headers: this._getHeaders(), }; await axios(config); }, async _makeGetRequest( endpoint, limit = null, offset = null, params = {}, url = null ) { const config = { method: "GET", url: url || `${this.$auth.base_url}/api/3/${endpoint}`, headers: this._getHeaders(), params, }; if (limit) config.params.limit = limit; if (offset) config.params.offset = offset; return await axios(config); }, async _getNextOptions(optionsFn, prevContext) { const limit = 100; const { offset = 0 } = prevContext; const results = await optionsFn(limit, offset); const context = { offset: offset + limit, }; return { results, context, }; }, getAllSources() { return ["public", "admin", "api", "system"]; }, async getList(id) { return (await this._makeGetRequest(`lists/${id}`)).data; }, async listAutomations(limit, offset) { return (await this._makeGetRequest("automations", limit, offset)).data; }, async listCampaigns(limit, offset) { return (await this._makeGetRequest("campaigns", limit, offset)).data; }, async listContacts(limit, offset) { return (await this._makeGetRequest("contacts", limit, offset)).data; }, async listDeals(limit, offset) { return (await this._makeGetRequest("deals", limit, offset)).data; }, async listLists(limit, offset) { return (await this._makeGetRequest("lists", limit, offset)).data; }, async listWebhookEvents() { return (await this._makeGetRequest("webhook/events")).data; }, }, }; <|start_filename|>components/ringcentral/sources/new-inbound-message/new-inbound-message.js<|end_filename|> const common = require("../common/http-based"); const messageTypes = require("../common/message-types"); module.exports = { ...common, key: "ringcentral-new-inbound-message-event", name: "New Inbound Message Event (Instant)", description: "Emits an event for each status change of inbound messages of a specific type", version: "0.0.1", props: { ...common.props, extensionId: { propDefinition: [common.props.ringcentral, "extensionId"] }, messageType: { type: "string", label: "Message Type", description: "The type of message to monitor for status changes", options({ page = 0}) { return page === 0 ? messageTypes : []; }, }, }, methods: { ...common.methods, getSupportedNotificationTypes() { return new Set([ "message-event-inbound", ]); }, generateMeta(data) { const { timestamp, uuid: id, } = data; const summary = "New inbound message event"; const ts = Date.parse(timestamp); return { id, summary, ts, }; }, }, }; <|start_filename|>components/todoist/sources/common.js<|end_filename|> const todoist = require("../todoist.app.js"); module.exports = { props: { todoist, timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 5, }, }, db: "$.service.db", }, methods: { generateMeta(element) { const { id: elementId, summary, date_completed: dateCompleted, } = element; const ts = new Date(dateCompleted).getTime(); const id = `${elementId}-${ts}`; return { id, summary, ts, }; }, }, }; <|start_filename|>components/yotpo/yotpo.app.js<|end_filename|> const axios = require("axios") const _get = require("lodash.get") module.exports = { type: "app", app: "yotpo", methods: { api() { return { core: axios.create({ baseURL: `https://api.yotpo.com`, headers: { Authorization: `Bearer ${this.$auth.oauth_access_token}`, Accept: "application/json", }, }), dev: axios.create({ baseURL: `https://developers.yotpo.com/v2/${this.$auth.app_key}`, params: { access_token: this.$auth.oauth_access_token, }, }), } }, async createWebhook(event_name = "review_create", url) { const api = this.api().dev const webhook = _get(await api.get("/webhooks"), "data.webhooks.webhooks", []).find(w => w.webhook_event_name == event_name) if(webhook) { if (webhook.url != url) { console.error("Cannot setup Yotpo webhook. An existing webhook of this type already exists", webhook) } else { console.log("Existing webhook found:", webhook) } } else { const response = await api.post("/webhooks", { event_name, url }) console.log("Webhook created:", { event_name, url }, _get(response, "data", "No response when creating webhook")) } }, async deleteWebhook(event_name = "review_create", url) { const api = this.api().dev const webhook = _get(await api.get("/webhooks"), "data.webhooks.webhooks", []).find(w => w.webhook_event_name == event_name) if (webhook && webhook.id) { if (webhook.url == url) { const response = await api.delete(`/webhooks/${webhook.id}`) console.log("Webhook deleted", webhook, _get(response, "data", "No response when deleting webhook")) } else { console.error("Cannot delete webhook - existing webhook does not match this endpoint:", {event_name, url}, webhook) } } else { console.error("Cannot delete webhook - not found:", {event_name, url}) } }, }, } <|start_filename|>components/intercom/sources/new-unsubscription/new-unsubscription.js<|end_filename|> const intercom = require("../../intercom.app.js"); module.exports = { key: "intercom-new-unsubscription", name: "New Unsubscriptions", description: "Emits an event each time a user unsubscribes from receiving emails.", version: "0.0.1", dedupe: "unique", props: { intercom, db: "$.service.db", timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 15, }, }, }, async run(event) { const data = { query: { operator: "AND", value: [ { field: "unsubscribed_from_emails", operator: "=", value: true, }, { field: "role", operator: "=", value: "user", }, ], }, }; const results = await this.intercom.searchContacts(data); for (const user of results) { this.$emit(user, { id: user.id, summary: user.name, ts: Date.now(), }); } }, }; <|start_filename|>components/bandwidth/package.json<|end_filename|> { "name": "@pipedream/bandwidth", "version": "1.0.0", "description": "Pipedream Bandwidth Components", "main": "index.js", "keywords": [ "pipedream", "bandwidth" ], "author": "Bandwidth", "license": "MIT", "dependencies": { "@bandwidth/messaging": "^4.0.0" } } <|start_filename|>components/microsoft_onedrive/sources/common/base.js<|end_filename|> const microsoft_onedrive = require("../../microsoft_onedrive.app"); const { MAX_INITIAL_EVENT_COUNT, WEBHOOK_SUBSCRIPTION_RENEWAL_SECONDS, } = require("./constants"); function toSingleLineString(multiLineString) { return multiLineString .trim() .replace(/\n/g, " ") .replace(/\s{2,}/g, ""); } module.exports = { props: { microsoft_onedrive, db: "$.service.db", http: { type: "$.interface.http", customResponse: true, }, timer: { label: "Webhook subscription renewal schedule", description: toSingleLineString(` The OneDrive API requires occasional renewal of webhook notification subscriptions. **This runs in the background, so you should not need to modify this schedule**. `), type: "$.interface.timer", default: { intervalSeconds: WEBHOOK_SUBSCRIPTION_RENEWAL_SECONDS, }, }, }, hooks: { async deploy() { const params = this.getDeltaLinkParams(); const deltaLink = this.microsoft_onedrive.getDeltaLink(params); const itemsStream = this.microsoft_onedrive.scanDeltaItems(deltaLink); // We skip the first drive item, since it represents the root directory await itemsStream.next(); let eventsToProcess = Math.max(MAX_INITIAL_EVENT_COUNT, 1); for await (const driveItem of itemsStream) { if (driveItem.deleted) { // We don't want to process items that were deleted from the drive // since they no longer exist continue; } await this.processEvent(driveItem); if (--eventsToProcess <= 0) { break; } } }, async activate() { await this._createNewSubscription(); const deltaLinkParams = this.getDeltaLinkParams(); const deltaLink = await this.microsoft_onedrive.getLatestDeltaLink(deltaLinkParams); this._setDeltaLink(deltaLink); }, async deactivate() { await this._deactivateSubscription(); }, }, methods: { _getNextExpirationDateTime() { const nowTimestamp = Date.now(); const expirationTimestampDelta = 2 * WEBHOOK_SUBSCRIPTION_RENEWAL_SECONDS * 1000; return new Date(nowTimestamp + expirationTimestampDelta); }, async _createNewSubscription() { const hookOpts = { expirationDateTime: this._getNextExpirationDateTime(), }; const hookId = await this.microsoft_onedrive.createHook(this.http.endpoint, hookOpts); this._setHookId(hookId); }, _renewSubscription() { const hookOpts = { expirationDateTime: this._getNextExpirationDateTime(), }; const hookId = this._getHookId(); return this.microsoft_onedrive.updateHook(hookId, hookOpts); }, async _deactivateSubscription() { const hookId = this._getHookId(); await this.microsoft_onedrive.deleteHook(hookId); this._setHookId(null); }, _getHookId() { return this.db.get("hookId"); }, _setHookId(hookId) { this.db.set("hookId", hookId); }, _getDeltaLink() { return this.db.get("deltaLink"); }, _setDeltaLink(deltaLink) { this.db.set("deltaLink", deltaLink); }, _validateSubscription(validationToken) { // See the docs for more information on how webhooks are validated upon // creation: https://bit.ly/3fzc3Tr const headers = { "Content-Type": "text/plain", }; this.http.respond({ // OK status: 200, headers, body: validationToken, }); }, async _processEventsFromDeltaLink(deltaLink) { const itemsStream = this.microsoft_onedrive.scanDeltaItems(deltaLink); while (true) { // We iterate through the `itemsStream` generator using explicit calls to // `next()` since the last/returned value is also useful because it // contains the latest Delta Link (using a `for...of` loop will discard // such value). const { done, value, } = await itemsStream.next(); if (done) { // No more items to retrieve from OneDrive. We update the cached Delta // Link and move on. this._setDeltaLink(value); break; } if (!this.isItemRelevant(value)) { // If the retrieved item is not relevant to the event source, we skip it continue; } await this.processEvent(value); } await this.postProcessEvent(); }, /** * The purpose of this method is for the different OneDrive event sources to * parameterize the OneDrive Delta Link to use. These parameters will be * forwarded to the `microsoft_onedrive.getLatestDeltaLink` method. * * @returns an object containing options/parameters to use when querying the * OneDrive API for a Delta Link */ getDeltaLinkParams() { return {}; }, /** * This method determines whether an item that's about to be processed is * relevant to the event source or not. This is helpful when the event * source has to go through a collection of items, some of which should be * skipped/ignored. * * @param {Object} item the item under evaluation * @returns a boolean value that indicates whether the item should be * processed or not */ isItemRelevant() { throw new Error("isItemRelevant is not implemented"); }, /** * This method generates the metadata that accompanies an event being * emitted by the event source, as outlined [in the * docs](https://github.com/PipedreamHQ/pipedream/blob/master/COMPONENT-API.md#emit) * * @param {Object} data the event data to consider in order to build the * metadata object * @returns an event metadata object containing, as described in the docs */ generateMeta() { throw new Error("generateMeta is not implemented"); }, /** * This method emits an event which payload is set to the provided [OneDrive * item](https://bit.ly/39T7mQz). The functionality provided by this method * is very basic and complex event sources probably need to override it. * * @param {Object} driveItem a OneDrive item object */ processEvent(driveItem) { const meta = this.generateMeta(driveItem); this.$emit(driveItem, meta); }, /** * This method is executed after processing all the items/events in a * particular execution. A normal use case for it is to store/cache some * final value that should be picked up by the next execution (e.g. an event * timestamp, the ID of the last processed item, etc.). */ postProcessEvent() {}, }, async run(event) { // The very first HTTP call that the event source receives is from the // OneDrive API to verify the webhook subscription. The response for such // call should be as fast as possible in order for the subscription to be // confirmed and activated. const { query: { validationToken } = {} } = event; if (validationToken) { this._validateSubscription(validationToken); console.log(` Received an HTTP call containing 'validationToken'. Validating webhook subscription and exiting... `); return; } if (event.interval_seconds || event.cron) { // Component was invoked by timer. When that happens, it means that it's // time to renew the webhook subscription, not that there are changes in // OneDrive to process. return this._renewSubscription(); } // Every HTTP call made by a OneDrive webhook expects a '202 Accepted` // response, and it should be done as soon as possible. this.http.respond({ status: 202, }); // Using the last known Delta Link, we retrieve and process the items that // changed after such Delta Link was obtained const deltaLink = this._getDeltaLink(); await this._processEventsFromDeltaLink(deltaLink); }, }; <|start_filename|>components/twilio/sources/common-webhook.js<|end_filename|> const twilio = require("../twilio.app.js"); const twilioClient = require("twilio"); module.exports = { props: { twilio, incomingPhoneNumber: { propDefinition: [twilio, "incomingPhoneNumber"] }, authToken: { propDefinition: [twilio, "authToken"] }, http: { type: "$.interface.http", customResponse: true, }, }, hooks: { async activate() { const createWebhookResp = await this.setWebhook( this.incomingPhoneNumber, this.http.endpoint ); console.log(createWebhookResp); }, async deactivate() { const deleteWebhookResp = await this.setWebhook( this.incomingPhoneNumber, "" // remove the webhook URL ); console.log(deleteWebhookResp); }, }, methods: { getResponseBody() { return null; }, isRelevant(body) { return true; }, validateRequest(body, headers) { const twilioSignature = headers["x-twilio-signature"]; if (!twilioSignature) { console.log("No x-twilio-signature header in request. Exiting."); return false; } /** See https://www.twilio.com/docs/usage/webhooks/webhooks-security */ return twilioClient.validateRequest( this.authToken, twilioSignature, /** This must match the incoming URL exactly, which contains a / */ `${this.http.endpoint}/`, body ); }, emitEvent(body, headers) { const meta = this.generateMeta(body, headers); this.$emit(body, meta); }, }, async run(event) { let { body, headers } = event; const responseBody = this.getResponseBody(); if (responseBody) { this.http.respond({ status: 200, headers: { "Content-Type": "text/xml" }, body: responseBody, }); } if (typeof body !== "object") body = Object.fromEntries(new URLSearchParams(body)); if (!this.isRelevant(body)) { console.log("Event not relevant. Skipping..."); return; } if (!this.validateRequest(body, headers)) { console.log("Event could not be validated. Skipping..."); return; } this.emitEvent(body, headers); }, }; <|start_filename|>components/google_docs/actions/append-text/append-text.js<|end_filename|> const googleDocs = require("../../google_docs.app"); module.exports = { key: "google_docs-append-text", name: "Append Text", description: "Append text to an existing document", version: "0.0.12", type: "action", props: { googleDocs, docId: { propDefinition: [ googleDocs, "docId", ], }, text: { type: "string", description: "Enter static text (e.g., `hello world`) or a reference to a string exported by a previous step (e.g., `{{steps.foo.$return_value}}`).", }, }, async run() { const docs = this.googleDocs.docs(); return (await docs.documents.batchUpdate({ documentId: this.docId, requestBody: { requests: [ { insertText: { location: { index: 1, }, text: this.text, }, }, ], }, })).data; }, }; <|start_filename|>components/webflow/sources/changed-ecomm-order/changed-ecomm-order.js<|end_filename|> const common = require("../common"); module.exports = { ...common, key: "webflow-changed-ecomm-order", name: "Changed E-commerce Order (Instant)", description: "Emit an event when an e-commerce order is changed", version: "0.0.1", methods: { ...common.methods, getWebhookTriggerType() { return "ecomm_order_changed"; }, generateMeta(data) { const { orderId } = data; const summary = `E-comm order changed: ${orderId}`; const ts = Date.now(); const id = `${orderId}-${ts}`; return { id, summary, ts, }; }, }, }; <|start_filename|>components/reddit/sources/new-hot-posts-on-a-subreddit/region-data.js<|end_filename|> module.exports = [ "GLOBAL", "US", "AR", "AU", "BG", "CA", "CL", "CO", "HR", "CZ", "FI", "FR", "DE", "GR", "HU", "IS", "IN", "IE", "IT", "JP", "MY", "MX", "NZ", "PH", "PL", "PT", "PR", "RO", "RS", "SG", "ES", "SE", "TW", "TH", "TR", "GB", "US_WA", "US_DE", "US_DC", "US_WI", "US_WV", "US_HI", "US_FL", "US_WY", "US_NH", "US_NJ", "US_NM", "US_TX", "US_LA", "US_NC", "US_ND", "US_NE", "US_TN", "US_NY", "US_PA", "US_CA", "US_NV", "US_VA", "US_CO", "US_AK", "US_AL", "US_AR", "US_VT", "US_IL", "US_GA", "US_IN", "US_IA", "US_OK", "US_AZ", "US_ID", "US_CT", "US_ME", "US_MD", "US_MA", "US_OH", "US_UT", "US_MO", "US_MN", "US_MI", "US_RI", "US_KS", "US_MT", "US_MS", "US_SC", "US_KY", "US_OR", "US_SD", ]; <|start_filename|>components/airtable/actions/common-list.js<|end_filename|> // Shared code for list-* actions const airtable = require("../airtable.app.js"); module.exports = { props: { sortFieldId: { propDefinition: [ airtable, "sortFieldId", ], }, sortDirection: { propDefinition: [ airtable, "sortDirection", ], }, maxRecords: { propDefinition: [ airtable, "maxRecords", ], }, filterByFormula: { propDefinition: [ airtable, "filterByFormula", ], }, }, async run() { const base = this.airtable.base(this.baseId); const data = []; const config = {}; if (this.viewId) { config.view = this.viewId; } if (this.filterByFormula) { config.filterByFormula = this.filterByFormula; } if (this.maxRecords) { config.maxRecords = this.maxRecords; } if (this.sortFieldId && this.sortDirection) { config.sort = [ { field: this.sortFieldId, direction: this.sortDirection, }, ]; } await base(this.tableId).select({ ...config, }) .eachPage(function page(records, fetchNextPage) { // This function (`page`) will get called for each page of records. records.forEach(function(record) { data.push(record._rawJson); }); // To fetch the next page of records, call `fetchNextPage`. // If there are more records, `page` will get called again. // If there are no more records, `done` will get called. fetchNextPage(); }); return data; }, }; <|start_filename|>components/activecampaign/sources/common-campaign.js<|end_filename|> const activecampaign = require("../activecampaign.app.js"); const common = require("./common-webhook.js"); module.exports = { ...common, props: { ...common.props, campaigns: { propDefinition: [activecampaign, "campaigns"] }, }, methods: { isRelevant(body) { return ( this.campaigns.length === 0 || this.campaigns.includes(body["campaign[id]"]) ); }, getMeta(body) { const { date_time: dateTimeIso } = body; const ts = Date.parse(dateTimeIso); return { id: `${body["campaign[id]"]}${body["contact[id]"]}`, summary: `${body["contact[email]"]}, Campaign: ${body["campaign[name]"]}`, ts }; }, }, }; <|start_filename|>components/jotform/jotform.app.js<|end_filename|> const axios = require("axios"); const querystring = require("querystring"); function ensureTrailingSlash(str) { if (str.endsWith("/")) return str; return `${str}/`; } module.exports = { type: "app", app: "jotform", propDefinitions: { formId: { type: "string", label: "Form", description: "The form to watch for new submissions", async options() { const forms = await this.getForms(this.$auth.api_key); return forms.content.map((form) => { return { label: form.title, value: form.id, }; }); }, }, }, methods: { _getBaseUrl() { return `https://${this.$auth.region}.jotform.com/`; }, async _makeRequest(config) { config.headers = { "APIKEY": this.$auth.api_key, }; if (config.params) { const query = querystring.stringify(config.params); delete config.params; const sep = config.url.indexOf("?") === -1 ? "?" : "&"; config.url += `${sep}${query}`; config.url = config.url.replace("?&", "?"); } return await axios(config); }, async getForms() { return (await this._makeRequest({ url: `${this._getBaseUrl()}user/forms`, method: "GET", })).data; }, async getWebhooks(opts = {}) { const { formId } = opts; return (await this._makeRequest({ url: `${this._getBaseUrl()}form/${encodeURIComponent(formId)}/webhooks`, method: "GET", })).data; }, async createHook(opts = {}) { const { formId, endpoint, } = opts; return (await this._makeRequest({ url: `${this._getBaseUrl()}form/${encodeURIComponent(formId)}/webhooks`, method: "POST", params: { webhookURL: ensureTrailingSlash(endpoint), }, })); }, async deleteHook(opts = {}) { const { formId, endpoint, } = opts; const result = await this.getWebhooks({ formId, }); let webhooks = Object.values(result && result.content || {}); let webhookIdx = -1; for (let idx in webhooks) { if (webhooks[idx] === ensureTrailingSlash(endpoint)) { webhookIdx = idx; } } if (webhookIdx === -1) { console.log(`Did not detect ${endpoint} as a webhook registered for form ID ${formId}.`); return; } console.log(`Deleting webhook at index ${webhookIdx}...`); return (await this._makeRequest({ url: `${this._getBaseUrl()}form/${encodeURIComponent(formId)}/webhooks/${encodeURIComponent(webhookIdx)}`, method: "DELETE", })); }, }, }; <|start_filename|>components/todoist/todoist.app.js<|end_filename|> const axios = require("axios"); const querystring = require("querystring"); const resourceTypes = require("./resource-types.js") module.exports = { type: "app", app: "todoist", propDefinitions: { includeResourceTypes: { type: "string[]", label: "Resource Types", description: "Select one or more resources to include", async options() { resourceTypes.unshift("all"); return resourceTypes; }, }, selectProjects: { type: "integer[]", label: "Select Projects", description: "Filter for events that match one or more projects. Leave this blank to emit results for any project.", optional: true, async options() { return (await this.getProjects()).map((project) => { return { label: project.name, value: project.id }; }); }, }, }, methods: { /** * Make a request to Todoist's sync API. * @params {Object} opts - An object representing the configuration options for this method * @params {String} opts.path [opts.path=/sync/v8/sync] - The path for the sync request * @params {String} opts.payload - The data to send in the API request at the POST body. This data will converted to `application/x-www-form-urlencoded` * @returns {Object} When the request succeeds, an HTTP 200 response will be returned with a JSON object containing the requested resources and also a new `sync_token`. */ async _makeSyncRequest(opts) { const { path = `/sync/v8/sync` } = opts; delete opts.path; opts.url = `https://api.todoist.com${path[0] === "/" ? "" : "/"}${path}`; opts.payload.token = this.$auth.oauth_access_token; opts.data = querystring.stringify(opts.payload); delete opts.payload; return await axios(opts); }, /** * Make a request to Todoist's REST API. * @params {Object} opts - An object representing the Axios configuration options for this method * @params {String} opts.path - The path for the REST API request * @returns {*} The response may vary depending the specific API request. */ async _makeRestRequest(opts) { const { path } = opts; delete opts.path; opts.url = `https://api.todoist.com${path[0] === "/" ? "" : "/"}${path}`; opts.headers = { Authorization: `Bearer ${this.$auth.oauth_access_token}`, }; return await axios(opts); }, /** * Check whether an array of project IDs contains the given proejct ID. This method is used in multiple sources to validate if an event matches the selection in the project filter. * @params {Integer} project_id - The ID for a Todoist project * @params {Array} selectedProjectIds - An array of Todoist project IDs * @returns {Boolean} Returns `true` if the `project_id` matches a value in the arrar or if the array is empty. Otherwise returns `false`. */ isProjectInList(projectId, selectedProjectIds) { return ( selectedProjectIds.length === 0 || selectedProjectIds.includes(projectId) ); }, /** * Public method to make a sync request. * @params {Object} opts - The configuration for an axios request with a `path` key. * @returns {Object} When the request succeeds, an HTTP 200 response will be returned with a JSON object containing the requested resources and also a new `sync_token`. */ async sync(opts) { return ( await this._makeSyncRequest({ path: `/sync/v8/sync`, method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", }, payload: opts, }) ).data; }, /** * Get the list of project for the authenticated user * @returns {Array} Returns a JSON-encoded array containing all user projects */ async getProjects() { return ( await this._makeRestRequest({ path: `/rest/v1/projects`, method: "GET", }) ).data; }, async syncItems(db) { return await this.syncResources(db, ["items"]); }, async syncProjects(db) { return await this.syncResources(db, ["projects"]); }, async syncResources(db, resourceTypes) { const syncToken = db.get("syncToken") || "*"; const result = await this.sync({ resource_types: JSON.stringify(resourceTypes), sync_token: syncToken, }); db.set("syncToken", result.sync_token); return result; }, }, }; <|start_filename|>components/twitch/sources/streams-by-streamer/streams-by-streamer.js<|end_filename|> const common = require("../common-polling.js"); module.exports = { ...common, name: "Streams By Streamer", key: "twitch-streams-by-streamer", description: "Emits an event when a live stream starts from the streamers you specify.", version: "0.0.3", props: { ...common.props, streamerLoginNames: { propDefinition: [common.props.twitch, "streamerLoginNames"], }, }, methods: { ...common.methods, getMeta(item) { const { id, started_at: startedAt, title: summary } = item; const ts = Date.parse(startedAt); return { id, summary, ts, }; }, }, async run() { // get and emit streams for the specified streamers const streams = await this.paginate(this.twitch.getStreams.bind(this), { user_login: this.streamerLoginNames, }); for await (const stream of streams) { this.$emit(stream, this.getMeta(stream)); } }, }; <|start_filename|>components/microsoft_onedrive/sources/new-file/new-file.js<|end_filename|> const common = require("../common/base"); module.exports = { ...common, key: "microsoft_onedrive-new-file", name: "New File (Instant)", description: "Emit an event when a new file is added to a specific drive in OneDrive", version: "0.0.1", dedupe: "unique", hooks: { ...common.hooks, async activate() { await common.hooks.activate.bind(this)(); this._setLastCreatedTimestamp(); }, }, methods: { ...common.methods, _getLastCreatedTimestamp() { return this.db.get("lastCreatedTimestamp") || 0; }, _setLastCreatedTimestamp(lastCreatedTimestamp = Date.now()) { this.db.set("lastCreatedTimestamp", lastCreatedTimestamp); }, _getMaxCreatedTimestamp() { return this.db.get("maxCreatedTimestamp") || 0; }, _setMaxCreatedTimestamp(maxCreatedTimestamp = Date.now()) { this.db.set("maxCreatedTimestamp", maxCreatedTimestamp); }, isItemRelevant(driveItem) { // Drive items that were created prior to the latest cached creation time // are not relevant to this event source const { createdDateTime } = driveItem; const createdTimestamp = Date.parse(createdDateTime); return createdTimestamp > this._getLastCreatedTimestamp(); }, generateMeta(driveItem) { const { id, createdDateTime, name, } = driveItem; const summary = `New file: ${name}`; const ts = Date.parse(createdDateTime); return { id, summary, ts, }; }, processEvent(driveItem) { const meta = this.generateMeta(driveItem); this.$emit(driveItem, meta); const { createdDateTime } = driveItem; const createdTimestamp = Date.parse(createdDateTime); if (createdTimestamp > this._getMaxCreatedTimestamp()) { this._setMaxCreatedTimestamp(createdTimestamp); } }, postProcessEvent() { const maxCreatedTimestamp = this._getMaxCreatedTimestamp(); this._setLastCreatedTimestamp(maxCreatedTimestamp); }, }, }; <|start_filename|>components/github/actions/create-issue/create-issue.js<|end_filename|> const github = require('../../github.app.js') const { Octokit } = require('@octokit/rest') module.exports = { key: "github-create-issue", name: "Create Issue", description: "Create a new issue in a Gihub repo.", version: "0.0.13", type: "action", props: { github, repoFullName: { propDefinition: [github, "repoFullName"] }, title: { propDefinition: [github, "issueTitle"] }, body: { propDefinition: [github, "issueBody"] }, labels: { propDefinition: [github, "labelNames", c => ({ repoFullName: c.repoFullName })], optional: true, }, milestone: { propDefinition: [github, "milestone", c => ({ repoFullName: c.repoFullName })], optional: true }, assignees: { propDefinition: [github, "issueAssignees"] }, }, async run() { const octokit = new Octokit({ auth: this.github.$auth.oauth_access_token }) return (await octokit.issues.create({ owner: this.repoFullName.split("/")[0], repo: this.repoFullName.split("/")[1], title: this.title, body: this.body, labels: this.labels, assignees: this.assignees, milestone: this.milestone, })).data }, } <|start_filename|>interfaces/http/examples/http-db-example.js<|end_filename|> // Example of how to use $.service.db methods // Each time this component receives an HTTP request, // it increments the requestCount key and emits it module.exports = { name: "http-db", version: "0.0.2", props: { http: { type: "$.interface.http", customResponse: true, }, db: "$.service.db", }, async run(event) { this.http.respond({ status: 200, body: event, }); let requestCount = this.db.get("requestCount") || 0; requestCount += 1; this.$emit({ requestCount, }); this.db.set("requestCount", requestCount); }, }; <|start_filename|>components/airtable/actions/create-single-record/create-single-record.js<|end_filename|> const airtable = require("../../airtable.app.js"); const common = require("../common.js"); module.exports = { key: "airtable-create-single-record", name: "Create single record", description: "Adds a record to a table.", version: "0.1.1", type: "action", props: { ...common.props, record: { propDefinition: [ airtable, "record", ], }, typecast: { propDefinition: [ airtable, "typecast", ], }, }, async run() { const table = this.airtable.base(this.baseId)(this.tableId); this.airtable.validateRecord(this.record); const data = [ { fields: this.record, }, ]; const params = { typecast: this.typecast, }; try { const [ response, ] = await table.create(data, params); return response; } catch (err) { this.airtable.throwFormattedError(err); } }, }; <|start_filename|>components/mysql/sources/new-column/new-column.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, key: "<KEY>", name: "New Column", description: "Emits an event when you add a new column to a table", version: "0.0.1", dedupe: "unique", props: { ...common.props, db: "$.service.db", table: { propDefinition: [common.props.mysql, "table"] }, }, methods: { ...common.methods, _getPreviousColumns() { return this.db.get("previousColumns"); }, _setPreviousColumns(previousColumns) { this.db.set("previousColumns", previousColumns); }, async listResults(connection) { let previousColumns = this._getPreviousColumns() || []; const columns = await this.mysql.listNewColumns( connection, this.table, previousColumns ); this.iterateAndEmitEvents(columns); const columnNames = columns.map((column) => column.Field); const newColumnNames = columnNames.filter( (c) => !previousColumns.includes(c) ); previousColumns = previousColumns.concat(newColumnNames); this._setPreviousColumns(previousColumns); }, generateMeta(column) { const columnName = column.Field; return { id: `${columnName}${this.table}`, summary: columnName, ts: Date.now(), }; }, }, }; <|start_filename|>components/ringcentral/sources/new-call-recording/new-call-recording.js<|end_filename|> const common = require("../common/timer-based"); module.exports = { ...common, key: "ringcentral-new-call-recording", name: "New Call Recording", description: "Emits an event when a call recording is created", version: "0.0.1", props: { ...common.props, extensionId: { propDefinition: [common.props.ringcentral, "extensionId"] }, }, methods: { ...common.methods, generateMeta(data) { const { id, startTime: timestamp, direction, } = data; const ts = Date.parse(timestamp); const { phoneNumber } = direction === "Outbound" ? data.to : data.from; const maskedPhoneNumber = this.getMaskedNumber(phoneNumber); const summary = `New call recording (${maskedPhoneNumber})`; return { id, summary, ts, }; }, async processEvent(opts) { const { dateFrom, dateTo, } = opts; const callRecordingsScan = this.ringcentral.getCallRecordings( this.extensionId, dateFrom, dateTo, ); for await (const record of callRecordingsScan) { const meta = this.generateMeta(record); this.$emit(record, meta); } } }, }; <|start_filename|>components/mysql/sources/new-row-custom-query/new-row-custom-query.js<|end_filename|> const common = require("../common.js"); const { v4: uuidv4 } = require("uuid"); module.exports = { ...common, key: "mysql-new-row-custom-query", name: "New Row (Custom Query)", description: "Emits an event when new rows are returned from a custom query", version: "0.0.1", dedupe: "unique", props: { ...common.props, table: { propDefinition: [common.props.mysql, "table"] }, column: { propDefinition: [ common.props.mysql, "column", (c) => ({ table: c.table }), ], label: "De-duplication Key", description: "The name of a column in the table to use for de-duplication", optional: true, }, query: { propDefinition: [common.props.mysql, "query"] }, }, methods: { ...common.methods, async listResults(connection) { const rows = await this.mysql.executeQuery(connection, this.query); this.iterateAndEmitEvents(rows); }, generateMeta(row) { const id = this.column ? row[this.column] : uuidv4(); return { id, summary: `New Row ${id}`, ts: Date.now(), }; }, }, }; <|start_filename|>components/cliniko/cliniko.app.js<|end_filename|> const { axios } = require("@pipedreamhq/platform"); module.exports = { type: "app", app: "cliniko", propDefinitions: { patientId: { type: "integer", label: "Patient ID", description: "Enter a unique patient ID.", }, }, methods: { /** * Get the Cliniko API key for the authenticated user. * @returns {String} The Cliniko API key. */ _apiKey() { return this.$auth.api_key; }, _shard() { return this.$auth.shard; }, _baseApiUrl() { return `https://api.${this._shard()}.cliniko.com/v1`; }, _makeRequestConfig(url) { const auth = { username: this._apiKey(), password: "", // No password needed. }; // Cliniko requires contact email address in User-Agent header. // See https://github.com/redguava/cliniko-api#identifying-your-application. const headers = { "Accept": "application/json", "User-Agent": "Pipedream (<EMAIL>)", }; return { url, headers, auth, }; }, _patientsApiUrl(id = undefined) { const baseUrl = this._baseApiUrl(); const basePath = "/patients"; const path = id ? `${basePath}/${id}` : basePath; return `${baseUrl}${path}`; }, /** * Get the details of a specified patient. * @params {Integer} patientId - The unique identifier of the patient * @returns {Object} The details of the specified patient. */ async getPatient(patientId) { const apiUrl = this._patientsApiUrl(patientId); const requestConfig = this._makeRequestConfig(apiUrl); return await axios(this, requestConfig); }, }, }; <|start_filename|>components/twitch/actions/get-top-games/get-top-games.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, name: "Get Top Games", key: "twitch-get-top-games", description: "Gets games sorted by number of current viewers on Twitch, most popular first", version: "0.0.1", type: "action", props: { ...common.props, max: { propDefinition: [ common.props.twitch, "max", ], description: "Maximum number of games to return", }, }, async run() { const topGames = await this.paginate( this.twitch.getTopGames.bind(this), {}, this.max, ); return await this.getPaginatedResults(topGames); }, }; <|start_filename|>components/mysql/sources/new-row/new-row.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, key: "mysql-new-row", name: "New Row", description: "Emits an event when you add a new row to a table", version: "0.0.1", dedupe: "unique", props: { ...common.props, db: "$.service.db", table: { propDefinition: [common.props.mysql, "table"] }, column: { propDefinition: [ common.props.mysql, "column", (c) => ({ table: c.table }), ], optional: true, }, }, hooks: { /** If column prop is left blank, get the table's primary key to use for ordering and deduping. */ async deploy() { const connection = await this.mysql.getConnection(); let column = this.column; if (!column) { const keyData = await this.mysql.getPrimaryKey(connection, this.table); column = keyData[0].Column_name; } this._setColumn(column); await this.listTopRows(connection, column); await this.mysql.closeConnection(connection); }, }, methods: { ...common.methods, _getColumn() { return this.db.get("column"); }, _setColumn(column) { this.db.set("column", column); }, async listResults(connection) { const column = this._getColumn(); await this.listRowResults(connection, column); }, iterateAndEmitEvents(rows) { const column = this._getColumn(); for (const row of rows) { const meta = this.generateMeta(row, column); this.$emit(row, meta); } }, generateMeta(row, column) { return { id: row[column], summary: `New Row Added ${column}: ${row[column]}`, ts: Date.now(), }; }, }, }; <|start_filename|>components/swapi/swapi.app.js<|end_filename|> const axios = require('axios') module.exports = { type: 'app', app: 'swapi', propDefinitions: { film: { type: "string", async options() { return (await axios({ url: 'https://swapi.dev/api/films' })).data.results.map(function(film, index) { return { label: film.title, value: index + 1 } }) } } } } <|start_filename|>examples/async-options.js<|end_filename|> module.exports = { name: "Async Options Example", version: "0.1", props: { msg: { type: "string", label: "Message", description: "Select a message to `console.log()`", async options() { return [ "This is option 1", "This is option 2", ]; }, }, }, async run() { this.$emit(this.msg); }, }; <|start_filename|>components/hubspot/sources/contact-updated/contact-updated.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, key: "hubspot-contact-updated", name: "<NAME>", description: "Emits an event each time a contact is updated.", version: "0.0.2", methods: { ...common.methods, generateMeta(contact) { const { id, properties, updatedAt } = contact; const ts = Date.parse(updatedAt); return { id: `${id}${ts}`, summary: `${properties.firstname} ${properties.lastname}`, ts, }; }, isRelevant(contact, updatedAfter) { return Date.parse(contact.updatedAt) > updatedAfter; }, }, async run(event) { const updatedAfter = this._getAfter(); const data = { limit: 100, sorts: [ { propertyName: "lastmodifieddate", direction: "DESCENDING", }, ], properties: this.db.get("properties"), object: "contacts", }; await this.paginate( data, this.hubspot.searchCRM.bind(this), "results", updatedAfter ); this._setAfter(Date.now()); }, }; <|start_filename|>components/dropbox/dropbox.app.js<|end_filename|> const Dropbox = require("dropbox").Dropbox; const fetch = require("isomorphic-fetch"); module.exports = { type: "app", app: "dropbox", propDefinitions: { path: { type: "string", label: "Path", description: "Path to the folder you want to watch for changes.", optional: false, useQuery: true, async options({ query }) { return await this.pathOptions(query); }, }, recursive: { type: "boolean", label: "Recursive", description: "Also watch sub-directories and their contents.", optional: false, default: false, }, }, methods: { async sdk() { const baseClientOpts = { accessToken: this.$auth.oauth_access_token, fetch, }; // In order to properly set the [root // path](https://www.dropbox.com/developers/reference/path-root-header-modes) // to use in every API request we first need to extract some information // from the authenticated user's account, for which we need to create a // client and issue an API request. const dpx = new Dropbox(baseClientOpts); const { result } = await dpx.usersGetCurrentAccount(); const pathRoot = JSON.stringify({ ".tag": "root", "root": result.root_info.root_namespace_id, }); return new Dropbox({ ...baseClientOpts, pathRoot, }); }, async pathOptions(path) { const limit = 50; let options = []; let entries, has_more, cursor; path = path === "/" || path === null ? "" : path; try { const dpx = await this.sdk(); let files = await dpx.filesListFolder({ path, limit }); if (files.result) { files = files.result; } do { ({ entries, has_more, cursor } = files); for (entry of entries) { if (entry[".tag"] == "folder") { options.push(entry.path_display); } } // TODO break after a certain number of folders has been found?? if (has_more) { files = await dpx.filesListFolderContinue({ cursor }); if (files.result) { files = files.result; } } } while (has_more); options = options.sort((a, b) => { return a.toLowerCase().localeCompare(b.toLowerCase()); }); if (path) { options.unshift(require("path").dirname(path)); } options.unshift(path); } catch (err) { console.log(err); throw `Error connecting to Dropbox API to get directory listing for path: ${path}`; } const labeledOptions = options.map((opt) => { if (opt === "") { return { label: "/", value: "" }; } return { label: opt, value: opt }; }); return { options: labeledOptions }; }, async initState(context) { const { path, recursive, db } = context; try { const fixedPath = path == "/" ? "" : path; const dpx = await this.sdk(); let response = await dpx.filesListFolderGetLatestCursor({ path: fixedPath, recursive, }); if (response.result) { response = response.result; } const { cursor } = response; const state = { path, recursive, cursor }; db.set("dropbox_state", state); return state; } catch (err) { console.log(err); throw `Error connecting to Dropbox API to get latest cursor for folder: ${path}${ recursive ? " (recursive)" : "" }`; } }, async getState(context) { const { path, recursive, db } = context; let state = db.get("dropbox_state"); if (state == null || state.path != path || state.recursive != recursive) { state = await this.initState(context); } return state; }, async getUpdates(context) { let ret = []; const state = await this.getState(context); if (state) { try { const { db } = context; let [cursor, has_more, entries] = [state.cursor, true, null]; while (has_more) { const dpx = await this.sdk(); let response = await dpx.filesListFolderContinue({ cursor }); if (response.result) { response = response.result; } ({ entries, cursor, has_more } = response); ret = ret.concat(entries); } state.cursor = cursor; db.set("dropbox_state", state); } catch (err) { console.log(err); throw `Error connecting to Dropbox API to get list of updated files/folders for cursor: ${state.cursor}`; } } return ret; }, }, }; <|start_filename|>components/twitter/sources/common/tweets.js<|end_filename|> const twitter = require("../../twitter.app"); module.exports = { props: { db: "$.service.db", twitter, count: { propDefinition: [ twitter, "count", ], }, maxRequests: { propDefinition: [ twitter, "maxRequests", ], }, timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 15, }, }, }, methods: { _addParsedId(tweet) { // This is needed since the numeric value of a Tweet's ID can exceed the // maximum supported value of `number` const parsedId = BigInt(tweet.id_str); return { ...tweet, parsedId, }; }, _compareByIdAsc({ parsedId: a }, { parsedId: b }) { if (a < b) return -1; if (a > b) return 1; return 0; }, sortTweets(tweets) { return tweets .map(this._addParsedId) .sort(this._compareByIdAsc); }, /** * This function returns the Twitter screen name of the subject account * * @returns a string containing the relevant Twitter screen name */ getScreenName() { throw new Error("getScreenName is not implemented"); }, /** * This function provides the list of options for the `tweetId` user prop. * It is meant to be called by Pipedream during the setup of the user prop * and not during normal operations of the event source. * * @param {object} context the context object for the pagination of the * prop options * @param {object} context.prevContext the context object of a previous * call to this method * @returns an object containing the list of Tweet ID options for the * `tweetId` user prop and the context for pagination */ async tweetIdOptions(context) { const { prevContext = {} } = context; const { screenName = await this.getScreenName(), sinceId = "1", } = prevContext; const userTimelineOpts = { screen_name: screenName, since_id: sinceId, count: 10, trim_user: true, exclude_replies: false, include_rts: false, }; const tweets = await this.twitter.getUserTimeline(userTimelineOpts); if (tweets.length === 0) { // There are no more tweets to go through return { options: null, context: prevContext, }; } const sortedTweets = this.sortTweets(tweets); const { id_str: lastId } = sortedTweets[sortedTweets.length-1]; const options = sortedTweets.map(({ full_text, id_str, }) => ({ label: full_text, value: id_str, })); return { options, context: { screenName, sinceId: lastId, }, }; }, getSinceId() { return this.db.get("since_id") || "1"; }, setSinceId(sinceId = "1") { this.db.set("since_id", sinceId); }, generateMeta(tweet) { const { created_at: createdAt, full_text: fullText, id_str: id, text, } = tweet; const summary = fullText || text; const ts = this.twitter.parseDate(createdAt); return { id, summary, ts, }; }, /** * The purpose of this function is to retrieve the relevant Tweets for the * event source that implements it. For example, if the event source emits * an event for each new Tweet of a specific user, the implementation of * this function will perform the retrieval of such Tweets and return it as * a list of [Tweet * objects](https://developer.twitter.com/en/docs/twitter-api/v1/data-dictionary/object-model/tweet) * * @returns a list of Tweet objects for which to emit new events */ retrieveTweets() { throw new Error("retrieveTweets is not implemented"); }, }, async run() { const tweets = await this.retrieveTweets(); if (tweets.length === 0) { console.log("No new tweets available. Skipping..."); return; } const sortedTweets = this.sortTweets(tweets); const { id_str: lastId } = sortedTweets[sortedTweets.length-1]; this.setSinceId(lastId); // Emit array of tweet objects sortedTweets.forEach(tweet => { const meta = this.generateMeta(tweet); this.$emit(tweet, meta); }); }, }; <|start_filename|>components/npm/npm.app.js<|end_filename|> module.exports = { type: "app", app: "npm", } <|start_filename|>components/twitch/sources/new-clips/new-clips.js<|end_filename|> const common = require("../common-polling.js"); const twitch = require("../../twitch.app.js"); module.exports = { ...common, name: "New Clips", key: "twitch-new-clips", description: "Emits an event when there is a new clip for the specified game.", version: "0.0.1", props: { ...common.props, game: { propDefinition: [twitch, "game"] }, max: { propDefinition: [twitch, "max"] }, }, methods: { ...common.methods, getMeta({ id, title: summary, created_at: createdAt }) { const ts = new Date(createdAt).getTime(); return { id, summary, ts, }; }, }, async run() { const { data: gameData } = await this.twitch.getGames([this.game]); if (gameData.length == 0) { console.log(`No game found with the name ${this.game}`); return; } // get and emit new clips of the specified game const params = { game_id: gameData[0].id, started_at: this.getLastEvent(this.db.get("lastEvent")), }; const clips = await this.paginate( this.twitch.getClips.bind(this), params, this.max ); for await (const clip of clips) { this.$emit(clip, this.getMeta(clip)); } this.db.set("lastEvent", Date.now()); }, }; <|start_filename|>components/clickup/actions/create-task/create-task.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, key: "clickup-create-task", name: "<NAME>", description: "Creates a new task", version: "0.0.2", type: "action", props: { ...common.props, list: { propDefinition: [ common.props.clickup, "list", (c) => ({ folder: c.folder, space: c.space, }), ], }, name: { propDefinition: [ common.props.clickup, "name", ], description: "New task name", }, description: { type: "string", label: "Description", description: "New task description", optional: true, }, assignees: { propDefinition: [ common.props.clickup, "assignees", (c) => ({ workspace: c.workspace, }), ], }, tags: { propDefinition: [ common.props.clickup, "tags", (c) => ({ space: c.space, }), ], }, status: { propDefinition: [ common.props.clickup, "status", (c) => ({ list: c.list, }), ], }, dueDate: { propDefinition: [ common.props.clickup, "dueDate", ], description: `The date by which you must complete the task. Use UTC time in milliseconds (ex. 1508369194377)`, }, dueDateTime: { propDefinition: [ common.props.clickup, "dueDateTime", ], description: "Set to true if you want to enable the due date time for the task", }, timeEstimate: { type: "integer", label: "Time Estimate", description: "Use milliseconds", optional: true, }, startDate: { type: "integer", label: "Start Date", description: "The start date of the task. Use UTC time in milliseconds (ex. 1567780450202)", optional: true, }, startDateTime: { type: "boolean", label: "Start Date Time", description: "Select true if you want to enable the start date time", optional: true, }, notifyAll: { type: "boolean", label: "Notify All", description: `If Notify All is true, creation notifications will be sent to everyone including the creator of the task.`, optional: true, }, parent: { propDefinition: [ common.props.clickup, "parent", (c) => ({ list: c.list, }), ], optional: true, }, linksTo: { propDefinition: [ common.props.clickup, "task", (c) => ({ list: c.list, }), ], label: "Links To", description: "Accepts a task ID to create a linked dependency on the new task", optional: true, }, checkRequiredCustomFields: { type: "boolean", label: "Check Required Custom Fields", description: `Indicates whether or not your new task will include data for required Custom Fields (true) or not (false). The default is false. If you set this option to true, and do not include information for required Custom Fields, then you will receive an error that 'One or more required fields is missing'.`, optional: true, }, customFields: { type: "string[]", label: "Custom Fields", description: `An array of objects containing 'id' and 'value' keys. Example: { "id": "0a52c486-5f05-403b-b4fd-c512ff05131c", "value": 23 }, `, optional: true, }, }, async run() { const data = { name: this.name, description: this.description, assignees: this.assignees, tags: this.tags, status: this.status, priority: this.priority, due_date: this.dueDate, due_date_time: this.dueDateTime, time_estimate: this.timeEstimate, start_date: this.startDate, start_date_time: this.startDateTime, notify_all: this.notifyAll, parent: this.parent, links_to: this.linksTo, check_required_custom_fields: this.checkRequiredCustomFields, custom_fields: this.customFields, }; return await this.clickup.createTask(this.list, data); }, }; <|start_filename|>components/stack_exchange/sources/new-answers-from-users/new-answers-from-users.js<|end_filename|> const stack_exchange = require('../../stack_exchange.app'); module.exports = { key: "stack_exchange-new-answers-from-users", name: "New Answers from Specific Users", description: "Emits an event when a new answer is posted by one of the specified users", version: "0.0.1", dedupe: "unique", props: { stack_exchange, db: "$.service.db", siteId: { propDefinition: [stack_exchange, "siteId"] }, userIds: { propDefinition: [ stack_exchange, "userIds", c => ({ siteId: c.siteId }), ], }, timer: { type: '$.interface.timer', default: { intervalSeconds: 60 * 15, // 15 minutes }, }, }, hooks: { async activate() { const fromDate = this._getCurrentEpoch(); this.db.set("fromDate", fromDate); }, }, methods: { _getCurrentEpoch() { // The StackExchange API works with Unix epochs in seconds. return Math.floor(Date.now() / 1000); }, generateMeta(data) { const { answer_id: id, owner: owner, creation_date: ts, } = data; const { display_name: username } = owner; const summary = `New answer from ${username}`; return { id, summary, ts, }; }, }, async run() { const fromDate = this.db.get("fromDate"); const toDate = this._getCurrentEpoch(); const filter = '!SWKA(ozr4ec2cHE9JK'; // See https://api.stackexchange.com/docs/filters const searchParams = { fromDate, toDate, filter, sort: 'creation', order: 'asc', site: this.siteId, } const items = this.stack_exchange.answersFromUsers(this.userIds, searchParams); for await (const item of items) { const meta = this.generateMeta(item); this.$emit(item, meta); } this.db.set("fromDate", toDate); }, }; <|start_filename|>components/airtable/actions/list-records-in-view/list-records-in-view.js<|end_filename|> const common = require("../common.js"); const commonList = require("../common-list.js"); module.exports = { key: "airtable-list-records-in-view", name: "List Records in View", description: "Retrieve records in a view with automatic pagination. Optionally sort and filter results.", type: "action", version: "0.1.0", ...commonList, props: { ...common.props, viewId: { type: "$.airtable.viewId", tableIdProp: "tableId", }, ...commonList.props, }, }; <|start_filename|>components/textlocal/sources/common/base.js<|end_filename|> const { v4: uuidv4 } = require("uuid"); const textlocal = require("../../textlocal.app"); module.exports = { props: { db: "$.service.db", textlocal, }, methods: { generateMeta() { throw new Error('generateMeta is not implemented') }, /** * Given a person's name, return a masked version of it. The purpose of a * masked name is to hide personal information so that it is not exposed to * an unintended audience. * * Examples: * * - Input: <NAME> (first name "John", last name "Doe") * - Output: <NAME>. * * - Input: Jane (first name "Jane", last name not provided) * - Output: Jane #. * * @param {object} nameProps Object containing the name to be masked * @param {string} nameProps.firstName The first name * @param {string} nameProps.lastName The last name * @return {string} The masked full name */ getMaskedName({ firstName = "", lastName = "", }) { const lastNameInitial = lastName.slice(0, 1).toUpperCase() || "#"; return `${firstName} ${lastNameInitial}.`; }, /** * Given a phone number, return a masked version of it. The purpose of a * masked number is to avoid exposing it to an unintended audience. * * Example: * * - Input: 6505551234 * - Output: ######1234 * * @param {number} number The phone number to mask * @return {string} The masked phone number */ getMaskedNumber(number) { const numberAsString = Number(number).toString(); const { length: numberLength } = numberAsString; return numberAsString .slice(numberLength - 4) .padStart(numberLength, "#"); }, processEvent(event) { const meta = this.generateMeta(event); this.$emit(event, meta); }, }, async run(event) { await this.processEvent(event); }, }; <|start_filename|>components/hubspot/sources/new-event/new-event.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, key: "hubspot-new-event", name: "New Events", description: "Emits an event for each new Hubspot event.", version: "0.0.2", dedupe: "unique", props: { ...common.props, objectType: { propDefinition: [common.props.hubspot, "objectType"] }, objectIds: { propDefinition: [ common.props.hubspot, "objectIds", (c) => ({ objectType: c.objectType }), ], }, }, hooks: {}, methods: { ...common.methods, generateMeta(result) { const { id, eventType } = result; return { id, summary: eventType, ts: Date.now(), }; }, }, async run(event) { const occurredAfter = this._getAfter(); for (const objectId of this.objectIds) { const params = { limit: 100, objectType: this.objectType, objectId, occurredAfter, }; await this.paginate( params, this.hubspot.getEvents.bind(this), "results", occurredAfter ); } this._setAfter(Date.now()); }, }; <|start_filename|>components/intercom/sources/tag-added-to-conversation/tag-added-to-conversation.js<|end_filename|> const intercom = require("../../intercom.app.js"); module.exports = { key: "intercom-tag-added-to-conversation", name: "Tag Added To Conversation", description: "Emits an event each time a new tag is added to a conversation.", version: "0.0.1", dedupe: "unique", props: { intercom, db: "$.service.db", timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 15, }, }, }, async run(event) { const data = { query: { field: "tag_ids", operator: "!=", value: null, }, }; results = await this.intercom.searchConversations(data); for (const conversation of results) { for (const tag of conversation.tags.tags) { this.$emit(tag, { id: `${conversation.id}${tag.id}`, summary: tag.name, ts: tag.applied_at, }); } } }, }; <|start_filename|>components/twitch/actions/get-users/get-users.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, name: "Get Users", key: "twitch-get-users", description: "Gets the user objects for the specified Twitch login names", version: "0.0.1", type: "action", props: { ...common.props, login: { type: "string[]", label: "Login names", description: "User login name. Multiple login names can be specified. Limit: 100.", }, }, async run() { const params = { login: this.login, }; return (await this.twitch.getMultipleUsers(params)).data.data; }, }; <|start_filename|>components/twitch/actions/search-games/search-games.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, name: "Search Games", key: "twitch-search-games", description: `Searches for games based on a specified query parameter. A game is returned if the query parameter is matched entirely or partially in the channel description or game name`, version: "0.0.1", type: "action", props: { ...common.props, max: { propDefinition: [ common.props.twitch, "max", ], description: "Maximum number of games to return", }, query: { type: "string", label: "Query", description: "The search query", }, }, async run() { const params = { query: this.query, }; const searchResults = await this.paginate( this.twitch.searchGames.bind(this), params, this.max, ); return await this.getPaginatedResults(searchResults); }, }; <|start_filename|>components/todoist/sources/incomplete-task/incomplete-task.js<|end_filename|> const common = require("../common-task.js"); module.exports = { ...common, key: "todoist-incomplete-task", name: "Incomplete Task", description: "Emit an event for each new incomplete task", version: "0.0.1", dedupe: "unique", methods: { ...common.methods, isElementRelevant(element) { return element.checked === 0; }, }, }; <|start_filename|>components/snowflake/sources/common.js<|end_filename|> const snowflake = require("../snowflake.app"); module.exports = { dedupe: "unique", props: { snowflake, db: "$.service.db", timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 15, // 15 minutes }, }, eventSize: { type: "integer", label: "Event Size", description: "The number of rows to include in a single event (by default, emits 1 event per row)", default: 1, min: 1, }, }, methods: { async processCollection(statement, timestamp) { let lastResultId; let totalRowCount = 0; const rowCollectionStream = this.snowflake.collectRowsPaginated(statement, this.eventSize); for await (const rows of rowCollectionStream) { const rowCount = rows.length; if (rowCount <= 0) { break; } lastResultId = rows[rowCount-1][this.uniqueKey]; totalRowCount += rowCount; const meta = this.generateMetaForCollection({ lastResultId, rowCount, timestamp, }); this.$emit({ rows }, meta); } return { lastResultId, rowCount: totalRowCount, } }, async processSingle(statement, timestamp) { let lastResultId; let rowCount = 0; const rowStream = await this.snowflake.getRows(statement); for await (const row of rowStream) { const meta = this.generateMeta({ row, timestamp, }); this.$emit(row, meta); lastResultId = row[this.uniqueKey]; ++rowCount; } return { lastResultId, rowCount, }; }, getStatement() { throw new Error('getStatement is not implemented'); }, generateMeta() { throw new Error('generateMeta is not implemented'); }, generateMetaForCollection() { throw new Error('generateMetaForCollection is not implemented'); }, processEvent() { throw new Error('processEvent is not implemented'); }, }, async run(event) { const { timestamp } = event; const statement = this.getStatement(event); return (this.eventSize === 1) ? this.processSingle(statement, timestamp) : this.processCollection(statement, timestamp); }, }; <|start_filename|>components/stack_exchange/stack_exchange.app.js<|end_filename|> const _ = require("lodash"); const axios = require("axios"); const he = require("he"); module.exports = { type: "app", app: "stack_exchange", propDefinitions: { siteId: { type: "string", label: "Site", description: "The StackExchange site for which questions are of interest", async options(context) { if (context.page !== 0) { // The `sites` API is not paginated: // https://api.stackexchange.com/docs/sites return { options: [] }; } const url = this._sitesUrl(); const { data } = await axios.get(url); const rawOptions = data.items.map(site => ({ label: site.name, value: site.api_site_parameter, })); const options = _.sortBy(rawOptions, ['label']); return { options, }; }, }, keywords: { type: "string[]", label: "Keywords", description: "Keywords to search for in questions", }, questionIds: { type: "string[]", label: "Questions", description: "Questions to monitor (max: 100)", useQuery: true, async options(context) { const q = context.query || ''; const searchParams = { sort: 'relevance', order: 'desc', closed: false, q, }; const url = this._advancedSearchUrl(); const { items, hasMore } = await this._propDefinitionsOptions(url, searchParams, context); const options = items.map((question) => ({ label: he.decode(question.title), value: question.question_id, })); return { options, context: { hasMore, }, }; }, }, userIds: { type: "string[]", label: "Users", description: "Users to monitor (max: 100)", useQuery: true, async options(context) { const inname = context.query || ''; const searchParams = { sort: 'reputation', order: 'desc', inname, }; const url = this._usersUrl(); const { items, hasMore } = await this._propDefinitionsOptions(url, searchParams, context); const options = items.map((user) => ({ label: user.display_name, value: user.user_id, })); return { options, context: { hasMore, }, }; }, }, }, methods: { _apiUrl() { return "https://api.stackexchange.com/2.2"; }, _sitesUrl() { const baseUrl = this._apiUrl(); return `${baseUrl}/sites`; }, _advancedSearchUrl() { const baseUrl = this._apiUrl(); return `${baseUrl}/search/advanced`; }, _usersUrl() { const baseUrl = this._apiUrl(); return `${baseUrl}/users`; }, _answersForQuestionsUrl(questionIds) { const baseUrl = this._apiUrl(); const ids = questionIds.join(';'); return `${baseUrl}/questions/${ids}/answers`; }, _answersFromUsersUrl(userIds) { const baseUrl = this._apiUrl(); const ids = userIds.join(';'); return `${baseUrl}/users/${ids}/answers`; }, _authToken() { return this.$auth.oauth_access_token }, async _propDefinitionsOptions(url, baseSearchParams, context) { const { hasMore = true, page, siteId, } = context; if (!hasMore) { return { items: [], hasMore: false, }; } const searchParams = { ...baseSearchParams, site: siteId, }; const searchPage = page + 1; // The StackExchange API pages are 1-indexed const { items, has_more: nextPageHasMore, } = await this.getItemsForPage(url, searchParams, searchPage); return { items, hasMore: nextPageHasMore, }; }, _makeRequestConfig() { const authToken = this._authToken(); const headers = { "Authorization": `Bearer ${authToken}`, "User-Agent": "@PipedreamHQ/pipedream v0.1", }; return { headers, }; }, advancedSearch(searchParams) { const url = this._advancedSearchUrl(); return this.getItems(url, searchParams); }, answersForQuestions(questionIds, searchParams) { const url = this._answersForQuestionsUrl(questionIds); return this.getItems(url, searchParams); }, answersFromUsers(userIds, searchParams) { const url = this._answersFromUsersUrl(userIds); return this.getItems(url, searchParams); }, async *getItems(url, baseParams) { let page = 1; let hasMore = false; do { const data = await this.getItemsForPage(url, baseParams, page); const { items } = data; if (items === undefined) { console.warn(` Unexpected response from ${url} (page ${page}): "items" is undefined. Query parameters: ${JSON.stringify(baseParams, null, 2)}. `); return; } if (items.length === 0) { console.log(` No new items found in ${url} for the following parameters: ${JSON.stringify(baseParams, null, 2)} `); return; } console.log(`Found ${items.length} new item(s) in ${url}`); for (const item of items) { yield item; } hasMore = data.has_more; ++page; } while (hasMore); }, async getItemsForPage(url, baseParams, page) { const baseRequestConfig = this._makeRequestConfig(); const params = { ...baseParams, page, }; const requestConfig = { ...baseRequestConfig, params, }; const { data } = await axios.get(url, requestConfig); return data; }, }, }; <|start_filename|>components/bitbucket/sources/new-branch/new-branch.js<|end_filename|> const common = require("../../common"); const { bitbucket } = common.props; const EVENT_SOURCE_NAME = "New Branch (Instant)"; module.exports = { ...common, name: EVENT_SOURCE_NAME, key: "bitbucket-new-branch", description: "Emits an event when a new branch is created", version: "0.0.2", props: { ...common.props, repositoryId: { propDefinition: [ bitbucket, "repositoryId", c => ({ workspaceId: c.workspaceId }), ], }, }, methods: { ...common.methods, getEventSourceName() { return EVENT_SOURCE_NAME; }, getHookEvents() { return [ "repo:push", ]; }, getHookPathProps() { return { workspaceId: this.workspaceId, repositoryId: this.repositoryId, }; }, isNewBranch(change) { const expectedChangeTypes = new Set([ "branch", "named_branch", ]); return ( change.created && expectedChangeTypes.has(change.new.type) ); }, generateMeta(data) { const { headers, change } = data; const newBranchName = change.new.name; const summary = `New Branch: ${newBranchName}`; const ts = +new Date(headers["x-event-time"]); const compositeId = `${newBranchName}-${ts}`; return { id: compositeId, summary, ts, }; }, async processEvent(event) { const { headers, body } = event; const { changes = [] } = body.push; changes .filter(this.isNewBranch) .forEach(change => { const data = { ...body, change, }; const meta = this.generateMeta({ headers, change, }); this.$emit(data, meta); }); }, }, }; <|start_filename|>components/shopify/sources/new-cancelled-order/new-cancelled-order.js<|end_filename|> const shopify = require("../../shopify.app.js"); module.exports = { key: "shopify-new-cancelled-order", name: "New Cancelled Order", description: "Emits an event each time a new order is cancelled.", version: "0.0.3", dedupe: "unique", props: { db: "$.service.db", timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 15, }, }, shopify, }, methods: { _getLastUpdatedDate() { return this.db.get("last_updated_at") || null; }, _setLastUpdatedDate(date) { this.db.set("last_updated_at", date); }, }, async run() { const lastUpdatedAt = this._getLastUpdatedDate(); let results = await this.shopify.getOrders( "any", true, null, lastUpdatedAt, "cancelled", ); for (const order of results) { this.$emit(order, { id: order.id, summary: `Order cancelled: ${order.name}`, ts: Date.parse(order.updated_at), }); } if (results[results.length - 1]) { this._setLastUpdatedDate(results[results.length - 1].updated_at); } }, }; <|start_filename|>components/eventbrite/actions/get-event-summary/get-event-summary.js<|end_filename|> const eventbrite = require("../../eventbrite.app"); module.exports = { key: "eventbrite-get-event-summary", name: "Get Event Summary", description: "Get event summary for a specified event.", version: "0.0.1", type: "action", props: { eventbrite, eventId: { propDefinition: [ eventbrite, "eventId", ], }, }, async run() { const { summary } = await this.eventbrite.getEvent(this.eventId); return summary; }, }; <|start_filename|>components/slack/actions/remove_star/remove_star.js<|end_filename|> const slack = require("../../slack.app.js"); module.exports = { key: "slack-remove-star", name: "Remove Star", description: "Remove a star from an item on behalf of the authenticated user", version: "0.0.1", type: "action", props: { slack, conversation: { propDefinition: [ slack, "conversation", ], optional: true, }, timestamp: { propDefinition: [ slack, "timestamp", ], optional: true, }, file: { propDefinition: [ slack, "file", ], optional: true, }, }, async run() { return await this.slack.sdk().stars.remove({ conversation: this.conversation, timestamp: this.timestamp, file: this.file, }); }, }; <|start_filename|>components/zoom/zoom.app.js<|end_filename|> module.exports = { type: "app", app: "zoom", }; <|start_filename|>components/bandwidth/sources/new-incoming-sms/new-incoming-sms.js<|end_filename|> const bandwidth = require("../../bandwidth.app"); module.exports = { name: "New Incoming SMS", description: "Emits an event each time a `message-received` event is received at the source url", key: "bandwidth-new-incoming-sms", version: "1.1.0", props: { bandwidth, http: { type: "$.interface.http", customResponse: true, }, }, async run(event) { const messageBody = event.body[0]; this.http.respond({ status: 204, }); if (messageBody.message.direction == "in") { this.$emit(messageBody, { summary: "Message Received", id: messageBody.message.id, ts: +new Date(messageBody.time), }); } }, }; <|start_filename|>components/webflow/sources/new-form-submission/new-form-submission.js<|end_filename|> const common = require("../common"); module.exports = { ...common, key: "webflow-new-form-submission", name: "New Form Submission (Instant)", description: "Emit an event when a new form is submitted", version: "0.0.1", dedupe: "unique", methods: { ...common.methods, getWebhookTriggerType() { return "form_submission"; }, generateMeta(data) { const { _id: id, d: date, } = data; const summary = "New form submission"; const ts = Date.parse(date); return { id, summary, ts, }; }, }, }; <|start_filename|>examples/timer-interface-cron.js<|end_filename|> module.exports = { name: "Cron Example", version: "0.1", props: { timer: { type: "$.interface.timer", default: { cron: "0 0 * * *", // Run job once a day }, }, }, async run() { console.log("hello world!"); }, }; <|start_filename|>components/github/sources/common-polling.js<|end_filename|> const github = require("../github.app.js"); module.exports = { props: { github, timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 5, }, }, db: "$.service.db", }, methods: { async getFilteredNotifications(params, reason) { const notifications = await this.github.getNotifications(params); return notifications.filter( (notification) => notification.reason === reason ); }, }, }; <|start_filename|>components/twist/sources/new-channel/new-channel.js<|end_filename|> const twist = require("../../twist.app.js"); const common = require("../common.js"); module.exports = { ...common, name: "New Channel (Instant)", version: "0.0.1", key: "twist-new-channel", description: "Emits an event for any new channel added in a workspace", methods: { getHookActivationData() { return { target_url: this.http.endpoint, event: "channel_added", workspace_id: this.workspace, }; }, getMeta(body) { const { id, name, created_ts } = body; return { id, summary: name, ts: Date.parse(created_ts), }; }, }, }; <|start_filename|>components/cliniko/package.json<|end_filename|> { "name": "@pipedream/cliniko", "version": "0.0.1", "description": "Pipedream Cliniko Components", "main": "cliniko.app.js", "keywords": [ "pipedream", "cliniko" ], "homepage": "https://pipedream.com/apps/cliniko", "author": "<NAME> <<EMAIL>> (https://ageuphealth.com.au/)", "license": "MIT", "dependencies": { "@pipedreamhq/platform": "^0.8.1" }, "publishConfig": { "access": "public" } } <|start_filename|>components/github/sources/new-repository/new-repository.js<|end_filename|> const common = require("../common-polling.js"); module.exports = { ...common, key: "github-new-repository", name: "New Repository", description: "Emit new events when new repositories are created", version: "0.0.4", type: "source", dedupe: "last", methods: { generateMeta(data) { const ts = new Date(data.created_at).getTime(); return { id: data.id, summary: data.full_name, ts, }; }, }, async run() { let since = this.db.get("since"); const repos = await this.github.getRepos({ sort: "created", direction: "asc", since, }); let maxDate = since; for (const repo of repos) { if (!maxDate || new Date(repo.created_at) > new Date(maxDate)) { maxDate = repo.created_at; } const meta = this.generateMeta(repo); this.$emit(repo, meta); since = repo.created_at; } this.db.set("since", since); }, }; <|start_filename|>components/stack_exchange/sources/new-question-for-keywords/new-question-for-keywords.js<|end_filename|> const stack_exchange = require('../../stack_exchange.app'); module.exports = { key: 'stack_exchange-new-question-for-specific-keywords', name: 'New Question for Specific Keywords', description: 'Emits an event when a new question is posted and related to a set of specific keywords', version: '0.0.2', dedupe: 'unique', props: { stack_exchange, db: '$.service.db', siteId: {propDefinition: [stack_exchange, 'siteId']}, keywords: {propDefinition: [stack_exchange, 'keywords']}, timer: { type: '$.interface.timer', default: { intervalSeconds: 60 * 15, // 15 minutes }, }, }, hooks: { async activate() { const fromDate = this._getCurrentEpoch(); this.db.set('fromDate', fromDate); }, }, methods: { _getCurrentEpoch() { // The StackExchange API works with Unix epochs in seconds. return Math.floor(Date.now() / 1000); }, generateMeta(data) { const {question_id: id, creation_date: ts, title} = data; const summary = `New question: ${title}`; return { id, summary, ts, }; }, }, async run() { const fromDate = this.db.get('fromDate'); const toDate = this._getCurrentEpoch(); const keywordsQuery = this.keywords.join(','); const searchParams = { fromDate, toDate, sort: 'creation', order: 'asc', closed: false, site: this.siteId, q: keywordsQuery, }; const items = this.stack_exchange.advancedSearch(searchParams); for await (const item of items) { const meta = this.generateMeta(item); this.$emit(item, meta); } this.db.set('fromDate', toDate); }, }; <|start_filename|>components/twist/sources/new-event/new-event.js<|end_filename|> const twist = require("../../twist.app.js"); const common = require("../common.js"); module.exports = { ...common, name: "New Event (Instant)", version: "0.0.1", key: "twist-new-event", description: "Emits an event for any new updates in a workspace", props: { ...common.props, channel: { propDefinition: [twist, "channel", (c) => ({ workspace: c.workspace })], }, thread: { propDefinition: [twist, "thread", (c) => ({ channel: c.channel })], }, eventType: { propDefinition: [twist, "eventType"], }, }, methods: { getHookActivationData() { return { target_url: this.http.endpoint, event: this.eventType, workspace_id: this.workspace, channel_id: this.channel, thread_id: this.thread, }; }, getMeta(body) { const { name, id, created } = body; return { id, summary: name || "New Event", ts: Date.parse(created), }; }, }, }; <|start_filename|>components/todoist/sources/common-task.js<|end_filename|> const todoist = require("../todoist.app.js"); const common = require("./common.js"); module.exports = { ...common, props: { ...common.props, selectProjects: { propDefinition: [todoist, "selectProjects"] }, }, methods: { ...common.methods, isElementRelevant() { return true; }, }, async run(event) { const syncResult = await this.todoist.syncItems(this.db); Object.values(syncResult) .filter(Array.isArray) .flat() .filter(this.isElementRelevant) .filter((element) => this.todoist.isProjectInList(element.project_id, this.selectProjects) ) .forEach((element) => { element.summary = `Task: ${element.id}`; const meta = this.generateMeta(element); this.$emit(element, meta); }); }, }; <|start_filename|>components/mercury/mercury.app.js<|end_filename|> const axios = require("axios"); module.exports = { type: "app", app: "mercury", propDefinitions: { account: { type: "string", label: "Account", async options() { const results = await this.getAccounts(); const options = results.map((result) => { const { name, id } = result; return { label: name, value: id }; }); return options; }, }, }, methods: { _getBaseURL() { return "https://backend.mercury.com/api/v1"; }, _getHeaders() { return { Authorization: `Bearer ${this.$auth.api_key}`, "Content-Type": "application/json", }; }, async _makeRequest(method, endpoint, params = null) { const config = { method, url: `${this._getBaseURL()}${endpoint}`, headers: this._getHeaders(), params, }; return (await axios(config)).data; }, daysAgo(days) { const daysAgo = new Date(); daysAgo.setDate(daysAgo.getDate() - days); return daysAgo; }, async getAccounts() { return (await this._makeRequest("GET", "/accounts")).accounts; }, async getTransactions(accountId, params) { return await this._makeRequest( "GET", `/account/${accountId}/transactions`, params ); }, }, }; <|start_filename|>components/slack/actions/list-channels/list-channels.js<|end_filename|> const slack = require("../../slack.app.js"); module.exports = { key: "slack-list-channels", name: "List Channels", description: "Return a list of all channels in a workspace", version: "0.0.1", type: "action", props: { slack, }, async run() { return await this.slack.sdk().conversations.list(); }, }; <|start_filename|>docs/docs/.vuepress/enhanceApp.js<|end_filename|> import VueGtm from "vue-gtm"; export default ({ Vue, // the version of Vue being used in the VuePress app options, // the options for the root Vue instance router, // the router instance for the app siteData, // site metadata }) => { if (typeof window !== "undefined") { Vue.use(VueGtm, { id: "GTM-KBDH3DB", enabled: true, debug: false, vueRouter: router, }); } router.addRoutes([ { path: "/cron", redirect: "/workflows/steps/triggers" }, { path: "/notebook", redirect: "/workflows/steps" }, { path: "/workflows/fork", redirect: "/workflows/copy" }, { path: "/notebook/fork", redirect: "/workflows/copy" }, { path: "/notebook/inspector/", redirect: "/workflows/events/inspect/" }, { path: "/notebook/destinations/s3/", redirect: "/destinations/s3/" }, { path: "/notebook/destinations/sse/", redirect: "/destinations/sse/" }, { path: "/notebook/destinations/snowflake/", redirect: "/destinations/snowflake/", }, { path: "/notebook/destinations/http/", redirect: "/destinations/http/" }, { path: "/notebook/destinations/email/", redirect: "/destinations/email/" }, { path: "/notebook/destinations/", redirect: "/destinations/" }, { path: "/notebook/code/", redirect: "/workflows/steps/code/" }, { path: "/notebook/observability/", redirect: "/workflows/events/inspect/", }, { path: "/notebook/actions/", redirect: "/workflows/steps/actions/" }, { path: "/notebook/sources/", redirect: "/workflows/steps/triggers/" }, { path: "/notebook/sql/", redirect: "/destinations/triggers/" }, { path: "/what-is-pipedream/", redirect: "/" }, { path: "/docs/apps/all-apps", redirect: "https://pipedream.com/apps", }, ]); }; <|start_filename|>interfaces/timer/examples/code.js<|end_filename|> console.log("Node code"); <|start_filename|>components/webflow/sources/new-ecomm-order/new-ecomm-order.js<|end_filename|> const common = require("../common"); module.exports = { ...common, key: "webflow-new-ecomm-order", name: "New E-commerce Order (Instant)", description: "Emit an event when an e-commerce order is created", version: "0.0.1", methods: { ...common.methods, getWebhookTriggerType() { return "ecomm_new_order"; }, generateMeta(data) { const { acceptedOn, orderId: id, } = data; const summary = `New e-comm order: ${id}`; const ts = Date.parse(acceptedOn); return { id, summary, ts, }; }, }, }; <|start_filename|>components/calendly/calendly.app.js<|end_filename|> const axios = require("axios"); module.exports = { type: "app", app: "calendly", methods: { _getAuthHeader() { return { "X-TOKEN": this.$auth.api_key, }; }, _getBaseURL() { return "https://calendly.com/api/v1"; }, monthAgo() { const now = new Date(); const monthAgo = new Date(now.getTime()); monthAgo.setMonth(monthAgo.getMonth() - 1); return Date.parse(monthAgo); }, async getEventTypes() { return ( await axios.get(`${this._getBaseURL()}/users/me/event_types`, { headers: this._getAuthHeader(), }) ).data.data; }, async getEvents() { return ( await axios.get(`${this._getBaseURL()}/users/me/events`, { headers: this._getAuthHeader(), }) ).data.data; }, async createHook(data) { const config = { method: "post", url: `${this._getBaseURL()}/hooks`, headers: this._getAuthHeader(), data, }; return await axios(config); }, async deleteHook(hookId) { const config = { method: "delete", url: `${this._getBaseURL()}/hooks/${hookId}`, headers: this._getAuthHeader(), }; await axios(config); }, }, }; <|start_filename|>components/slack/actions/create-channel/create-channel.js<|end_filename|> const slack = require("../../slack.app.js"); module.exports = { key: "slack-create-channel", name: "Create a Channel", description: "Create a new channel", version: "0.0.2", type: "action", props: { slack, channelName: { label: "Channel name", description: "Name of the public or private channel to create", type: "string", }, isPrivate: { label: "Is private?", type: "boolean", description: "`false` by default. Pass `true` to create a private channel instead of a public one.", default: false, optional: true, }, }, async run() { return await this.slack.sdk().conversations.create({ name: this.channelName, is_private: this.isPrivate, }); }, }; <|start_filename|>components/activecampaign/sources/campaign-starts-sending/campaign-starts-sending.js<|end_filename|> const activecampaign = require("../../activecampaign.app.js"); const common = require("../common-webhook.js"); module.exports = { ...common, name: "Campaign Starts Sending (Instant)", key: "activecampaign-campaign-starts-sending", description: "Emits an event each time a campaign starts sending.", version: "0.0.1", methods: { ...common.methods, getEvents() { return ["sent"]; }, getMeta(body) { const { date_time: dateTimeIso } = body; const ts = Date.parse(dateTimeIso); return { id: body["campaign[id]"], summary: body["campaign[name]"], ts }; }, }, }; <|start_filename|>components/bitbucket/sources/new-commit/new-commit.js<|end_filename|> const get = require("lodash/get"); const common = require("../../common"); const { bitbucket } = common.props; const EVENT_SOURCE_NAME = "New Commit (Instant)"; module.exports = { ...common, name: EVENT_SOURCE_NAME, key: "bitbucket-new-commit", description: "Emits an event when a new commit is pushed to a branch", version: "0.0.2", props: { ...common.props, repositoryId: { propDefinition: [ bitbucket, "repositoryId", c => ({ workspaceId: c.workspaceId }), ], }, branchName: { propDefinition: [ bitbucket, "branchName", c => ({ workspaceId: c.workspaceId, repositoryId: c.repositoryId, }), ], }, }, methods: { ...common.methods, getEventSourceName() { return EVENT_SOURCE_NAME; }, getHookEvents() { return [ "repo:push", ]; }, getHookPathProps() { return { workspaceId: this.workspaceId, repositoryId: this.repositoryId, }; }, isEventForThisBranch(change) { const expectedChangeTypes = new Set([ "branch", "named_branch", ]); if (change.new) { const { name, type } = change.new; return name === this.branchName && expectedChangeTypes.has(type); } return false; }, doesEventContainNewCommits(change) { return change.commits && change.commits.length > 0; }, getBaseCommitHash(change) { return get(change, [ "old", "target", "hash", ]); }, generateMeta(commit) { const { hash, message, date, } = commit; const commitTitle = message .split("\n") .shift(); const summary = `New commit: ${commitTitle} (${hash})`; const ts = +new Date(date); return { id: hash, summary, ts, }; }, async processEvent(event) { const { body } = event; const { changes = [] } = body.push; // Push events can be for different branches, tags and // causes. We need to make sure that we're only processing events // that are related to new commits in the particular branch // that the user indicated. const newCommitsInThisBranch = changes .filter(this.isEventForThisBranch) .filter(this.doesEventContainNewCommits); const isEventRelevant = newCommitsInThisBranch.length > 0; if (!isEventRelevant) { return; } // BitBucket events provide information about the state // of an entity before it was changed. // Based on that, we can extract the HEAD commit of // the relevant branch before new commits were pushed to it. const lastProcessedCommitHash = newCommitsInThisBranch .map(this.getBaseCommitHash) .shift(); // The event payload contains some commits but it's not exhaustive, // so we need to explicitly fetch them just in case. const opts = { workspaceId: this.workspaceId, repositoryId: this.repositoryId, branchName: this.branchName, lastProcessedCommitHash, }; const allCommits = this.bitbucket.getCommits(opts); // We need to collect all the relevant commits, sort // them in reverse order (since the BitBucket API sorts them // from most to least recent) and emit an event for each // one of them. const allCommitsCollected = []; for await (const commit of allCommits) { allCommitsCollected.push(commit); }; allCommitsCollected.reverse().forEach(commit => { const meta = this.generateMeta(commit) this.$emit(commit, meta); }); }, }, }; <|start_filename|>components/twitter/sources/watch-retweets-of-user-tweet/watch-retweets-of-user-tweet.js<|end_filename|> const base = require("../common/tweets"); const baseRetweets = require("../watch-retweets-of-my-tweet/watch-retweets-of-my-tweet"); module.exports = { ...baseRetweets, key: "twitter-watch-retweets-of-user-tweet", name: "Watch Retweets of User Tweet", description: "Emit an event when a specific Tweet from a user is retweeted", version: "0.0.1", props: { ...base.props, screen_name: { propDefinition: [ base.props.twitter, "screen_name", ], }, tweetId: { type: "string", label: "Tweet", description: "The Tweet to watch for retweets", options(context) { return this.tweetIdOptions(context); }, }, }, methods: { ...baseRetweets.methods, getScreenName() { return this.screen_name; }, }, }; <|start_filename|>components/activecampaign/sources/new-event/new-event.js<|end_filename|> const activecampaign = require("../../activecampaign.app.js"); const common = require("../common-webhook.js"); module.exports = { ...common, name: "New Event (Instant)", key: "activecampaign-new-event", description: "Emits an event for the specified event type from ActiveCampaign.", version: "0.0.1", props: { ...common.props, eventType: { propDefinition: [activecampaign, "eventType"] }, }, methods: { ...common.methods, getEvents() { return [this.eventType]; }, getMeta(body) { const { date_time: dateTimeIso } = body; const ts = Date.parse(dateTimeIso); return { id: body.date_time, summary: `${body.type} initiated by ${body.initiated_by}`, ts }; }, }, }; <|start_filename|>examples/http.js<|end_filename|> module.exports = { name: "HTTP Example", version: "0.0.1", props: { http: { type: "$.interface.http", customResponse: true, }, }, async run(event) { this.http.respond({ status: 200, body: { "msg": "hello world!", }, headers: { "content-type": "application/json", }, }); console.log(event); }, }; <|start_filename|>components/calendly/sources/new-event-type/new-event-type.js<|end_filename|> const common = require("../common-polling.js"); const get = require("lodash/get"); module.exports = { ...common, key: "calendly-new-event-type", name: "New Event Type", description: "Emits an event for each new event type", version: "0.0.2", dedupe: "unique", methods: { ...common.methods, async getResults() { return await this.calendly.getEventTypes(); }, isRelevant(eventType, lastEvent) { const createdAt = Date.parse(get(eventType, "attributes.created_at")); return createdAt > lastEvent; }, generateMeta({ id, attributes }) { return { id, summary: attributes.name, ts: Date.now(), }; }, }, }; <|start_filename|>components/twitter/actions/retweet/retweet.js<|end_filename|> const twitter = require("../../twitter.app.js"); module.exports = { key: "twitter-retweet", name: "Retweet a tweet", description: "Retweets a specific tweet by ID", version: "0.0.1", type: "action", props: { twitter, tweetID: { propDefinition: [ twitter, "tweetID", ], description: "The numerical ID of the tweet you'd like to retweet", }, }, async run() { return await this.twitter.retweet({ tweetID: this.tweetID, }); }, }; <|start_filename|>components/twitch/sources/common-polling.js<|end_filename|> const common = require("./common.js"); module.exports = { ...common, props: { ...common.props, timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 15, }, }, }, methods: { ...common.methods, getLastEvent(lastEvent) { return lastEvent ? new Date(lastEvent) : new Date(); }, }, }; <|start_filename|>components/datadog/sources/new-monitor-event/new-monitor-event.js<|end_filename|> const datadog = require("../../datadog.app"); const payloadFormat = require("../payload-format"); module.exports = { key: "datadog-new-monitor-event", name: "New Monitor Event (Instant)", description: "Captures events emitted by a Datadog monitor", dedupe: "unique", version: "0.0.1", props: { datadog, db: "$.service.db", http: { type: "$.interface.http", customResponse: true, }, monitors: { type: "string[]", label: "Monitors", description: "The monitors to observe for notifications", optional: true, async options(context) { const { page } = context; const pageSize = 10; const monitors = await this.datadog.listMonitors(page, pageSize); const options = monitors.map(monitor => ({ label: monitor.name, value: monitor.id, })); return { options, }; }, }, }, hooks: { async activate() { const { name: webhookName, secretKey: webhookSecretKey, } = await this.datadog.createWebhook( this.http.endpoint, payloadFormat, ); console.log(`Created webhook "${webhookName}"`); this.db.set("webhookName", webhookName); this.db.set("webhookSecretKey", webhookSecretKey); await Promise.all( this.monitors.map(monitorId => this.datadog.addWebhookNotification(webhookName, monitorId) ) ); }, async deactivate() { const webhookName = this.db.get("webhookName"); await this.datadog.removeWebhookNotifications(webhookName); await this.datadog.deleteWebhook(webhookName); }, }, methods: { generateMeta(data) { const { id, eventTitle: summary, date: ts, } = data; return { id, summary, ts, }; }, }, async run(event) { const webhookSecretKey = this.db.get("webhookSecretKey"); if (!this.datadog.isValidSource(event, webhookSecretKey)) { console.log(`Skipping event from unrecognized source`); this.http.respond({ status: 404, }); return; } // Acknowledge the event back to Datadog. this.http.respond({ status: 200, }); const { body } = event; const meta = this.generateMeta(body); this.$emit(body, meta); }, }; <|start_filename|>components/bandwidth/actions/send-sms/send-sms.js<|end_filename|> const bandwidth = require("../../bandwidth.app.js"); module.exports = { key: "bandwidth-send-sms", name: "Send SMS", description: "Send an SMS message using Bandwidth's Messaging API", type: "action", version: "1.0.0", props: { bandwidth, messageTo: { propDefinition: [ bandwidth, "messageTo", ], }, from: { propDefinition: [ bandwidth, "from", ], }, message: { propDefinition: [ bandwidth, "message", ], }, messagingApplicationId: { propDefinition: [ bandwidth, "messagingApplicationId", ], }, }, async run () { const response = await this.bandwidth.sendSms( this.messageTo, this.from, this.message, this.messagingApplicationId, ); console.log("Status Code:", response.statusCode); console.log("Message ID:", response.result.id); return response; }, }; <|start_filename|>components/hubspot/sources/new-task/new-task.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, key: "hubspot-new-task", name: "New Calendar Task", description: "Emits an event for each new task added.", version: "0.0.2", dedupe: "unique", hooks: {}, methods: { ...common.methods, generateMeta(task) { const { id, name, eventType } = task; return { id, summary: `${name} - ${eventType}`, ts: Date.now(), }; }, }, async run(event) { const yearFromNow = new Date(); yearFromNow.setFullYear(yearFromNow.getFullYear() + 1); const results = await this.hubspot.getCalendarTasks(yearFromNow.getTime()); for (const task of results) { const meta = this.generateMeta(task); this.$emit(task, meta); } }, }; <|start_filename|>components/google_drive/google_drive.app.js<|end_filename|> const axios = require("axios"); const { google } = require("googleapis"); const { uuid } = require("uuidv4"); const { GOOGLE_DRIVE_UPDATE_TYPES, MY_DRIVE_VALUE, WEBHOOK_SUBSCRIPTION_EXPIRATION_TIME_MILLISECONDS, } = require("./constants"); const { isMyDrive, getDriveId, } = require("./utils"); module.exports = { type: "app", app: "google_drive", propDefinitions: { watchedDrive: { type: "string", label: "Drive", description: "The drive you want to watch for changes", async options({ prevContext }) { const { nextPageToken } = prevContext; return this._listDriveOptions(nextPageToken); }, }, updateTypes: { type: "string[]", label: "Types of updates", description: `The types of updates you want to watch for on these files. [See Google's docs] (https://developers.google.com/drive/api/v3/push#understanding-drive-api-notification-events).`, // https://developers.google.com/drive/api/v3/push#understanding-drive-api-notification-events default: GOOGLE_DRIVE_UPDATE_TYPES, options: GOOGLE_DRIVE_UPDATE_TYPES, }, watchForPropertiesChanges: { type: "boolean", label: "Watch for changes to file properties", description: `Watch for changes to [file properties](https://developers.google.com/drive/api/v3/properties) in addition to changes to content. **Defaults to \`false\`, watching for only changes to content**.`, optional: true, default: false, }, }, methods: { // Static methods isMyDrive, getDriveId, // Returns a drive object authenticated with the user's access token drive() { const auth = new google.auth.OAuth2(); auth.setCredentials({ access_token: this.$auth.oauth_access_token, }); return google.drive({ version: "v3", auth, }); }, // Google's push notifications provide a URL to the resource that changed, // which we can use to fetch the file's metadata. So we use axios here // (vs. the Node client) to get that. async getFileMetadata(url) { return ( await axios({ method: "GET", headers: { Authorization: `Bearer ${this.$auth.oauth_access_token}`, }, url, }) ).data; }, /** * This method yields a list of changes that occurred to files in a * particular Google Drive. It is a wrapper around [the `drive.changes.list` * API](https://bit.ly/2SGb5M2) but defined as a generator to enable lazy * loading of multiple pages. * * @typedef {object} ChangesPage * @property {object[]} changedFiles - the list of file changes, as [defined * by the API](https://bit.ly/3h7WeUa). This list filters out any result * that is not a proper object. * @property {string} nextPageToken - the page token [returned by the last API * call](https://bit.ly/3h7WeUa). **Note that this generator keeps track of * this token internally, and the purpose of this value is to provide a way * for consumers of this method to handle checkpoints in case of an * unexpected halt.** * * @param {string} [pageToken] - the token for continuing a previous list * request on the next page. This must be a token that was previously * returned by this same method. * @param {string} [driveId] - the shared drive from which changes are * returned * @yields * @type {ChangesPage} */ async *listChanges(pageToken, driveId) { const drive = this.drive(); let changeRequest = { pageToken, pageSize: 1000, }; // As with many of the methods for Google Drive, we must // pass a request of a different shape when we're requesting // changes for My Drive (null driveId) vs. a shared drive if (driveId) { changeRequest = { ...changeRequest, driveId, includeItemsFromAllDrives: true, supportsAllDrives: true, }; } while (true) { const { data } = await drive.changes.list(changeRequest); const { changes = [], newStartPageToken, nextPageToken, } = data; // Some changes do not include an associated file object. Return only // those that do const changedFiles = changes .map((change) => change.file) .filter((f) => typeof f === "object"); yield { changedFiles, nextPageToken: nextPageToken || newStartPageToken, }; if (newStartPageToken) { // The 'newStartPageToken' field is only returned as part of the last // page from the API response: https://bit.ly/3jBEvWV break; } changeRequest.pageToken = nextPageToken; } }, async getPageToken(driveId) { const drive = this.drive(); const request = driveId ? { driveId, supportsAllDrives: true, } : {}; const { data } = await drive.changes.getStartPageToken(request); return data.startPageToken; }, checkHeaders(headers, subscription, channelID) { if ( !headers["x-goog-resource-state"] || !headers["x-goog-resource-id"] || !headers["x-goog-resource-uri"] || !headers["x-goog-message-number"] ) { console.log("Request missing necessary headers: ", headers); return false; } const incomingChannelID = headers["x-goog-channel-id"]; if (incomingChannelID !== channelID) { console.log( `Channel ID of ${incomingChannelID} not equal to deployed component channel of ${channelID}`, ); return false; } if (headers["x-goog-resource-id"] !== subscription.resourceId) { console.log( `Resource ID of ${subscription.resourceId} not currently being tracked. Exiting`, ); return false; } return true; }, /** * A utility method around [the `drive.drives.list` * API](https://bit.ly/3AiWE1x) but scoped to a specific page of the API * response * * @typedef {object} DriveListPage - an object representing a page that * lists GDrive drives, as defined by [the API](https://bit.ly/3jwxbvy) * * @param {string} [pageToken] - the page token for the next page of shared * drives * @param {number} [pageSize=10] - the number of records to retrieve as part * of the page * * @returns * @type {DriveListPage} */ async listDrivesInPage(pageToken, pageSize = 10) { const drive = this.drive(); const { data } = await drive.drives.list({ pageSize, pageToken, }); return data; }, /** * This method yields the visible GDrive drives of the authenticated * account. It is a wrapper around [the `drive.drives.list` * API](https://bit.ly/3AiWE1x) but defined as a generator to enable lazy * loading of multiple pages. * * @typedef {object} Drive - an object representing a GDrive drive, as * defined by [the API](https://bit.ly/3ycifGY) * * @yields * @type {Drive} */ async *listDrives() { let pageToken; while (true) { const { drives = [], nextPageToken, } = await this.listDrivesInPage(pageToken); for (const drive in drives) { yield drive; } if (!nextPageToken) { // The 'nextPageToken' field is only returned when there's still // comments to be retrieved (i.e. when the end of the list has not // been reached yet): https://bit.ly/3jwxbvy break; } pageToken = nextPageToken; } }, async _listDriveOptions(pageToken) { const { drives, nextPageToken, } = await this.listDrivesInPage(pageToken); // "My Drive" isn't returned from the list of drives, so we add it to the // list and assign it a static ID that we can refer to when we need. We // only do this during the first page of options (i.e. when `pageToken` is // undefined). const options = pageToken !== undefined ? [] : [ { label: "My Drive", value: MY_DRIVE_VALUE, }, ]; for (const d of drives) { options.push({ label: d.name, value: d.id, }); } return { options, context: { nextPageToken, }, }; }, /** * A utility method around [the `drive.files.list` * API](https://bit.ly/366CFVN) but scoped to a specific page of the API * response * * @typedef {object} FileListPage - an object representing a page that lists * GDrive files, as defined by [the API](https://bit.ly/3xdbAwc) * * @param {string} [pageToken] - the page token for the next page of shared * drives * @param {object} [extraOpts = {}] - an object containing extra/optional * parameters to be fed to the GDrive API call, as defined in [the API * docs](https://bit.ly/3AnQDR1) * * @returns * @type {FileListPage} */ async listFilesInPage(pageToken, extraOpts = {}) { const drive = this.drive(); const { data } = await drive.files.list({ pageToken, ...extraOpts, }); return data; }, /** * A utility method around [the `drive.files.list` * API](https://bit.ly/366CFVN) but scoped to a specific page of the API * response, and intended to be used as a way for prop definitions to return * a list of options. * * @param {string} [pageToken] - the page token for the next page of shared * drives * @param {object} [extraOpts = {}] - an object containing extra/optional * parameters to be fed to the GDrive API call, as defined in [the API * docs](https://bit.ly/3AnQDR1) * * @returns a list of prop options */ async listFilesOptions(pageToken, extraOpts = {}) { const { files, nextPageToken, } = await this.listFilesInPage(pageToken, extraOpts); const options = files.map((file) => ({ label: file.name, value: file.id, })); return { options, context: { nextPageToken, }, }; }, /** * Method returns a list of folder options * * @param {string} [pageToken] - the page token for the next page of shared * drives * @param {object} [opts = {}] - an object containing extra/optional * parameters to be fed to the GDrive API call, as defined in [the API * docs](https://bit.ly/3AnQDR1) * * @returns a list of prop options */ async listFolderOptions(pageToken, opts = {}) { return await this.listFilesOptions(pageToken, { ...opts, q: "mimeType = 'application/vnd.google-apps.folder'", }); }, /** * Creates a new file in a drive * * @param {object} [opts = {}] - an object containing parameters to be fed to the GDrive * API call as defined in [the API docs](https://developers.google.com/drive/api/v3/reference/files/create) * * @returns a files resource */ async createFile(opts = {}) { const drive = this.drive(); return (await drive.files.create(opts)).data; }, /** * This method yields comments made to a particular GDrive file. It is a * wrapper around [the `drive.comments.list` API](https://bit.ly/2UjYajv) * but defined as a generator to enable lazy loading of multiple pages. * * @typedef {object} Comment - an object representing a comment in a GDrive * file, as defined by [the API](https://bit.ly/3htAd12) * * @yields * @type {Comment} */ async *listComments(fileId, startModifiedTime = null) { const drive = this.drive(); const opts = { fileId, fields: "*", pageSize: 100, }; if (startModifiedTime !== null) { opts.startModifiedTime = new Date(startModifiedTime).toISOString(); } while (true) { const { data } = await drive.comments.list(opts); const { comments = [], nextPageToken, } = data; for (const comment of comments) { yield comment; } if (!nextPageToken) { // The 'nextPageToken' field is only returned when there's still // comments to be retrieved (i.e. when the end of the list has not // been reached yet): https://bit.ly/3w9ru9m break; } opts.pageToken = nextPageToken; } }, _makeWatchRequestBody(id, address) { const expiration = Date.now() + WEBHOOK_SUBSCRIPTION_EXPIRATION_TIME_MILLISECONDS; return { id, // the component-specific channel ID, a UUID type: "web_hook", address, // the component-specific HTTP endpoint expiration, }; }, async watchDrive(id, address, pageToken, driveId) { const drive = this.drive(); const requestBody = this._makeWatchRequestBody(id, address); let watchRequest = { pageToken, requestBody, }; // Google expects an entirely different object to be passed // when you make a watch request for My Drive vs. a shared drive // "My Drive" doesn't have a driveId, so if this method is called // without a driveId, we make a watch request for My Drive if (driveId) { watchRequest = { ...watchRequest, driveId, includeItemsFromAllDrives: true, supportsAllDrives: true, }; } // When watching for changes to an entire account, we must pass a pageToken, // which points to the moment in time we want to start watching for changes: // https://developers.google.com/drive/api/v3/manage-changes const { expiration, resourceId, } = ( await drive.changes.watch(watchRequest) ).data; console.log(`Watch request for drive successful, expiry: ${expiration}`); return { expiration: parseInt(expiration), resourceId, }; }, async watchFile(id, address, fileId) { const drive = this.drive(); const requestBody = this._makeWatchRequestBody(id, address); const { expiration, resourceId, } = ( await drive.files.watch({ fileId, requestBody, supportsAllDrives: true, }) ).data; console.log( `Watch request for file ${fileId} successful, expiry: ${expiration}`, ); return { expiration: parseInt(expiration), resourceId, }; }, async stopNotifications(id, resourceId) { // id = channelID // See https://github.com/googleapis/google-api-nodejs-client/issues/627 const drive = this.drive(); // If for some reason the channel doesn't exist, this throws an error // It's OK for this to fail in those cases, since we'll renew the channel // immediately after trying to stop it if we still want notifications, // so we squash the error, log it, and move on. try { await drive.channels.stop({ resource: { id, resourceId, }, }); console.log(`Stopped push notifications on channel ${id}`); } catch (err) { console.error( `Failed to stop channel ${id} for resource ${resourceId}: ${err}`, ); } }, async getFile(fileId) { const drive = this.drive(); return ( await drive.files.get({ fileId, fields: "*", supportsAllDrives: true, }) ).data; }, async getDrive(driveId) { const drive = this.drive(); return ( await drive.drives.get({ driveId, }) ).data; }, async activateHook(channelID, url, drive) { const startPageToken = await this.getPageToken(); const { expiration, resourceId, } = await this.watchDrive( channelID, url, startPageToken, drive, ); return { startPageToken, expiration, resourceId, }; }, async deactivateHook(channelID, resourceId) { if (!channelID) { console.log( "Channel not found, cannot stop notifications for non-existent channel", ); return; } if (!resourceId) { console.log( "No resource ID found, cannot stop notifications for non-existent resource", ); return; } await this.stopNotifications(channelID, resourceId); }, async invokedByTimer(drive, subscription, url, channelID, pageToken) { const newChannelID = channelID || uuid(); const driveId = this.getDriveId(drive); const newPageToken = pageToken || await this.getPageToken(driveId); const { expiration, resourceId, } = await this.checkResubscription( subscription, newChannelID, newPageToken, url, drive, ); return { newChannelID, newPageToken, expiration, resourceId, }; }, async checkResubscription( subscription, channelID, pageToken, endpoint, drive, ) { const driveId = this.getDriveId(drive); if (subscription && subscription.resourceId) { console.log( `Notifications for resource ${subscription.resourceId} are expiring at ${subscription.expiration}. Stopping existing sub`, ); await this.stopNotifications(channelID, subscription.resourceId); } const { expiration, resourceId, } = await this.watchDrive( channelID, endpoint, pageToken, driveId, ); return { expiration, resourceId, }; }, }, }; <|start_filename|>components/gorgias/gorgias.app.js<|end_filename|> // Gorgias app file module.exports = { type: "app", app: "gorgias", } <|start_filename|>components/slack/actions/upload-file/upload-file.js<|end_filename|> const slack = require("../../slack.app.js"); module.exports = { key: "slack-upload-file", name: "Upload File", description: "Upload a file", version: "0.0.1", type: "action", props: { slack, content: { propDefinition: [ slack, "content", ], }, initial_comment: { propDefinition: [ slack, "initial_comment", ], optional: true, }, conversation: { propDefinition: [ slack, "conversation", ], }, }, async run() { return await this.slack.sdk().files.upload({ content: this.content, channel: this.conversation, initial_comment: this.initial_comment, }); }, }; <|start_filename|>components/rss/rss.app.js<|end_filename|> module.exports = { type: 'app', app: 'rss', } <|start_filename|>components/eventbrite/sources/common/webhook.js<|end_filename|> const common = require("./base.js"); const get = require("lodash/get"); module.exports = { ...common, props: { ...common.props, http: "$.interface.http", }, hooks: { ...common.hooks, async activate() { const data = { actions: this.getActions(), endpoint_url: this.http.endpoint, }; const { id } = await this.eventbrite.createHook(this.organization, data); this._setHookId(id); }, async deactivate() { const id = this._getHookId("hookId"); await this.eventbrite.deleteHook(id); }, }, methods: { ...common.methods, getData() { throw new Error("getData is not implemented"); }, _getHookId() { return this.db.get("hookId"); }, _setHookId(hookId) { this.db.set("hookId", hookId); }, }, async run(event) { const url = get(event, "body.api_url"); if (!url) return; const resource = await this.eventbrite.getResource(url); const data = await this.getData(resource); this.emitEvent(data); }, }; <|start_filename|>components/docusign/actions/create-signature-request/create-signature-request.js<|end_filename|> const docusign = require("../../docusign.app.js"); module.exports = { key: "docusign-create-signature-request", name: "Create Signature Request", description: "Creates a signature request from a template", version: "0.0.1", type: "action", props: { docusign, account: { propDefinition: [ docusign, "account", ], }, template: { propDefinition: [ docusign, "template", (c) => ({ account: c.account, }), ], }, emailSubject: { propDefinition: [ docusign, "emailSubject", ], }, emailBlurb: { propDefinition: [ docusign, "emailBlurb", ], }, recipientEmail: { propDefinition: [ docusign, "recipientEmail", ], }, recipientName: { propDefinition: [ docusign, "recipientName", ], }, role: { propDefinition: [ docusign, "role", (c) => ({ account: c.account, template: c.template, }), ], }, }, async run() { const baseUri = await this.docusign.getBaseUri(this.account); const data = { status: "sent", templateId: this.template, templateRoles: [ { roleName: this.role, name: this.recipientName, email: this.recipientEmail, }, ], emailSubject: this.emailSubject, }; if (this.emailBlurb) data.emailBlurb = this.emailBlurb; try { return await this.docusign.createEnvelope(baseUri, data); } catch (err) { throw new Error(err.message); } }, }; <|start_filename|>components/docusign/sources/envelope-sent-or-complete/envelope-sent-or-complete.js<|end_filename|> const docusign = require("../../docusign.app.js"); module.exports = { key: "docusign-envelope-sent-or-complete", name: "Envelope Sent or Complete", description: "Emits an event when an envelope status is set to sent or complete", version: "0.0.2", dedupe: "unique", props: { docusign, db: "$.service.db", timer: { type: "$.interface.timer", default: { intervalSeconds: 60 * 15, }, }, account: { propDefinition: [ docusign, "account", ], }, status: { type: "string[]", label: "Status", description: "The envelope status that you are checking for", options: [ "sent", "completed", ], default: [ "sent", ], }, }, methods: { _getLastEvent() { return this.db.get("lastEvent"); }, _setLastEvent(lastEvent) { this.db.set("lastEvent", lastEvent); }, monthAgo() { const monthAgo = new Date(); monthAgo.setMonth(monthAgo.getMonth() - 1); return monthAgo; }, generateMeta({ envelopeId: id, emailSubject: summary, status, }, ts) { return { id: `${id}${status}`, summary, ts, }; }, }, async run(event) { const { timestamp: ts } = event; const lastEvent = this._getLastEvent() || this.monthAgo().toISOString(); const baseUri = await this.docusign.getBaseUri(this.account); let done = false; const params = { from_date: lastEvent, status: this.status.join(), }; do { const { envelopes = [], nextUri, endPosition, } = await this.docusign.listEnvelopes(baseUri, params); if (nextUri) params.start_position += endPosition + 1; else done = true; for (const envelope of envelopes) { const meta = this.generateMeta(envelope, ts); this.$emit(envelope, meta); } } while (!done); this._setLastEvent(new Date(ts * 1000).toISOString()); }, }; <|start_filename|>components/hubspot/sources/new-company/new-company.js<|end_filename|> const common = require("../common.js"); module.exports = { ...common, key: "hubspot-new-company", name: "New Companies", description: "Emits an event for each new company added.", version: "0.0.2", dedupe: "unique", hooks: {}, methods: { ...common.methods, generateMeta(company) { const { id, properties, createdAt } = company; const ts = Date.parse(createdAt); return { id, summary: properties.name, ts, }; }, isRelevant(company, createdAfter) { return Date.parse(company.createdAt) > createdAfter; }, }, async run(event) { const createdAfter = this._getAfter(); const data = { limit: 100, sorts: [ { propertyName: "createdate", direction: "DESCENDING", }, ], object: "companies", }; await this.paginate( data, this.hubspot.searchCRM.bind(this), "results", createdAfter ); this._setAfter(Date.now()); }, }; <|start_filename|>components/netlify/netlify.app.js<|end_filename|> const axios = require("axios"); const crypto = require("crypto"); const jwt = require('jwt-simple'); const NetlifyAPI = require("netlify"); const parseLinkHeader = require('parse-link-header'); module.exports = { type: "app", app: "netlify", propDefinitions: { siteId: { type: "string", label: "Site ID", description: "The site for which events must be captured", async options(context) { // At the moment we need to "manually" query these items // instead of using the Netlify client, since it doesn't support // pagination. const url = this._sitesEndpoint(); const params = { per_page: 10, }; const { data, next } = await this._propDefinitionsOptions(url, params, context); const options = data.map(site => ({ label: site.name, value: site.id, })); return { options, context: { nextPage: next, }, }; }, }, }, methods: { _apiUrl() { return "https://api.netlify.com/api/v1"; }, _sitesEndpoint() { const baseUrl = this._apiUrl(); return `${baseUrl}/sites`; }, _authToken() { return this.$auth.oauth_access_token; }, _makeRequestConfig() { const authToken = this._authToken(); const headers = { "Authorization": `Bearer ${authToken}`, "User-Agent": "@PipedreamHQ/pipedream v0.1", }; return { headers, }; }, async _propDefinitionsOptions(url, params, { page, prevContext }) { let requestConfig = this._makeRequestConfig(); // Basic axios request config if (page === 0) { // First time the options are being retrieved. // Include the parameters provided, which will be persisted // across the different pages. requestConfig = { ...requestConfig, params, }; } else if (prevContext.nextPage) { // Retrieve next page of options. url = prevContext.nextPage.url; } else { // No more options available. return { data: [] }; } const { data, headers } = await axios.get(url, requestConfig); // https://docs.netlify.com/api/get-started/#link-header const { next } = parseLinkHeader(headers.link); return { data, next, }; }, generateToken() { return crypto.randomBytes(32).toString("hex"); }, createClient() { const opts = { userAgent: "@PipedreamHQ/pipedream v0.1", pathPrefix: "/api/v1", accessToken: this._authToken(), }; return new NetlifyAPI(opts); }, async createHook(opts) { const { event, url, siteId, } = opts; const token = this.generateToken(); const hookOpts = { type: "url", event, data: { url, signature_secret: token, }, }; const requestParams = { site_id: siteId, body: hookOpts, }; const netlifyClient = this.createClient(); const { id } = await netlifyClient.createHookBySiteId(requestParams); console.log( `Created "${event}" webhook for site ID ${siteId}. (Hook ID: ${id}, endpoint: ${url})` ); return { hookId: id, token, }; }, async deleteHook(opts) { const { hookId, siteId } = opts; const requestParams = { hook_id: hookId, }; const netlifyClient = this.createClient(); await netlifyClient.deleteHook(requestParams); console.log( `Deleted webhook for site ID ${siteId}. (Hook ID: ${hookId})` ); }, isValidSource(headers, bodyRaw, db) { // Verifies that the event is really coming from Netlify. // See https://docs.netlify.com/site-deploys/notifications/#payload-signature const signature = headers["x-webhook-signature"]; const token = db.get("token"); const { sha256 } = jwt.decode(signature, token); const encoded = crypto .createHash('sha256') .update(bodyRaw) .digest('hex'); return sha256 === encoded; }, }, }; <|start_filename|>components/ringcentral/sources/common/base.js<|end_filename|> const ringcentral = require("../../ringcentral.app"); module.exports = { props: { ringcentral, db: "$.service.db", }, methods: { /** * Given a phone number, return a masked version of it. The purpose of a * masked number is to avoid exposing it to an unintended audience. * * Example: * * - Input: +16505551234 * - Output: ########1234 * * @param {string} number The phone number to mask * @return {string} The masked phone number */ getMaskedNumber(number) { const { length: numberLength } = number; return number .slice(numberLength - 4) .padStart(numberLength, "#"); }, generateMeta() { throw new Error("generateMeta is not implemented"); }, processEvent() { throw new Error("processEvent is not implemented"); }, }, }; <|start_filename|>components/eventbrite/actions/create-event/create-event.js<|end_filename|> const eventbrite = require("../../eventbrite.app"); const locales = require("../locales.js"); module.exports = { key: "eventbrite-create-event", name: "Create Event", description: "Create a new Eventbrite event", version: "0.0.1", type: "action", props: { eventbrite, organization: { propDefinition: [ eventbrite, "organization", ], }, name: { type: "string", label: "Name", description: "Event name. Value cannot be empty nor whitespace", }, summary: { type: "string", label: "Summary", description: "Event summary. This is a plaintext field and will have any supplied HTML removed from it. Maximum of 140 characters", optional: true, }, timezone: { propDefinition: [ eventbrite, "timezone", ], }, startTime: { type: "string", label: "Start Time", description: "The event start time relative to UTC. (Ex. 2018-05-12T02:00:00Z).", }, endTime: { type: "string", label: "End Time", description: "The event end time relative to UTC. (Ex. 2018-05-12T02:00:00Z)", }, hideStartDate: { type: "boolean", label: "Hide Start Date", description: "Whether the start date should be hidden. Defaults to false if left blank.", optional: true, }, hideEndDate: { type: "boolean", label: "Hide End Date", description: "Whether the end date should be hidden. Defaults to false if left blank.", optional: true, }, currency: { type: "string", label: "Currency", description: "The ISO 4217 currency code for this event", default: "USD", }, onlineEvent: { type: "boolean", label: "Online Event", description: "If this event doesn't have a venue and is only held online. Defaults to false if left blank.", optional: true, }, organizerId: { type: "string", label: "Organizer ID", description: "ID of the event organizer", optional: true, }, logoId: { type: "string", label: "Logo ID", description: "Image ID of the event logo", optional: true, }, venueId: { type: "string", label: "Venue ID", description: "Event venue ID", optional: true, }, formatId: { type: "string", label: "Format ID", description: "Event format", optional: true, }, categoryId: { type: "string", label: "Category ID", description: "Event category", optional: true, }, subcategoryId: { type: "string", label: "Subcategory ID", description: "Event subcategory (US only)", optional: true, }, listed: { type: "boolean", label: "Listed", description: "Is this event publicly searchable on Eventbrite? Defaults to true.", default: true, }, shareable: { type: "boolean", label: "Shareable", description: "Can this event show social sharing buttons? Defaults to false if left blank.", optional: true, }, inviteOnly: { type: "boolean", label: "Invite Only", description: "Can only people with invites see the event page?. Defaults to false if left blank.", optional: true, }, showRemaining: { type: "boolean", label: "Show Remaining", description: "If the remaining number of tickets is publicly visible on the event page. Defaults to false if left blank.", optional: true, }, password: { type: "string", label: "Password", description: "Password needed to see the event in unlisted mode", optional: true, }, capacity: { type: "integer", label: "Capacity", description: "Set specific capacity (if omitted, sums ticket capacities)", optional: true, }, isReservedSeating: { type: "boolean", label: "Is Reserved Seating", description: "If the event is reserved seating. Defaults to false if left blank.", optional: true, }, isSeries: { type: "boolean", label: "Is Series", description: "If the event is part of a series. Specifying this attribute as True during event creation will always designate the event as a series parent, never as a series occurrence. Series occurrences must be created through the schedules API and cannot be created using the events API. Defaults to false if left blank.", optional: true, }, showPickASeat: { type: "boolean", label: "Show Pick A Seat", description: "For reserved seating event, if attendees can pick their seats. Defaults to false if left blank.", optional: true, }, showSeatmapThumbnail: { type: "boolean", label: "Show Seatmap Thumbnail", description: "For reserved seating event, if venue map thumbnail visible on the event page. Defaults to false if left blank.", optional: true, }, showColorsInSeatmapThumbnail: { type: "boolean", label: "Show Colors In Seatmap Thumbnail", description: "For reserved seating event, if venue map thumbnail should have colors on the event page. Defaults to false if left blank.", optional: true, }, source: { type: "string", label: "Source", description: "Source of the event (defaults to API)", optional: true, }, locale: { type: "string", label: "Locale", description: "Indicates event language on Event's listing page. Language options from Eventbrite documentation: https://www.eventbrite.com/platform/api#/reference/event/retrieve/create-an-event", options: locales, default: "en_US", }, }, async run() { /* convert start and end time to UTC in case time was entered with timezone offset */ const startTime = (new Date(this.startTime)).toISOString() .split(".")[0] + "Z"; const endTime = (new Date(this.endTime)).toISOString() .split(".")[0] + "Z"; let data = { event: { name: { html: this.name, }, summary: this.summary, start: { timezone: this.timezone, utc: startTime, }, end: { timezone: this.timezone, utc: endTime, }, hide_start_date: this.hideStartDate, hide_end_date: this.hideEndDate, currency: this.currency, online_event: this.onlineEvent, organizer_id: this.organizerId, logo_id: this.logoId, venue_id: this.venueId, format_id: this.formatId, category_id: this.categoryId, subcategory_id: this.subcategoryId, listed: this.listed, shareable: this.shareable, invite_only: this.inviteOnly, show_remaining: this.showRemaining, password: <PASSWORD>, capacity: this.capacity, is_reserved_seating: this.isReservedSeating, is_series: this.isSeries, show_pick_a_seat: this.showPickASeat, show_seatmap_thumbnail: this.showSeatmapThumbnail, show_colors_in_seatmap_thumbnail: this.showColorsInSeatmapThumbnail, source: this.source, locale: this.locale, }, }; data = JSON.parse(JSON.stringify(data)); return await this.eventbrite.createEvent(this.organization, data); }, };
saikrishna169/pipedream
<|start_filename|>app/assets/javascripts/modules/teams/index.js<|end_filename|> import Vue from 'vue'; import TeamsIndexPage from './pages/index'; import TeamsShowPage from './pages/show'; $(() => { if (!$('body[data-controller="teams"]').length) { return; } // eslint-disable-next-line no-new new Vue({ el: '.vue-root', components: { TeamsIndexPage, TeamsShowPage, }, }); }); <|start_filename|>spec/javascripts/utils/comparator.spec.js<|end_filename|> import Comparator from '~/utils/comparator'; describe('Comparator', () => { it('returns string comparator function', () => { expect(Comparator.of('string').name).toBe('stringComparator'); }); it('returns number comparator function', () => { expect(Comparator.of(1).name).toBe('numberComparator'); }); it('returns date comparator function', () => { expect(Comparator.of(new Date()).name).toBe('dateComparator'); }); it('returns string comparator function by default', () => { expect(Comparator.of(null).name).toBe('stringComparator'); }); describe('string comparator', () => { const comparator = Comparator.of('string'); it('returns -1 if string a < b', () => { expect(comparator('a', 'b')).toBe(-1); }); it('returns 0 if string a = b', () => { expect(comparator('a', 'a')).toBe(0); }); it('returns 1 if string a > b', () => { expect(comparator('b', 'a')).toBe(1); }); }); describe('number comparator', () => { const comparator = Comparator.of(1); it('returns a negative number if a < b', () => { expect(comparator(1, 2)).toBeLessThanOrEqual(0); }); it('returns 0 if number a = b', () => { expect(comparator(1, 1)).toBe(0); }); it('returns a positive number > 0 if a > b', () => { expect(comparator(2, 1)).toBeGreaterThanOrEqual(0); }); }); describe('date comparator', () => { const comparator = Comparator.of(new Date()); it('returns a negative number if date a < b', () => { const date1 = new Date('December 16, 1995 03:24:00'); const date2 = new Date('December 17, 1995 03:24:00'); expect(comparator(date1, date2)).toBeLessThanOrEqual(0); }); it('returns 0 if date a = b', () => { const date1 = new Date('December 17, 1995 03:24:00'); const date2 = new Date('December 17, 1995 03:24:00'); expect(comparator(date1, date2)).toBe(0); }); it('returns a positive number if date a > b', () => { const date1 = new Date('December 18, 1995 03:24:00'); const date2 = new Date('December 17, 1995 03:24:00'); expect(comparator(date1, date2)).toBeGreaterThanOrEqual(0); }); }); }); <|start_filename|>app/assets/javascripts/plugins/unauthenticated.js<|end_filename|> import Vue from 'vue'; import Alert from '~/plugins/alert'; Vue.use(Alert); <|start_filename|>app/assets/javascripts/modules/webhooks/index.js<|end_filename|> import Vue from 'vue'; import WebhooksIndexPage from './pages/index'; import WebhooksShowPage from './pages/show'; $(() => { if (!$('body[data-controller="webhooks"]').length) { return; } // eslint-disable-next-line no-new new Vue({ el: '.vue-root', components: { WebhooksIndexPage, WebhooksShowPage, }, }); }); <|start_filename|>spec/javascripts/modules/repositories/delete-tag-action.spec.js<|end_filename|> import { mount } from '@vue/test-utils'; import DeleteTagAction from '~/modules/repositories/components/tags/delete-tag-action'; import sinon from 'sinon'; describe('delete-tag-action', () => { let wrapper; beforeEach(() => { wrapper = mount(DeleteTagAction, { propsData: { state: { selectedTags: [], }, }, mocks: { $bus: { $emit: sinon.spy(), }, }, }); }); it('shows nothing if no tag is selected', () => { expect(wrapper.find('.label').exists()).toBe(false); }); it('shows label in singular if only one tag is selected', () => { wrapper.setProps({ state: { selectedTags: [{}] } }); expect(wrapper.text()).toBe('Delete tag'); }); it('shows label in plural if more than one tag is selected', () => { wrapper.setProps({ state: { selectedTags: [{}, {}] } }); expect(wrapper.text()).toBe('Delete tags'); }); it('shows label in plural if more a tag with multiple labels is selected', () => { wrapper.setProps({ state: { selectedTags: [{ multiple: true }] } }); expect(wrapper.text()).toBe('Delete tags'); }); it('emits deleteTags event if clicked', () => { wrapper.setProps({ state: { selectedTags: [{}] } }); wrapper.find('.btn').trigger('click'); expect(wrapper.vm.$bus.$emit.calledWith('deleteTags')).toBe(true); }); }); <|start_filename|>app/assets/javascripts/modules/dashboard/pages/dashboard.js<|end_filename|> import BaseComponent from '~/base/component'; import TabbedWidget from '../components/tabbed_widget'; const TAB_WIDGET = '#sidebar-tabs'; class DashboardPage extends BaseComponent { elements() { this.$widget = this.$el.find(TAB_WIDGET); } mount() { this.tabbedWidget = new TabbedWidget(this.$widget); } } export default DashboardPage; <|start_filename|>spec/javascripts/modules/repositories/vulnerabilities-parser.spec.js<|end_filename|> import VulnerabilitiesParser from '~/modules/repositories/services/vulnerabilities-parser'; describe('VulnerabilitiesParser', () => { describe('#countBySeverities', () => { const emptyVulnerabilities = []; const vulnerabilities = [ { severity: 'Critical' }, { severity: 'High' }, { severity: 'High' }, { severity: 'Medium' }, { severity: 'Low' }, { severity: 'Low' }, { severity: 'Negligible' }, ]; const severitiesNames = ['Defcon1', 'Critical', 'High', 'Medium', 'Low', 'Unknown', 'Negligible']; it('returns object with severities categories', () => { const severities = VulnerabilitiesParser.countBySeverities(vulnerabilities); expect(Object.keys(severities)).toEqual(severitiesNames); }); it('returns object with severities zero', () => { const severities = VulnerabilitiesParser.countBySeverities(emptyVulnerabilities); severitiesNames.forEach((s) => { expect(severities[s]).toBe(0); }); }); it('counts vulnerabilities by category', () => { const severities = VulnerabilitiesParser.countBySeverities(vulnerabilities); expect(severities.Critical).toBe(1); expect(severities.High).toBe(2); expect(severities.Medium).toBe(1); expect(severities.Low).toBe(2); expect(severities.Unknown).toBe(0); expect(severities.Negligible).toBe(1); }); }); }); <|start_filename|>app/assets/javascripts/utils/comparator.js<|end_filename|> import dateutil from '~/utils/date'; const stringComparator = (a, b) => a.localeCompare(b); const numberComparator = (a, b) => a - b; const dateComparator = (a, b) => new Date(a) - new Date(b); function of(value) { let type = typeof value; if (dateutil.isISO8601(value)) { type = 'date'; } switch (type) { case 'boolean': case 'number': return numberComparator; case 'date': return dateComparator; default: return stringComparator; } } export default { of, }; <|start_filename|>app/assets/javascripts/utils/alert.js<|end_filename|> const ALERT_ELEMENT = '#float-alert'; const TEXT_ALERT_ELEMENT = '#float-alert p'; const HIDE_TIMEOUT = 5000; const STORAGE_KEY = 'portus.alerts.schedule'; const storage = window.localStorage; const $show = (text, autohide = true, timeout = HIDE_TIMEOUT) => { $(TEXT_ALERT_ELEMENT).html(text); $(ALERT_ELEMENT).fadeIn(); if (autohide) { setTimeout(() => $(ALERT_ELEMENT).fadeOut(), timeout); } }; const scheduledMessages = () => JSON.parse(storage.getItem(STORAGE_KEY)) || []; const storeMessages = messages => storage.setItem(STORAGE_KEY, JSON.stringify(messages)); // the idea is to simulate the alert that is showed after a redirect // e.g.: something happened that requires a page reload/redirect and // we need to show this info to the user. const $schedule = (text) => { const messages = scheduledMessages(); messages.push(text); storeMessages(messages); }; const $process = () => { const messages = scheduledMessages(); messages.forEach(m => $show(m, false)); storage.clear(STORAGE_KEY); }; export default { $show, $schedule, $process, }; <|start_filename|>app/assets/javascripts/modules/webhooks/services/webhooks.js<|end_filename|> import Vue from 'vue'; import VueResource from 'vue-resource'; Vue.use(VueResource); const customActions = { toggleEnabled: { method: 'PUT', url: 'namespaces/{namespaceId}/webhooks/{id}/toggle_enabled.json', }, }; const oldResource = Vue.resource('namespaces/{namespaceId}/webhooks{/id}.json', {}, customActions); function destroy(namespaceId, id) { return oldResource.delete({ namespaceId, id }); } function save(namespaceId, webhook) { return oldResource.save({ namespaceId }, { webhook }); } function toggleEnabled(namespaceId, id) { return oldResource.toggleEnabled({ namespaceId, id }, {}); } function update(namespaceId, webhook) { return oldResource.update({ namespaceId, id: webhook.id }, { webhook }); } export default { destroy, save, toggleEnabled, update, }; <|start_filename|>app/assets/javascripts/unauthenticated.js<|end_filename|> // Bootstrap import 'bootstrap/js/tooltip'; // misc import './plugins/unauthenticated'; import './polyfill'; // modules import './modules/explore'; import './modules/users/unauthenticated'; import './bootstrap'; <|start_filename|>app/assets/javascripts/modules/teams/service.js<|end_filename|> import Vue from 'vue'; import VueResource from 'vue-resource'; Vue.use(VueResource); const customActions = { teamTypeahead: { method: 'GET', url: 'teams/typeahead/{teamName}', }, }; const membersCustomActions = { memberTypeahead: { method: 'GET', url: 'teams/{teamId}/typeahead/{name}', }, }; const resource = Vue.resource('api/v1/teams{/id}', {}, customActions); const membersResource = Vue.resource('api/v1/teams{/teamId}/members{/id}', {}, membersCustomActions); function all(params = {}) { return resource.get({}, params); } function get(id) { return resource.get({ id }); } function save(team) { return resource.save({}, team); } function update(team) { return resource.update({ id: team.id }, { team }); } function remove(id, params) { return resource.delete({ id }, params); } function searchTeam(teamName, options = {}) { const params = Object.assign({ teamName }, options); return resource.teamTypeahead(params); } function exists(value, options) { return searchTeam(value, options) .then((response) => { const collection = response.data; if (Array.isArray(collection)) { return collection.some(e => e.name === value); } // some unexpected response from the api, // leave it for the back-end validation return null; }) .catch(() => null); } function searchMember(teamId, name) { return membersResource.memberTypeahead({ teamId, name }); } function destroyMember(member) { const teamId = member.team_id; const { id } = member; return membersResource.delete({ teamId, id }); } function updateMember(member, role) { const teamId = member.team_id; const { id } = member; return membersResource.update({ teamId, id }, { role }); } function saveMember(teamId, member) { return membersResource.save({ teamId }, member); } function memberExists(teamId, value) { return searchMember(teamId, value) .then((response) => { const collection = response.data; if (Array.isArray(collection)) { return collection.some(e => e.name === value); } // some unexpected response from the api, // leave it for the back-end validation return null; }) .catch(() => null); } export default { get, all, save, update, remove, exists, searchMember, destroyMember, updateMember, saveMember, memberExists, }; <|start_filename|>app/assets/javascripts/modules/tags/index.js<|end_filename|> import Vue from 'vue'; import TagsShowPage from './pages/show'; $(() => { if (!$('body[data-controller="tags"]').length) { return; } // eslint-disable-next-line no-new new Vue({ el: '.vue-root', components: { TagsShowPage, }, }); }); <|start_filename|>spec/javascripts/shared/toggle-link.spec.js<|end_filename|> import { mount } from '@vue/test-utils'; import ToggleLink from '~/shared/components/toggle-link'; describe('toggle-link', () => { let wrapper; beforeEach(() => { wrapper = mount(ToggleLink, { propsData: { state: { key: false, }, stateKey: 'key', text: '', }, }); }); it('shows the passed text', () => { wrapper.setProps({ text: 'Text xD' }); expect(wrapper.html()).toContain('Text xD'); }); it('changes the state on user click', () => { wrapper.find('.btn').trigger('click'); expect(wrapper.vm.state.key).toBe(true); }); it('shows `trueIcon` when state is true', () => { const icon = wrapper.find('.fa'); wrapper.setProps({ trueIcon: 'fa-true', state: { key: true }, }); expect(icon.classes()).toContain('fa-true'); }); it('shows `falseIcon` when state is false', () => { const icon = wrapper.find('.fa'); wrapper.setProps({ falseIcon: 'fa-false', state: { key: false }, }); expect(icon.classes()).toContain('fa-false'); }); it('changes icon when state changes', () => { const icon = wrapper.find('.fa'); wrapper.setProps({ trueIcon: 'fa-true', falseIcon: 'fa-false', state: { key: false }, }); expect(icon.classes()).toContain('fa-false'); wrapper.find('.btn').trigger('click'); expect(icon.classes()).toContain('fa-true'); }); }); <|start_filename|>app/assets/javascripts/modules/repositories/index.js<|end_filename|> import Vue from 'vue'; import RepositoriesIndexPage from './pages/index'; import RepositoriesShowPage from './pages/show'; $(() => { if (!$('body[data-controller="repositories"]').length) { return; } // eslint-disable-next-line no-new new Vue({ el: '.vue-root', components: { RepositoriesIndexPage, RepositoriesShowPage, }, }); }); <|start_filename|>app/assets/javascripts/modules/namespaces/mixins/visibility.js<|end_filename|> export default { props: ['namespace'], data() { return { onGoingRequest: false, }; }, computed: { isPrivate() { return this.namespace.visibility === 'private'; }, isProtected() { return this.namespace.visibility === 'protected'; }, isPublic() { return this.namespace.visibility === 'public'; }, canChangeVibisility() { return this.namespace.permissions.visibility && !this.onGoingRequest; }, privateTitle() { if (this.namespace.global) { return 'The global namespace cannot be private'; } return 'Team members can pull images from this namespace'; }, }, }; <|start_filename|>app/assets/javascripts/utils/effects.js<|end_filename|> // after jquery was upgraded this effect was conflicting // with lifeitup functions (probably layout_resizer) // so setTimeout was the workaround I found to solve the error export const fadeIn = function ($el) { setTimeout(() => { $el.hide().fadeIn(1000); }, 0); }; // openCloseIcon toggles the state of the given icon with the // 'fa-pencil'/'fa-close' classes. export const openCloseIcon = function (icon) { if (icon.hasClass('fa-close')) { icon.removeClass('fa-close'); icon.addClass('fa-pencil'); } else { icon.removeClass('fa-pencil'); icon.addClass('fa-close'); } }; // refreshFloatAlertPosition updates the position of a floating alert on scroll. export const refreshFloatAlertPosition = function () { var box = $('.float-alert'); if ($(this).scrollTop() < 60) { box.css('top', (72 - $(this).scrollTop()) + 'px'); } $(window).scroll(() => { if ($(this).scrollTop() > 60) { box.css('top', '12px'); } else { box.css('top', (72 - $(this).scrollTop()) + 'px'); } }); }; // setTimeoutAlertDelay sets up the delay for hiding an alert. // IDEA: if alerts are put into a component, this hack will no longer be needed. export const setTimeOutAlertDelay = function () { setTimeout(() => { $('.alert-hide').click(); }, 4000); }; export default { fadeIn, openCloseIcon, refreshFloatAlertPosition, setTimeOutAlertDelay, }; <|start_filename|>spec/javascripts/modules/repositories/tag.spec.js<|end_filename|> import { mount } from '@vue/test-utils'; import Tag from '~/modules/repositories/components/tags/tag'; import sinon from 'sinon'; describe('tag', () => { let wrapper; const commandToPull = 'docker pull localhost:5000/opensuse/portus:latest'; beforeEach(() => { wrapper = mount(Tag, { propsData: { // not real data but the one used in the component tag: { name: 'latest', }, repository: { registry_hostname: 'localhost:5000', full_name: 'opensuse/portus', }, }, mocks: { $alert: { $show: sinon.spy(), }, }, }); }); it('shows tag name', () => { expect(wrapper.find('.label').text()).toBe('latest'); }); it('computes command to pull properly', () => { expect(wrapper.vm.commandToPull).toBe(commandToPull); }); it('copies command to pull to the clipboard', () => { // document in test env doesn't have execCommand document.execCommand = sinon.spy(); wrapper.find('.label').trigger('click'); expect(document.execCommand.calledWith('copy')).toBe(true); }); it('calls $alert plugin notifying user', () => { const message = 'Copied pull command to clipboard'; wrapper.find('.label').trigger('click'); expect(wrapper.vm.$alert.$show.calledWith(message)).toBe(true); }); }); <|start_filename|>app/assets/javascripts/modules/repositories/services/vulnerabilities-parser.js<|end_filename|> const countBySeverities = function (vulnerabilities) { const severities = { Defcon1: 0, Critical: 0, High: 0, Medium: 0, Low: 0, Unknown: 0, Negligible: 0, }; if (vulnerabilities) { vulnerabilities.forEach((vul) => { severities[vul.severity] += 1; }); } return severities; }; export default { countBySeverities, }; <|start_filename|>app/assets/javascripts/modules/users/service.js<|end_filename|> import Vue from 'vue'; import VueResource from 'vue-resource'; Vue.use(VueResource); const customActions = { createToken: { method: 'POST', url: 'api/v1/users/{userId}/application_tokens', }, destroyToken: { method: 'DELETE', url: 'api/v1/users/application_tokens/{id}', }, }; const oldCustomActions = { toggleAdmin: { method: 'PUT', url: 'admin/users/{id}/toggle_admin', }, toggleEnabled: { method: 'PUT', url: 'toggle_enabled/{id}', }, }; const resource = Vue.resource('api/v1/users{/id}', {}, customActions); const oldResource = Vue.resource('admin/users{/id}', {}, oldCustomActions); function createToken(userId, appToken) { return resource.createToken({ userId }, appToken); } function destroyToken(id) { return resource.destroyToken({ id }); } function save(user) { return oldResource.save({}, { user }); } function update(user) { return resource.update({ id: user.id }, { user }); } function destroy({ id }) { return resource.delete({ id }); } function toggleAdmin({ id }) { return oldResource.toggleAdmin({ id }, {}); } function toggleEnabled({ id }) { return oldResource.toggleEnabled({ id }, {}); } export default { save, destroy, update, toggleAdmin, toggleEnabled, createToken, destroyToken, }; <|start_filename|>app/assets/javascripts/utils/csrf.js<|end_filename|> const token = () => { const tokenEl = document.querySelector('meta[name=csrf-token]'); if (tokenEl !== null) { return tokenEl.getAttribute('content'); } return null; }; export default { token, }; <|start_filename|>app/assets/javascripts/modules/dashboard/index.js<|end_filename|> import SearchComponent from './components/search'; import DashboardPage from './pages/dashboard'; const DASHBOARD_INDEX = 'dashboard/index'; $(() => { const $body = $('body'); const route = $body.data('route'); // Enable the search component globally if the HTML code is there. if ($('#search').length > 0) { // eslint-disable-next-line new SearchComponent($body); } if (route === DASHBOARD_INDEX) { // eslint-disable-next-line new DashboardPage($body); } }); <|start_filename|>spec/javascripts/utils/date.spec.js<|end_filename|> import DateUtil from '~/utils/date'; describe('DateUtil', () => { it('returns false if it\'s not a valid date string/object', () => { expect(DateUtil.isISO8601('asdasd')).toBe(false); expect(DateUtil.isISO8601(null)).toBe(false); expect(DateUtil.isISO8601('2018-222-222')).toBe(false); expect(DateUtil.isISO8601('')).toBe(false); expect(DateUtil.isISO8601('20180205T173027Z')).toBe(false); }); it('returns true if it\'s a valid date string/object', () => { expect(DateUtil.isISO8601('2018-07-20T18:14:43.000Z')).toBe(true); expect(DateUtil.isISO8601('2018-07-20T18:14:43Z')).toBe(true); expect(DateUtil.isISO8601('2018-02-05T17:14Z')).toBe(true); }); }); <|start_filename|>app/assets/javascripts/modules/users/index.js<|end_filename|> import Vue from 'vue'; import DisableAccountPanel from './components/disable-account-panel'; import AppTokensWrapper from './components/application-tokens/wrapper'; import UsersIndexPage from './pages/index'; import UsersEditPage from './pages/edit'; import LegacyUsersEditPage from './pages/legacy/edit'; const USERS_SELF_EDIT_ROUTE = 'auth/registrations/edit'; $(() => { const $body = $('body'); const route = $body.data('route'); const controller = $body.data('controller'); if (controller === 'admin/users' || route === USERS_SELF_EDIT_ROUTE) { // eslint-disable-next-line no-new new Vue({ el: '.vue-root', components: { AppTokensWrapper, DisableAccountPanel, UsersEditPage, UsersIndexPage, }, mounted() { // eslint-disable-next-line new LegacyUsersEditPage($body); }, }); } }); <|start_filename|>app/assets/javascripts/bootstrap.js<|end_filename|> import Vue from 'vue'; import dayjs from 'dayjs'; import relativeTime from 'dayjs/plugin/relativeTime'; import Alert from './utils/alert'; import { setTimeOutAlertDelay, refreshFloatAlertPosition } from './utils/effects'; dayjs.extend(relativeTime); $(function () { // this is a fallback to always instantiate a vue instance // useful for isolated shared components like <sign-out-btn> // eslint-disable-next-line no-underscore-dangle if (!$('.vue-root')[0].__vue__) { // eslint-disable-next-line no-new new Vue({ el: '.vue-root' }); } if ($.fn.popover) { $('a[rel~=popover], .has-popover').popover(); } if ($.fn.tooltip) { $('a[rel~=tooltip], .has-tooltip').tooltip(); } $('.alert .close').on('click', function () { $(this).closest('.alert-wrapper').fadeOut(); }); // process scheduled alerts Alert.$process(); refreshFloatAlertPosition(); // disable effects during tests $.fx.off = $('body').data('disable-effects'); }); // necessary to be compatible with the js rendered // on the server-side via jquery-ujs window.setTimeOutAlertDelay = setTimeOutAlertDelay; window.refreshFloatAlertPosition = refreshFloatAlertPosition; // we are not a SPA and when user clicks on back/forward // we want the page to be fully reloaded to take advantage of // the url query params state window.onpopstate = function (e) { // phantomjs seems to trigger an oppopstate event // when visiting pages, e.state is always null and // in our component we set an empty string if (e.state !== null) { window.location.reload(); } }; Vue.config.productionTip = process.env.NODE_ENV !== 'production'; <|start_filename|>vendor/assets/javascripts/lifeitup_layout.js<|end_filename|> /* eslint-disable max-len, vars-on-top */ // to render the layout correctly in every browser/screen var alreadyResizing = false; window.$ = window.jQuery; window.layout_resizer = function layout_resizer() { alreadyResizing = true; var screenHeight = $(window).height(); var headerHeight = $('header').outerHeight(); var footerHeight = $('footer').outerHeight(); var asideHeight = $('aside ul').outerHeight(); var sectionHeight = $('section').outerHeight(); if ((headerHeight + footerHeight + asideHeight) > screenHeight && asideHeight > sectionHeight) { $('.container-fluid').css({ height: asideHeight + 'px', }); } else if ((headerHeight + footerHeight + sectionHeight) > screenHeight && asideHeight < sectionHeight) { $('.container-fluid').css({ height: sectionHeight + 'px', }); } else { $('.container-fluid').css({ height: screenHeight - headerHeight - footerHeight + 'px', }); } alreadyResizing = false; }; $(window).on('load', function () { layout_resizer(); }); $(window).on('resize', function () { layout_resizer(); }); $(document).bind('DOMSubtreeModified', function () { if (!alreadyResizing) { layout_resizer(); } }); // triger the function to resize and to get the images size when a panel has been displayed $(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function () { layout_resizer(); }); // BOOTSTRAP INITS $(function () { if ($.fn.popover) { $('body').popover({ selector: '[data-toggle="popover"]', trigger: 'focus', }); // to destroy the popovers that are hidden $('[data-toggle="popover"]').on('hidden.bs.popover', function () { var popover = $('.popover').not('.in'); if (popover) { popover.remove(); } }); } }); // init tooltip $(function () { if ($.fn.tooltip) { $('[data-toggle="tooltip"]').tooltip(); } }); // Hide alert box instead of closing it $(document).on('click', '.alert-hide', function () { $(this).parent().parent().fadeOut(); }); <|start_filename|>spec/javascripts/modules/teams/form.spec.js<|end_filename|> import { mount } from '@vue/test-utils'; import Vue from 'vue'; import Vuelidate from 'vuelidate'; import sinon from 'sinon'; import NewTeamForm from '~/modules/teams/components/new-form'; Vue.use(Vuelidate); describe('new-team-form', () => { let wrapper; const submitButton = () => wrapper.find('button[type="submit"]'); const teamNameInput = () => wrapper.find('#team_name'); beforeEach(() => { wrapper = mount(NewTeamForm, { propsData: { isAdmin: false, currentUserId: 0, owners: [{}], }, mocks: { $bus: { $emit: sinon.spy(), }, }, }); }); context('when current user is admin', () => { beforeEach(() => { wrapper.setProps({ isAdmin: true, }); }); it('shows owner select field', () => { expect(wrapper.text()).toContain('Owner'); }); }); context('when current user is not admin', () => { beforeEach(() => { wrapper.setProps({ isAdmin: false, }); }); it('hides owner select field', () => { expect(wrapper.text()).not.toContain('Owner'); }); }); it('disables submit button if form is invalid', () => { expect(submitButton().attributes().disabled).toBe('disabled'); }); it('enables submit button if form is valid', () => { // there's a custom validation the involves a Promise and an ajax request. // this was the simpler way to bypass that validation. // tried to stub/mock/fake with sinon but wasn't able to make it work. // another solution would be using vue resource interceptors but that would // add unecessary complexity for the moment. // maybe when we move to axios we could use moxios for that which is much simpler. Object.defineProperty(wrapper.vm.$v.team.name, 'available', { value: true, writable: false, }); teamNameInput().element.value = 'test'; teamNameInput().trigger('input'); expect(submitButton().attributes().disabled).toBeUndefined(); }); }); <|start_filename|>app/assets/javascripts/polyfill.js<|end_filename|> import 'core-js/fn/array/some'; import 'core-js/fn/array/from'; import 'core-js/fn/array/find'; import 'core-js/fn/array/find-index'; import 'core-js/fn/object/assign'; <|start_filename|>app/assets/javascripts/modules/namespaces/index.js<|end_filename|> import Vue from 'vue'; import NamespacesIndexPage from './pages/index'; import NamespacesShowPage from './pages/show'; $(() => { if (!$('body[data-controller="namespaces"]').length) { return; } // eslint-disable-next-line no-new new Vue({ el: '.vue-root', components: { NamespacesIndexPage, NamespacesShowPage, }, }); }); <|start_filename|>app/assets/javascripts/modules/users/pages/sign-in.js<|end_filename|> import BaseComponent from '~/base/component'; import { fadeIn } from '~/utils/effects'; // UsersSignInPage component responsible to instantiate // the user's sign in page components and handle interactions. class UsersSignInPage extends BaseComponent { mount() { fadeIn(this.$el.find('> .container-fluid')); } } export default UsersSignInPage; <|start_filename|>app/assets/javascripts/modules/users/components/password-form.js<|end_filename|> import BaseComponent from '~/base/component'; const CURRENT_PASSWORD_FIELD = <PASSWORD>'; const NEW_PASSWORD_FIELD = <PASSWORD>'; const NEW_CONFIRMATION_PASSWORD_FIELD = <PASSWORD>'; const SUBMIT_BUTTON = 'input[type=submit]'; // UsersPasswordForm component that handles user password form // interactions. class UsersPasswordForm extends BaseComponent { elements() { this.$currentPassword = this.$el.find(CURRENT_PASSWORD_FIELD); this.$newPassword = this.$el.find(NEW_PASSWORD_FIELD); this.$newPasswordConfirmation = this.$el.find(NEW_CONFIRMATION_PASSWORD_FIELD); this.$submit = this.$el.find(SUBMIT_BUTTON); } events() { this.$el.on('keyup', CURRENT_PASSWORD_FIELD, e => this.onKeyup(e)); this.$el.on('keyup', NEW_PASSWORD_FIELD, e => this.onKeyup(e)); this.$el.on('keyup', NEW_CONFIRMATION_PASSWORD_FIELD, e => this.onKeyup(e)); } onKeyup() { const currentPassword = this.$currentPassword.val(); const newPassword = this.$<PASSWORD>.val(); const newPasswordConfirmation = this.$newPasswordConfirmation.val(); const currentPasswordInvalid = !currentPassword; const newPasswordInvalid = !newPassword; const newPasswordConfirmationInvalid = !newPasswordConfirmation || newPassword !== <PASSWORD>Confirmation; if (currentPasswordInvalid || newPasswordInvalid || newPasswordConfirmationInvalid) { this.$submit.attr('disabled', 'disabled'); } else { this.$submit.removeAttr('disabled'); } } } export default UsersPasswordForm; <|start_filename|>app/assets/javascripts/modules/webhooks/store.js<|end_filename|> import Vue from 'vue'; const { set } = Vue; class WebhooksStore { constructor() { this.state = { newFormVisible: false, editFormVisible: false, newHeaderFormVisible: false, }; } set(key, value) { set(this.state, key, value); } } export default new WebhooksStore(); <|start_filename|>app/assets/javascripts/config.js<|end_filename|> export default { pagination: window.PAGINATION, apiUrl: window.API_URL, }; <|start_filename|>spec/javascripts/utils/range.spec.js<|end_filename|> import range from '~/utils/range'; describe('Range', () => { it('returns throws exception if start > end', () => { expect(() => { range(1, -2); }).toThrowError(); }); it('returns an array of integers', () => { expect(range(-1, 1)).toEqual([-1, 0, 1]); }); }); <|start_filename|>app/assets/javascripts/modules/webhooks/services/deliveries.js<|end_filename|> import Vue from 'vue'; import VueResource from 'vue-resource'; Vue.use(VueResource); const oldResource = Vue.resource('namespaces/{namespaceId}/webhooks/{webhookId}/deliveries{/id}.json'); function retrigger(namespaceId, webhookId, id) { return oldResource.update({ namespaceId, webhookId, id }, {}); } export default { retrigger, }; <|start_filename|>spec/javascripts/modules/repositories/vulnerabilities-preview.spec.js<|end_filename|> import { mount } from '@vue/test-utils'; import VulnerabilitiesPreview from '~/modules/vulnerabilities/components/preview'; describe('vulnerabilities-preview', () => { let wrapper; beforeEach(() => { wrapper = mount(VulnerabilitiesPreview, { propsData: { vulnerabilities: [], }, }); }); context('when no vulnerabilities', () => { it('shows passed', () => { expect(wrapper.find('.severity-passed').text()).toBe('Passed'); }); }); context('when vulnerabilities', () => { it('shows highest severity and total number', () => { const vulnerabilities = [ { severity: 'High' }, { severity: 'High' }, { severity: 'Low' }, { severity: 'Low' }, ]; wrapper.setProps({ vulnerabilities }); expect(wrapper.find('.severity-high').text()).toBe('2 High'); expect(wrapper.find('.total').text()).toBe('4 total'); }); it('shows highest severity and total number [2]', () => { const vulnerabilities = [ { severity: 'Critical' }, { severity: 'High' }, { severity: 'High' }, { severity: 'Low' }, { severity: 'Low' }, ]; wrapper.setProps({ vulnerabilities }); expect(wrapper.find('.severity-critical').text()).toBe('1 Critical'); expect(wrapper.find('.total').text()).toBe('5 total'); }); }); }); <|start_filename|>spec/javascripts/setup.js<|end_filename|> require('jsdom-global')(); const dayjs = require('dayjs'); const relativeTime = require('dayjs/plugin/relativeTime'); global.expect = require('expect'); dayjs.extend(relativeTime); <|start_filename|>app/assets/javascripts/modules/users/store.js<|end_filename|> class UsersStore { constructor() { this.state = { newFormVisible: false, }; } } export default new UsersStore(); <|start_filename|>app/assets/javascripts/modules/admin/registries/service.js<|end_filename|> import Vue from 'vue'; import VueResource from 'vue-resource'; Vue.use(VueResource); const customActions = { validate: { method: 'GET', url: 'api/v1/registries/validate', }, }; const resource = Vue.resource('api/v1/registries/{/id}.json', {}, customActions); function validate(registry, field = null) { const data = registry; if (field) { data['only[]'] = field; } return resource.validate(data) .then(response => response.data) .catch(() => null); } export default { validate, }; <|start_filename|>app/assets/javascripts/main.js<|end_filename|> // Bootstrap import 'bootstrap/js/transition'; import 'bootstrap/js/tab'; import 'bootstrap/js/tooltip'; import 'bootstrap/js/popover'; import 'bootstrap/js/dropdown'; import 'bootstrap/js/button'; import 'bootstrap/js/collapse'; // Life it up import 'vendor/lifeitup_layout'; // misc import './plugins'; import './polyfill'; // modules import './modules/admin/registries'; import './modules/users'; import './modules/dashboard'; import './modules/repositories'; import './modules/namespaces'; import './modules/tags'; import './modules/teams'; import './modules/webhooks'; import './bootstrap'; import './globals'; <|start_filename|>app/assets/javascripts/modules/repositories/services/comments.js<|end_filename|> import Vue from 'vue'; import VueResource from 'vue-resource'; Vue.use(VueResource); const oldResource = Vue.resource('repositories/{repositoryId}/comments{/id}.json'); function save(repositoryId, comment) { return oldResource.save({ repositoryId }, { comment }); } function remove(repositoryId, id) { return oldResource.delete({ repositoryId, id }); } export default { save, remove, }; <|start_filename|>app/assets/javascripts/modules/explore/pages/index.js<|end_filename|> import Vue from 'vue'; import Result from '../components/result'; $(() => { if (!$('body[data-route="explore/index"]').length) { return; } // eslint-disable-next-line no-new new Vue({ el: 'body[data-route="explore/index"] .vue-root', components: { Result, }, }); }); <|start_filename|>app/assets/javascripts/modules/admin/registries/index.js<|end_filename|> import Vue from 'vue'; import AdminRegistriesNewPage from './pages/new'; import AdminRegistriesEditPage from './pages/edit'; $(() => { if (!$('body[data-controller="admin/registries"]').length) { return; } // eslint-disable-next-line no-new new Vue({ el: '.vue-root', components: { AdminRegistriesNewPage, AdminRegistriesEditPage, }, }); }); <|start_filename|>app/assets/javascripts/modules/dashboard/components/search.js<|end_filename|> import BaseComponent from '~/base/component'; const SEARCH_FIELD = '#search'; const CTRL = 17; const SPACE = 32; // SearchComponent handles the state and the dynamic behavior of the // search input. class SearchComponent extends BaseComponent { elements() { // Instance variables. this.keys = [ { key: CTRL, pressed: false }, { key: SPACE, pressed: false }, ]; this.keypressed = void 0; // UI elements. this.$search = this.$el.find(SEARCH_FIELD); } events() { this.$el.on('keydown', e => this.onKey(e, true)); this.$el.on('keyup', e => this.onKey(e, false)); } // onKey is a callback that should be executed on key events. The first // parameter is the event object, and `down` is a boolean specifying whether // this is a "keydown" event or not. onKey(e, down) { if (e.keyCode === CTRL || e.keyCode === SPACE) { // If we are on a key down event and ctrl is currently pressed, the // spacebar default action wont be triggered if (down && this.keys[0].v) { e.preventDefault(); } this.keypressed = e.keyCode; this.searchKey(this.keypressed, down); } } // openSearch scrolls to the top if needed and focuses the search input. openSearch() { if ($(window).scrollTop() > 0) { $('html,body').unbind().animate({ scrollTop: 0 }, 500); } this.$search.val('').focus(); } // activateSearch calls openSearch if both keys are pressed at the same time. activateSearch() { var performSearch = 0; $.each(this.keys, (i) => { if (this.keys[i].pressed) { performSearch++; } if (performSearch === 2) { this.openSearch(); } }); } // searchKey sets the given key as pressed/unpressed if it's one of the two // keys. searchKey(key, pressed) { $.each(this.keys, (i) => { if (this.keys[i].key === key) { this.keys[i].pressed = pressed; } }); this.activateSearch(); } } export default SearchComponent; <|start_filename|>app/assets/javascripts/plugins/config.js<|end_filename|> import config from '~/config'; export default function install(Vue) { Object.defineProperties(Vue.prototype, { $config: { get() { return config; }, }, }); } <|start_filename|>app/assets/javascripts/modules/namespaces/store.js<|end_filename|> class RepositoriesStore { constructor() { this.state = { newFormVisible: false, editFormVisible: false, isDeleting: false, isLoading: false, notLoaded: false, onGoingVisibilityRequest: false, }; } } export default new RepositoriesStore(); <|start_filename|>app/assets/javascripts/plugins/index.js<|end_filename|> import Vue from 'vue'; import VueResource from 'vue-resource'; import Vuelidate from 'vuelidate'; import EventBus from '~/plugins/eventbus'; import Alert from '~/plugins/alert'; import Config from '~/plugins/config'; import CSRF from '~/utils/csrf'; import configObj from '~/config'; Vue.use(Vuelidate); Vue.use(VueResource); Vue.use(EventBus); Vue.use(Alert); Vue.use(Config); Vue.http.options.root = configObj.apiUrl; Vue.http.interceptors.push((_request) => { window.$.active = window.$.active || 0; window.$.active += 1; return function () { window.$.active -= 1; }; }); Vue.http.interceptors.push((request) => { const token = CSRF.token(); if (token !== null) { request.headers.set('X-CSRF-Token', token); } }); <|start_filename|>app/assets/javascripts/modules/dashboard/components/tabbed_widget.js<|end_filename|> import BaseComponent from '~/base/component'; class TabbedWidget extends BaseComponent { elements() { this.$links = this.$el.find('a'); } events() { this.$links.on('click', (e) => { e.preventDefault(); $(this).tab('show'); }); } } export default TabbedWidget; <|start_filename|>config/webpack.js<|end_filename|> /* eslint-disable quote-props, comma-dangle, import/no-extraneous-dependencies */ // This file was based on Gitlab's config/webpack.config.js file. const path = require('path'); const webpack = require('webpack'); const CompressionPlugin = require('compression-webpack-plugin'); const StatsPlugin = require('stats-webpack-plugin'); const VueLoaderPlugin = require('vue-loader/lib/plugin'); const UglifyJSPlugin = require('uglifyjs-webpack-plugin'); const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer'); const ROOT_PATH = path.resolve(__dirname, '..'); const CACHE_PATH = path.join(ROOT_PATH, 'tmp/cache'); const IS_PRODUCTION = process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging'; const IS_TEST = process.env.NODE_ENV === 'test'; const { WEBPACK_REPORT } = process.env; const VUE_VERSION = require('vue/package.json').version; const VUE_LOADER_VERSION = require('vue-loader/package.json').version; const devtool = IS_PRODUCTION ? 'source-map' : 'cheap-module-eval-source-map'; var config = { mode: IS_PRODUCTION ? 'production' : 'development', context: path.join(ROOT_PATH, 'app/assets/javascripts'), entry: { application: './main.js', unauthenticated: './unauthenticated.js', }, output: { path: path.join(ROOT_PATH, 'public/assets/webpack'), publicPath: '/assets/webpack/', filename: IS_PRODUCTION ? '[name]-[chunkhash].js' : '[name].js', chunkFilename: IS_PRODUCTION ? '[name]-[chunkhash].chunk.js' : '[name].chunk.js', }, resolve: { extensions: ['.js', '.vue'], mainFields: ['jsnext', 'main', 'browser'], alias: { '~': path.join(ROOT_PATH, 'app/assets/javascripts'), 'bootstrap/js': 'bootstrap-sass/assets/javascripts/bootstrap', 'vendor': path.join(ROOT_PATH, 'vendor/assets/javascripts'), 'vue$': 'vue/dist/vue.esm.js', }, }, devtool, module: { rules: [ { test: /\.js$/, exclude: file => /node_modules|vendor[\\/]assets/.test(file) && !/\.vue\.js/.test(file), loader: 'babel-loader', options: { cacheDirectory: path.join(CACHE_PATH, 'babel-loader'), }, }, { test: /\.vue$/, exclude: /(node_modules|vendor\/assets)/, loader: 'vue-loader', options: { cacheDirectory: path.join(CACHE_PATH, 'vue-loader'), cacheIdentifier: [ process.env.NODE_ENV || 'development', webpack.version, VUE_VERSION, VUE_LOADER_VERSION, ].join('|'), }, }, { test: /\.css$/, use: [ 'vue-style-loader', 'css-loader', ], }, ], }, optimization: { splitChunks: { chunks: 'all', cacheGroups: { default: false, vendors: { priority: 10, test: /[\\/](node_modules|vendor[\\/]assets[\\/]javascripts)[\\/]/, }, }, }, }, plugins: [ // Manifest filename must match config.webpack.manifest_filename // webpack-rails only needs assetsByChunkName to function properly new StatsPlugin('manifest.json', { chunkModules: false, source: false, chunks: false, modules: false, assets: true, }), new VueLoaderPlugin(), // fix legacy jQuery plugins which depend on globals new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery', }), new webpack.IgnorePlugin(/^\.\/jquery$/, /jquery-ujs$/), WEBPACK_REPORT && new BundleAnalyzerPlugin({ analyzerMode: 'static', generateStatsFile: true, openAnalyzer: false, reportFilename: path.join(ROOT_PATH, 'webpack-report/index.html'), statsFilename: path.join(ROOT_PATH, 'webpack-report/stats.json'), }), ].filter(Boolean), }; if (IS_PRODUCTION) { config.optimization.minimizer = [ new UglifyJSPlugin({ sourceMap: true, cache: true, parallel: true, uglifyOptions: { output: { comments: false } } }) ]; config.plugins.push( new webpack.NoEmitOnErrorsPlugin(), new webpack.LoaderOptionsPlugin({ minimize: true, debug: false, }), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production') }, }), new CompressionPlugin() ); } if (IS_TEST) { // eslint-disable-next-line config.externals = [require('webpack-node-externals')()]; config.devtool = 'eval-source-map'; } module.exports = config; <|start_filename|>app/assets/javascripts/utils/date.js<|end_filename|> import dayjs from 'dayjs'; const isISO8601 = (date) => { const type = typeof date; const regex = /(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))/; if (type === 'object') { return dayjs(date).isValid(); } if (type !== 'string' || !regex.test(date)) { return false; } return dayjs(date).isValid(); }; export default { isISO8601, }; <|start_filename|>app/assets/javascripts/modules/webhooks/services/headers.js<|end_filename|> import Vue from 'vue'; import VueResource from 'vue-resource'; Vue.use(VueResource); const oldResource = Vue.resource('namespaces/{namespaceId}/webhooks/{webhookId}/headers{/id}.json'); function destroy(namespaceId, webhookId, id) { return oldResource.delete({ namespaceId, webhookId, id }); } function save(namespaceId, webhookId, webhook_header) { return oldResource.save({ namespaceId, webhookId }, { webhook_header }); } export default { destroy, save, };
xybots/Portus
<|start_filename|>.vscode/settings.json<|end_filename|> { "editor.formatOnSave": true, "yaml.schemas": { "https://raw.githubusercontent.com/SchemaStore/schemastore/master/src/schemas/json/github-workflow.json": ".github/workflows/**" } } <|start_filename|>src/JsonRpc.fs<|end_filename|> module Ionide.LanguageServerProtocol.JsonRpc open Newtonsoft.Json open Newtonsoft.Json.Linq type MessageTypeTest = { [<JsonProperty("jsonrpc")>] Version: string Id: int option Method: string option } [<RequireQualifiedAccess>] type MessageType = | Notification | Request | Response | Error let getMessageType messageTest = match messageTest with | { Version = "2.0"; Id = Some _; Method = Some _ } -> MessageType.Request | { Version = "2.0"; Id = Some _; Method = None } -> MessageType.Response | { Version = "2.0"; Id = None; Method = Some _ } -> MessageType.Notification | _ -> MessageType.Error type Request = { [<JsonProperty("jsonrpc")>] Version: string Id: int Method: string Params: JToken option } static member Create(id: int, method': string, rpcParams: JToken option) = { Version = "2.0"; Id = id; Method = method'; Params = rpcParams } type Notification = { [<JsonProperty("jsonrpc")>] Version: string Method: string Params: JToken option } static member Create(method': string, rpcParams: JToken option) = { Version = "2.0"; Method = method'; Params = rpcParams } module ErrorCodes = let parseError = -32700 let invalidRequest = -32600 let methodNotFound = -32601 let invalidParams = -32602 let internalError = -32603 let serverErrorStart = -32000 let serverErrorEnd = -32099 type Error = { Code: int Message: string Data: JToken option } static member Create(code: int, message: string) = { Code = code; Message = message; Data = None } static member ParseError = Error.Create(ErrorCodes.parseError, "Parse error") static member InvalidRequest = Error.Create(ErrorCodes.invalidRequest, "Invalid Request") static member MethodNotFound = Error.Create(ErrorCodes.methodNotFound, "Method not found") static member InvalidParams = Error.Create(ErrorCodes.invalidParams, "Invalid params") static member InternalError = Error.Create(ErrorCodes.internalError, "Internal error") static member InternalErrorMessage message = Error.Create(ErrorCodes.internalError, message) type Response = { [<JsonProperty("jsonrpc")>] Version: string Id: int option Error: Error option [<JsonProperty(NullValueHandling = NullValueHandling.Include)>] Result: JToken option } /// Json.NET conditional property serialization, controlled by naming convention member x.ShouldSerializeResult() = x.Error.IsNone static member Success(id: int, result: JToken option) = { Version = "2.0"; Id = Some id; Result = result; Error = None } static member Failure(id: int, error: Error) = { Version = "2.0"; Id = Some id; Result = None; Error = Some error } <|start_filename|>src/Server.fs<|end_filename|> namespace Ionide.LanguageServerProtocol open Ionide.LanguageServerProtocol.Types module private ServerUtil = /// Return the JSON-RPC "not implemented" error let notImplemented<'t> = async.Return LspResult.notImplemented<'t> /// Do nothing and ignore the notification let ignoreNotification = async.Return(()) open ServerUtil [<AbstractClass>] type LspServer() = interface System.IDisposable with member x.Dispose() = x.Dispose() abstract member Dispose: unit -> unit /// The initialize request is sent as the first request from the client to the server. /// The initialize request may only be sent once. abstract member Initialize: InitializeParams -> AsyncLspResult<InitializeResult> default __.Initialize(_) = notImplemented /// The initialized notification is sent from the client to the server after the client received the result /// of the initialize request but before the client is sending any other request or notification to the server. /// The server can use the initialized notification for example to dynamically register capabilities. /// The initialized notification may only be sent once. abstract member Initialized: InitializedParams -> Async<unit> default __.Initialized(_) = ignoreNotification /// The shutdown request is sent from the client to the server. It asks the server to shut down, but to not /// exit (otherwise the response might not be delivered correctly to the client). There is a separate exit /// notification that asks the server to exit. abstract member Shutdown: unit -> Async<unit> default __.Shutdown() = ignoreNotification /// A notification to ask the server to exit its process. abstract member Exit: unit -> Async<unit> default __.Exit() = ignoreNotification /// The hover request is sent from the client to the server to request hover information at a given text /// document position. abstract member TextDocumentHover: TextDocumentPositionParams -> AsyncLspResult<Hover option> default __.TextDocumentHover(_) = notImplemented /// The document open notification is sent from the client to the server to signal newly opened text /// documents. /// /// The document’s truth is now managed by the client and the server must not try to read the document’s /// truth using the document’s uri. Open in this sense means it is managed by the client. It doesn't /// necessarily mean that its content is presented in an editor. An open notification must not be sent /// more than once without a corresponding close notification send before. This means open and close /// notification must be balanced and the max open count for a particular textDocument is one. abstract member TextDocumentDidOpen: DidOpenTextDocumentParams -> Async<unit> default __.TextDocumentDidOpen(_) = ignoreNotification /// The document change notification is sent from the client to the server to signal changes to a text document. abstract member TextDocumentDidChange: DidChangeTextDocumentParams -> Async<unit> default __.TextDocumentDidChange(_) = ignoreNotification /// The Completion request is sent from the client to the server to compute completion items at a given /// cursor position. Completion items are presented in the IntelliSense user interface. /// /// If computing full completion items is expensive, servers can additionally provide a handler for the /// completion item resolve request (‘completionItem/resolve’). This request is sent when a completion /// item is selected in the user interface. A typical use case is for example: the ‘textDocument/completion’ /// request doesn’t fill in the documentation property for returned completion items since it is expensive /// to compute. When the item is selected in the user interface then a ‘completionItem/resolve’ request is /// sent with the selected completion item as a param. The returned completion item should have the /// documentation property filled in. The request can delay the computation of the detail and documentation /// properties. However, properties that are needed for the initial sorting and filtering, like sortText, /// filterText, insertText, and textEdit must be provided in the textDocument/completion request and must /// not be changed during resolve. abstract member TextDocumentCompletion: CompletionParams -> AsyncLspResult<CompletionList option> default __.TextDocumentCompletion(_) = notImplemented /// The request is sent from the client to the server to resolve additional information for a given /// completion item. abstract member CompletionItemResolve: CompletionItem -> AsyncLspResult<CompletionItem> default __.CompletionItemResolve(_) = notImplemented /// The rename request is sent from the client to the server to perform a workspace-wide rename of a symbol. abstract member TextDocumentRename: RenameParams -> AsyncLspResult<WorkspaceEdit option> default __.TextDocumentRename(_) = notImplemented /// The goto definition request is sent from the client to the server to resolve the definition location of /// a symbol at a given text document position. abstract member TextDocumentDefinition: TextDocumentPositionParams -> AsyncLspResult<GotoResult option> default __.TextDocumentDefinition(_) = notImplemented /// The references request is sent from the client to the server to resolve project-wide references for /// the symbol denoted by the given text document position. abstract member TextDocumentReferences: ReferenceParams -> AsyncLspResult<Location [] option> default __.TextDocumentReferences(_) = notImplemented /// The document highlight request is sent from the client to the server to resolve a document highlights /// for a given text document position. For programming languages this usually highlights all references /// to the symbol scoped to this file. /// /// However we kept `textDocument/documentHighlight` and `textDocument/references` separate requests since /// the first one is allowed to be more fuzzy. Symbol matches usually have a DocumentHighlightKind of Read /// or Write whereas fuzzy or textual matches use Text as the kind. abstract member TextDocumentDocumentHighlight: TextDocumentPositionParams -> AsyncLspResult<DocumentHighlight [] option> default __.TextDocumentDocumentHighlight(_) = notImplemented /// The document links request is sent from the client to the server to request the location of links /// in a document. abstract member TextDocumentDocumentLink: DocumentLinkParams -> AsyncLspResult<DocumentLink [] option> default __.TextDocumentDocumentLink(_) = notImplemented /// The goto type definition request is sent from the client to the server to resolve the type definition /// location of a symbol at a given text document position. abstract member TextDocumentTypeDefinition: TextDocumentPositionParams -> AsyncLspResult<GotoResult option> default __.TextDocumentTypeDefinition(_) = notImplemented /// The goto implementation request is sent from the client to the server to resolve the implementation /// location of a symbol at a given text document position. abstract member TextDocumentImplementation: TextDocumentPositionParams -> AsyncLspResult<GotoResult option> default __.TextDocumentImplementation(_) = notImplemented /// The code action request is sent from the client to the server to compute commands for a given text /// document and range. These commands are typically code fixes to either fix problems or to /// beautify/refactor code. The result of a textDocument/codeAction request is an array of Command literals /// which are typically presented in the user interface. When the command is selected the server should be /// contacted again (via the workspace/executeCommand) request to execute the command. abstract member TextDocumentCodeAction: CodeActionParams -> AsyncLspResult<TextDocumentCodeActionResult option> default __.TextDocumentCodeAction(_) = notImplemented /// The code action request is sent from the client to the server to compute commands for a given text /// document and range. These commands are typically code fixes to either fix problems or to /// beautify/refactor code. The result of a textDocument/codeAction request is an array of Command literals /// which are typically presented in the user interface. When the command is selected the server should be /// contacted again (via the workspace/executeCommand) request to execute the command. abstract member CodeActionResolve: CodeAction -> AsyncLspResult<CodeAction option> default __.CodeActionResolve(_) = notImplemented /// The code lens request is sent from the client to the server to compute code lenses for a given /// text document. abstract member TextDocumentCodeLens: CodeLensParams -> AsyncLspResult<CodeLens [] option> default __.TextDocumentCodeLens(_) = notImplemented /// The code lens resolve request is sent from the client to the server to resolve the command for /// a given code lens item. abstract member CodeLensResolve: CodeLens -> AsyncLspResult<CodeLens> default __.CodeLensResolve(_) = notImplemented /// The signature help request is sent from the client to the server to request signature information at /// a given cursor position. abstract member TextDocumentSignatureHelp: SignatureHelpParams -> AsyncLspResult<SignatureHelp option> default __.TextDocumentSignatureHelp(_) = notImplemented /// The document link resolve request is sent from the client to the server to resolve the target of /// a given document link. abstract member DocumentLinkResolve: DocumentLink -> AsyncLspResult<DocumentLink> default __.DocumentLinkResolve(_) = notImplemented /// The document color request is sent from the client to the server to list all color references /// found in a given text document. Along with the range, a color value in RGB is returned. abstract member TextDocumentDocumentColor: DocumentColorParams -> AsyncLspResult<ColorInformation []> default __.TextDocumentDocumentColor(_) = notImplemented /// The color presentation request is sent from the client to the server to obtain a list of /// presentations for a color value at a given location. Clients can use the result to abstract member TextDocumentColorPresentation: ColorPresentationParams -> AsyncLspResult<ColorPresentation []> default __.TextDocumentColorPresentation(_) = notImplemented /// The document formatting request is sent from the client to the server to format a whole document. abstract member TextDocumentFormatting: DocumentFormattingParams -> AsyncLspResult<TextEdit [] option> default __.TextDocumentFormatting(_) = notImplemented /// The document range formatting request is sent from the client to the server to format a given /// range in a document. abstract member TextDocumentRangeFormatting: DocumentRangeFormattingParams -> AsyncLspResult<TextEdit [] option> default __.TextDocumentRangeFormatting(_) = notImplemented /// The document on type formatting request is sent from the client to the server to format parts /// of the document during typing. abstract member TextDocumentOnTypeFormatting: DocumentOnTypeFormattingParams -> AsyncLspResult<TextEdit [] option> default __.TextDocumentOnTypeFormatting(_) = notImplemented /// The document symbol request is sent from the client to the server to return a flat list of all symbols /// found in a given text document. Neither the symbol’s location range nor the symbol’s container name /// should be used to infer a hierarchy. abstract member TextDocumentDocumentSymbol: DocumentSymbolParams -> AsyncLspResult<U2<SymbolInformation [], DocumentSymbol []> option> default __.TextDocumentDocumentSymbol(_) = notImplemented /// The watched files notification is sent from the client to the server when the client detects changes /// to files watched by the language client. It is recommended that servers register for these file /// events using the registration mechanism. In former implementations clients pushed file events without /// the server actively asking for it. abstract member WorkspaceDidChangeWatchedFiles: DidChangeWatchedFilesParams -> Async<unit> default __.WorkspaceDidChangeWatchedFiles(_) = ignoreNotification /// The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server to inform /// the server about workspace folder configuration changes. The notification is sent by default if both /// *ServerCapabilities/workspace/workspaceFolders* and *ClientCapabilities/workapce/workspaceFolders* are /// true; or if the server has registered to receive this notification it first. abstract member WorkspaceDidChangeWorkspaceFolders: DidChangeWorkspaceFoldersParams -> Async<unit> default __.WorkspaceDidChangeWorkspaceFolders(_) = ignoreNotification /// A notification sent from the client to the server to signal the change of configuration settings. abstract member WorkspaceDidChangeConfiguration: DidChangeConfigurationParams -> Async<unit> default __.WorkspaceDidChangeConfiguration(_) = ignoreNotification /// The will create files request is sent from the client to the server before files are actually created /// as long as the creation is triggered from within the client either by a user action or by applying a /// workspace edit abstract member WorkspaceWillCreateFiles: CreateFilesParams -> AsyncLspResult<WorkspaceEdit option> default __.WorkspaceWillCreateFiles(_) = notImplemented /// The did create files notification is sent from the client to the server when files were created /// from within the client. abstract member WorkspaceDidCreateFiles: CreateFilesParams -> Async<unit> default __.WorkspaceDidCreateFiles(_) = ignoreNotification /// The will rename files request is sent from the client to the server before files are actually renamed /// as long as the rename is triggered from within the client either by a user action or by applying a /// workspace edit. abstract member WorkspaceWillRenameFiles: RenameFilesParams -> AsyncLspResult<WorkspaceEdit option> default __.WorkspaceWillRenameFiles(_) = notImplemented /// The did rename files notification is sent from the client to the server when files were renamed from /// within the client. abstract member WorkspaceDidRenameFiles: RenameFilesParams -> Async<unit> default __.WorkspaceDidRenameFiles(_) = ignoreNotification /// The will delete files request is sent from the client to the server before files are actually deleted /// as long as the deletion is triggered from within the client either by a user action or by applying a /// workspace edit. abstract member WorkspaceWillDeleteFiles: DeleteFilesParams -> AsyncLspResult<WorkspaceEdit option> default __.WorkspaceWillDeleteFiles(_) = notImplemented /// The did delete files notification is sent from the client to the server when files were deleted from /// within the client. abstract member WorkspaceDidDeleteFiles: DeleteFilesParams -> Async<unit> default __.WorkspaceDidDeleteFiles(_) = ignoreNotification /// The workspace symbol request is sent from the client to the server to list project-wide symbols matching /// the query string. abstract member WorkspaceSymbol: WorkspaceSymbolParams -> AsyncLspResult<SymbolInformation [] option> default __.WorkspaceSymbol(_) = notImplemented /// The `workspace/executeCommand` request is sent from the client to the server to trigger command execution /// on the server. In most cases the server creates a `WorkspaceEdit` structure and applies the changes to the /// workspace using the request `workspace/applyEdit` which is sent from the server to the client. abstract member WorkspaceExecuteCommand: ExecuteCommandParams -> AsyncLspResult<Newtonsoft.Json.Linq.JToken> default __.WorkspaceExecuteCommand(_) = notImplemented /// The document will save notification is sent from the client to the server before the document is /// actually saved. abstract member TextDocumentWillSave: WillSaveTextDocumentParams -> Async<unit> default __.TextDocumentWillSave(_) = ignoreNotification /// The document will save request is sent from the client to the server before the document is actually saved. /// The request can return an array of TextEdits which will be applied to the text document before it is saved. /// Please note that clients might drop results if computing the text edits took too long or if a server /// constantly fails on this request. This is done to keep the save fast and reliable. abstract member TextDocumentWillSaveWaitUntil: WillSaveTextDocumentParams -> AsyncLspResult<TextEdit [] option> default __.TextDocumentWillSaveWaitUntil(_) = notImplemented /// The document save notification is sent from the client to the server when the document was saved /// in the client. abstract member TextDocumentDidSave: DidSaveTextDocumentParams -> Async<unit> default __.TextDocumentDidSave(_) = ignoreNotification /// The document close notification is sent from the client to the server when the document got closed in the /// client. The document’s truth now exists where the document’s uri points to (e.g. if the document’s uri is /// a file uri the truth now exists on disk). As with the open notification the close notification is about /// managing the document’s content. Receiving a close notification doesn't mean that the document was open in /// an editor before. A close notification requires a previous open notification to be sent. abstract member TextDocumentDidClose: DidCloseTextDocumentParams -> Async<unit> default __.TextDocumentDidClose(_) = ignoreNotification /// The folding range request is sent from the client to the server to return all folding ranges found in a given text document. abstract member TextDocumentFoldingRange: FoldingRangeParams -> AsyncLspResult<FoldingRange list option> default __.TextDocumentFoldingRange(_) = notImplemented /// The selection range request is sent from the client to the server to return suggested selection ranges at an array of given positions. /// A selection range is a range around the cursor position which the user might be interested in selecting. abstract member TextDocumentSelectionRange: SelectionRangeParams -> AsyncLspResult<SelectionRange list option> default __.TextDocumentSelectionRange(_) = notImplemented abstract member TextDocumentSemanticTokensFull: SemanticTokensParams -> AsyncLspResult<SemanticTokens option> default __.TextDocumentSemanticTokensFull(_) = notImplemented abstract member TextDocumentSemanticTokensFullDelta: SemanticTokensDeltaParams -> AsyncLspResult<U2<SemanticTokens, SemanticTokensDelta> option> default __.TextDocumentSemanticTokensFullDelta(_) = notImplemented abstract member TextDocumentSemanticTokensRange: SemanticTokensRangeParams -> AsyncLspResult<SemanticTokens option> default __.TextDocumentSemanticTokensRange(_) = notImplemented /// The inlay hints request is sent from the client to the server to compute inlay hints for a given [text document, range] tuple /// that may be rendered in the editor in place with other text. abstract member TextDocumentInlayHint: InlayHintParams -> AsyncLspResult<InlayHint [] option> default __.TextDocumentInlayHint(_) = notImplemented /// The request is sent from the client to the server to resolve additional information for a given inlay hint. /// This is usually used to compute the `tooltip`, `location` or `command` properties of a inlay hint’s label part /// to avoid its unnecessary computation during the `textDocument/inlayHint` request. /// /// Consider the clients announces the `label.location` property as a property that can be resolved lazy using the client capability /// ```typescript /// textDocument.inlayHint.resolveSupport = { properties: ['label.location'] }; /// ``` /// then an inlay hint with a label part without a location needs to be resolved using the `inlayHint/resolve` request before it can be used. abstract member InlayHintResolve: InlayHint -> AsyncLspResult<InlayHint> default __.InlayHintResolve(_) = notImplemented <|start_filename|>src/Client.fs<|end_filename|> namespace Ionide.LanguageServerProtocol open Ionide.LanguageServerProtocol.Types module private ClientUtil = /// Return the JSON-RPC "not implemented" error let notImplemented<'t> = async.Return LspResult.notImplemented<'t> /// Do nothing and ignore the notification let ignoreNotification = async.Return(()) open ClientUtil [<AbstractClass>] type LspClient() = /// The show message notification is sent from a server to a client to ask the client to display /// a particular message in the user interface. abstract member WindowShowMessage: ShowMessageParams -> Async<unit> default __.WindowShowMessage(_) = ignoreNotification /// The show message request is sent from a server to a client to ask the client to display /// a particular message in the user interface. In addition to the show message notification the /// request allows to pass actions and to wait for an answer from the client. abstract member WindowShowMessageRequest: ShowMessageRequestParams -> AsyncLspResult<MessageActionItem option> default __.WindowShowMessageRequest(_) = notImplemented /// The log message notification is sent from the server to the client to ask the client to log ///a particular message. abstract member WindowLogMessage: LogMessageParams -> Async<unit> default __.WindowLogMessage(_) = ignoreNotification /// The telemetry notification is sent from the server to the client to ask the client to log /// a telemetry event. abstract member TelemetryEvent: Newtonsoft.Json.Linq.JToken -> Async<unit> default __.TelemetryEvent(_) = ignoreNotification /// The `client/registerCapability` request is sent from the server to the client to register for a new /// capability on the client side. Not all clients need to support dynamic capability registration. /// A client opts in via the dynamicRegistration property on the specific client capabilities. A client /// can even provide dynamic registration for capability A but not for capability B. abstract member ClientRegisterCapability: RegistrationParams -> AsyncLspResult<unit> default __.ClientRegisterCapability(_) = notImplemented /// The `client/unregisterCapability` request is sent from the server to the client to unregister a previously /// registered capability. abstract member ClientUnregisterCapability: UnregistrationParams -> AsyncLspResult<unit> default __.ClientUnregisterCapability(_) = notImplemented /// Many tools support more than one root folder per workspace. Examples for this are VS Code’s multi-root /// support, Atom’s project folder support or Sublime’s project support. If a client workspace consists of /// multiple roots then a server typically needs to know about this. The protocol up to know assumes one root /// folder which is announce to the server by the rootUri property of the InitializeParams. /// If the client supports workspace folders and announces them via the corresponding workspaceFolders client /// capability the InitializeParams contain an additional property workspaceFolders with the configured /// workspace folders when the server starts. /// /// The workspace/workspaceFolders request is sent from the server to the client to fetch the current open /// list of workspace folders. Returns null in the response if only a single file is open in the tool. /// Returns an empty array if a workspace is open but no folders are configured. abstract member WorkspaceWorkspaceFolders: unit -> AsyncLspResult<WorkspaceFolder [] option> default __.WorkspaceWorkspaceFolders() = notImplemented /// The workspace/configuration request is sent from the server to the client to fetch configuration /// settings from the client. /// /// The request can fetch n configuration settings in one roundtrip. The order of the returned configuration /// settings correspond to the order of the passed ConfigurationItems (e.g. the first item in the response /// is the result for the first configuration item in the params). abstract member WorkspaceConfiguration: ConfigurationParams -> AsyncLspResult<Newtonsoft.Json.Linq.JToken []> default __.WorkspaceConfiguration(_) = notImplemented abstract member WorkspaceApplyEdit: ApplyWorkspaceEditParams -> AsyncLspResult<ApplyWorkspaceEditResponse> default __.WorkspaceApplyEdit(_) = notImplemented /// The workspace/semanticTokens/refresh request is sent from the server to the client. /// Servers can use it to ask clients to refresh the editors for which this server provides semantic tokens. /// As a result the client should ask the server to recompute the semantic tokens for these editors. /// This is useful if a server detects a project wide configuration change which requires a re-calculation /// of all semantic tokens. Note that the client still has the freedom to delay the re-calculation of /// the semantic tokens if for example an editor is currently not visible. abstract member WorkspaceSemanticTokensRefresh: unit -> Async<unit> default __.WorkspaceSemanticTokensRefresh() = ignoreNotification /// The `workspace/inlayHint/refresh` request is sent from the server to the client. /// Servers can use it to ask clients to refresh the inlay hints currently shown in editors. /// As a result the client should ask the server to recompute the inlay hints for these editors. /// This is useful if a server detects a configuration change which requires a re-calculation /// of all inlay hints. Note that the client still has the freedom to delay the re-calculation of the inlay hints /// if for example an editor is currently not visible. abstract member WorkspaceInlayHintRefresh: unit -> Async<unit> default __.WorkspaceInlayHintRefresh() = ignoreNotification /// Diagnostics notification are sent from the server to the client to signal results of validation runs. /// /// Diagnostics are “owned” by the server so it is the server’s responsibility to clear them if necessary. /// The following rule is used for VS Code servers that generate diagnostics: /// /// * if a language is single file only (for example HTML) then diagnostics are cleared by the server when /// the file is closed. /// * if a language has a project system (for example C#) diagnostics are not cleared when a file closes. /// When a project is opened all diagnostics for all files are recomputed (or read from a cache). /// /// When a file changes it is the server’s responsibility to re-compute diagnostics and push them to the /// client. If the computed set is empty it has to push the empty array to clear former diagnostics. /// Newly pushed diagnostics always replace previously pushed diagnostics. There is no merging that happens /// on the client side. abstract member TextDocumentPublishDiagnostics: PublishDiagnosticsParams -> Async<unit> default __.TextDocumentPublishDiagnostics(_) = ignoreNotification
baronfel/LanguageServerProtocol
<|start_filename|>Hashids/Classes/Hashids.h<|end_filename|> // // Hashids.h // Hashids // // Created by <NAME> on 7/13/13. // Copyright (c) 2013 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> #define HASHID_MIN_ALPHABET_LENGTH 4 #define HASHID_SEP_DIV 3.5 #define HASHID_GUARD_DIV 12 #define HASHID_MAX_INT_VALUE 1000000000 @interface HashidsException : NSException @end @interface NSMutableString (Hashids) - (NSString *) replaceIndex:(NSInteger)index withString:(NSString *)replaceString; @end @interface Hashids : NSObject + (id)hashidWithSalt:(NSString *) salt; + (id)hashidWithSalt:(NSString *) salt andMinLength:(NSInteger)minLength; + (id)hashidWithSalt:(NSString *) salt minLength:(NSInteger) minLength andAlpha:(NSString *) alphabet; - (id)initWithSalt:(NSString *) salt minLength:(NSInteger) minLength andAlpha:(NSString *) alphabet; - (NSString *) encode:(NSNumber *)firstEntry, ... NS_REQUIRES_NIL_TERMINATION; - (NSArray *) decode:(NSString *) encoded; @end
jofell/hashids-objc
<|start_filename|>test/vary.test.js<|end_filename|> 'use strict' const { test } = require('tap') const vary = require('../vary') test('Should not set reply header if none is passed', t => { t.plan(1) const replyMock = { getHeader (name) { return [] }, header (name, value) { t.fail('Should not be here') } } vary(replyMock, []) t.pass() })
mikemaccana/fastify-cors
<|start_filename|>packages/p/pcre2/xmake.lua<|end_filename|> package("pcre2") set_homepage("https://www.pcre.org/") set_description("A Perl Compatible Regular Expressions Library") set_urls("https://ftp.pcre.org/pub/pcre/pcre2-$(version).zip", "ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre2-$(version).zip") add_versions("10.23", "6301a525a8a7e63a5fac0c2fbfa0374d3eb133e511d886771e097e427707094a") add_versions("10.30", "3677ce17854fffa68fce6b66442858f48f0de1f537f18439e4bd2771f8b4c7fb") add_versions("10.31", "b4b40695a5347a770407d492c1749e35ba3970ca03fe83eb2c35d44343a5a444") if is_host("windows") then add_deps("cmake") end add_configs("jit", {description = "Enable jit.", default = true, type = "boolean"}) add_configs("bitwidth", {description = "Set the code unit width.", default = "8", values = {"8", "16", "32"}}) on_load(function (package) local bitwidth = package:config("bitwidth") or "8" package:add("links", "pcre2-" .. bitwidth) package:add("defines", "PCRE2_CODE_UNIT_WIDTH=" .. bitwidth) if not package:config("shared") then package:add("defines", "PCRE2_STATIC") end end) on_install("windows", function (package) if package:version():lt("10.21") then io.replace("CMakeLists.txt", [[SET(CMAKE_C_FLAGS -I${PROJECT_SOURCE_DIR}/src)]], [[SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -I${PROJECT_SOURCE_DIR}/src")]], {plain = true}) end local configs = {"-DPCRE2_BUILD_TESTS=OFF", "-DPCRE2_BUILD_PCRE2GREP=OFF"} table.insert(configs, "-DBUILD_SHARED_LIBS=" .. (package:config("shared") and "ON" or "OFF")) table.insert(configs, "-DPCRE2_SUPPORT_JIT=" .. (package:config("jit") and "ON" or "OFF")) local bitwidth = package:config("bitwidth") or "8" if bitwidth ~= "8" then table.insert(configs, "-DPCRE2_BUILD_PCRE2_8=OFF") table.insert(configs, "-DPCRE2_BUILD_PCRE2_" .. bitwidth .. "=ON") end if package:debug() then table.insert(configs, "-DPCRE2_DEBUG=ON") end if package:is_plat("windows") then table.insert(configs, "-DPCRE2_STATIC_RUNTIME=" .. (package:config("vs_runtime"):startswith("MT") and "ON" or "OFF")) end import("package.tools.cmake").install(package, configs) end) on_install("macosx", "linux", "mingw", function (package) local configs = {} table.insert(configs, "--enable-shared=" .. (package:config("shared") and "yes" or "no")) table.insert(configs, "--enable-static=" .. (package:config("shared") and "no" or "yes")) if package:debug() then table.insert(configs, "--enable-debug") end if package:config("pic") ~= false then table.insert(configs, "--with-pic") end if package:config("jit") then table.insert(configs, "--enable-jit") end local bitwidth = package:config("bitwidth") or "8" if bitwidth ~= "8" then table.insert(configs, "--disable-pcre2-8") table.insert(configs, "--enable-pcre2-" .. bitwidth) end import("package.tools.autoconf").install(package, configs) end) on_test(function (package) assert(package:has_cfuncs("pcre2_compile", {includes = "pcre2.h"})) end)
wsw0108/xmake-repo
<|start_filename|>main.go<|end_filename|> package main import ( "flag" "fmt" "log" "os" "os/exec" "os/signal" "strconv" "strings" "syscall" "time" "github.com/bendahl/uinput" "github.com/godbus/dbus" evdev "github.com/gvalkov/golang-evdev" ) var ( config Config dbusConn *dbus.Conn keyboard uinput.Keyboard threshold time.Time pressed = make(map[uint16]struct{}) configFile = flag.String("config", "config.json", "path to config file") debug = flag.Bool("debug", false, "enables debug output") timeout = flag.Uint("threshold", 200, "threshold in ms between wheel events") ) type Event struct { *evdev.InputEvent Device Device } // logs if debug is enabled func dLog(a ...interface{}) { if !*debug { return } log.Println(a...) } // prints all detected input devices func listDevices() error { devs, err := evdev.ListInputDevices() if err != nil { return fmt.Errorf("Can't find input devices") } for _, val := range devs { dLog("ID->", val.File.Name(), "Device->", val.Name) } return nil } // findDevice returns the device file matching an input device's name func findDevice(s string) (string, error) { devs, err := evdev.ListInputDevices() if err != nil { return "", err } for _, val := range devs { if strings.Contains(val.Name, s) { return val.File.Name(), nil } } return "", fmt.Errorf("No such device") } // emulates a (multi-)key press func emulateKeyPress(keys string) { kk := strings.Split(keys, "-") for i, k := range kk { kc, err := strconv.Atoi(k) if err != nil { log.Fatalf("%s is not a valid keycode: %s", k, err) } if i+1 < len(kk) { keyboard.KeyDown(kc) defer keyboard.KeyUp(kc) } else { keyboard.KeyPress(kc) } } } // executes a dbus method func executeDBusMethod(object, path, method, args string) { call := dbusConn.Object(object, dbus.ObjectPath(path)).Call(method, 0) if call.Err != nil { log.Printf("dbus call failed: %s", call.Err) } } // executes a command func executeCommand(cmd string) { args := strings.Split(cmd, " ") c := exec.Command(args[0], args[1:]...) if err := c.Start(); err != nil { panic(err) } err := c.Wait() if err != nil { log.Printf("command failed: %s", err) } } // executes an action func executeAction(a Action) { dLog(fmt.Sprintf("Executing action: %+v", a)) if a.Keycode != "" { emulateKeyPress(a.Keycode) } if a.DBus.Method != "" { executeDBusMethod(a.DBus.Object, a.DBus.Path, a.DBus.Method, a.DBus.Value) } if a.Exec != "" { executeCommand(a.Exec) } } // handles mouse wheel events func mouseWheelEvent(ev Event, activeWindow Window) { rel := evdev.RelEvent{} rel.New(ev.InputEvent) if ev.Code != evdev.REL_HWHEEL && ev.Code != evdev.REL_DIAL { return } if time.Since(threshold) < time.Millisecond*time.Duration(*timeout) { dLog("Discarding wheel event below threshold") return } threshold = time.Now() switch ev.Code { case evdev.REL_HWHEEL: rr := config.Rules. FilterByDevice(ev.Device). FilterByDial(0). FilterByHWheel(ev.Value). FilterByKeycodes(pressed). FilterByApplication(activeWindow.Class) if len(rr) == 0 { return } executeAction(rr[0].Action) case evdev.REL_DIAL: rr := config.Rules. FilterByDevice(ev.Device). FilterByDial(ev.Value). FilterByHWheel(0). FilterByKeycodes(pressed). FilterByApplication(activeWindow.Class) if len(rr) == 0 { return } executeAction(rr[0].Action) default: // dLog(rel.String()) } } // handles key events func keyEvent(ev Event, activeWindow Window) { kev := evdev.KeyEvent{} kev.New(ev.InputEvent) pressed[ev.Code] = struct{}{} if kev.State != evdev.KeyUp { return } rr := config.Rules. FilterByDevice(ev.Device). FilterByHWheel(0). FilterByDial(0). FilterByKeycodes(pressed). FilterByApplication(activeWindow.Class) delete(pressed, ev.Code) if len(rr) == 0 { return } executeAction(rr[0].Action) } func handleEvent(ev Event, win Window) { switch ev.Type { case evdev.EV_KEY: // dLog("Key event:", ev.String()) keyEvent(ev, win) case evdev.EV_REL: // dLog("Rel event:", ev.String()) mouseWheelEvent(ev, win) case evdev.EV_ABS: case evdev.EV_SYN: case evdev.EV_MSC: case evdev.EV_LED: case evdev.EV_SND: case evdev.EV_SW: case evdev.EV_PWR: case evdev.EV_FF: case evdev.EV_FF_STATUS: default: log.Println("Unexpected event type:", ev.String()) } } func subscribeToDevice(dev Device, keychan chan Event) { go func(dev Device) { for { var err error df := dev.Dev if df == "" { df, err = findDevice(dev.Name) if err != nil { log.Fatalf("Could not find device for %s", dev.Name) } } ed, err := evdev.Open(df) if err != nil { panic(err) } dLog(ed.String()) for { ev, eerr := ed.ReadOne() if eerr != nil { log.Printf("Error reading from device: %v", eerr) time.Sleep(1 * time.Second) break } keychan <- Event{ InputEvent: ev, Device: dev, } } } }(dev) } func main() { var err error flag.Parse() config, err = LoadConfig(*configFile) if err != nil { log.Fatal(err) } dbusConn, err = dbus.SessionBus() if err != nil { panic(err) } x := Connect(os.Getenv("DISPLAY")) defer x.Close() tracker := make(chan Window) x.TrackActiveWindow(tracker, time.Second) go func() { for w := range tracker { dLog(fmt.Sprintf("Active window changed to %s (%s)", w.Class, w.Name)) } }() keyboard, err = uinput.CreateKeyboard("/dev/uinput", []byte("Virtual Wand")) if err != nil { log.Fatalf("Could not create virtual input device (/dev/uinput): %s", err) } defer keyboard.Close() err = listDevices() if err != nil { panic(err) } keychan := make(chan Event) for _, dev := range config.Devices { subscribeToDevice(dev, keychan) } sigchan := make(chan os.Signal, 1) signal.Notify(sigchan, os.Interrupt, syscall.SIGTERM) var quit bool for { select { case <-sigchan: quit = true case ev := <-keychan: handleEvent(ev, x.ActiveWindow()) } if quit { break } } fmt.Println("Shutting down...") if *debug { err = config.Save(*configFile) if err != nil { log.Fatal(err) } } } <|start_filename|>config.go<|end_filename|> package main import ( "encoding/json" "io/ioutil" "log" "strconv" "strings" ) type DBus struct { Object string `json:"object,omitempty"` Path string `json:"path,omitempty"` Method string `json:"method,omitempty"` Value string `json:"value,omitempty"` } type Action struct { Keycode string `json:"keycode,omitempty"` Exec string `json:"exec,omitempty"` DBus DBus `json:"dbus,omitempty"` } type Rule struct { Device *Device `json:"device,omitempty"` Application string `json:"application,omitempty"` Keycode string `json:"keycode,omitempty"` HWheel int32 `json:"hwheel"` Dial int32 `json:"dial"` Action Action `json:"action"` } type Rules []Rule type Device struct { Name string `json:"name,omitempty"` Dev string `json:"dev,omitempty"` } type Devices []Device type Config struct { Devices Devices `json:"devices"` Rules Rules `json:"rules"` } // LoadConfig loads config from filename func LoadConfig(filename string) (Config, error) { config := Config{} j, err := ioutil.ReadFile(filename) if err != nil { return config, err } err = json.Unmarshal(j, &config) return config, err } // Save writes config as json to filename func (c Config) Save(filename string) error { j, err := json.MarshalIndent(c, "", " ") if err != nil { return err } return ioutil.WriteFile(filename, j, 0644) } func (r Rules) FilterByDevice(dev Device) Rules { var res Rules for _, v := range r { if v.Device == nil || (len(dev.Name) > 0 && v.Device.Name == dev.Name) || (len(dev.Dev) > 0 && v.Device.Dev == dev.Dev) { res = append(res, v) } } return res } func (r Rules) FilterByApplication(name string) Rules { var res Rules for _, v := range r { if v.Application == "" || v.Application == name { res = append(res, v) } if len(v.Application) > 0 && v.Application[0] == '!' { if v.Application[1:] != name { res = append(res, v) } } } return res } func (r Rules) FilterByHWheel(wheel int32) Rules { var res Rules for _, v := range r { if v.HWheel == 0 || v.HWheel == wheel { res = append(res, v) } } return res } func (r Rules) FilterByDial(dial int32) Rules { var res Rules for _, v := range r { if v.Dial == 0 || v.Dial == dial { res = append(res, v) } } return res } func (r Rules) FilterByKeycodes(pressed map[uint16]struct{}) Rules { var res Rules for _, v := range r { kk := strings.Split(v.Keycode, "-") match := true for _, k := range kk { if k == "" { continue } kc, err := strconv.Atoi(k) if err != nil { log.Fatalf("%s is not a valid keycode: %s", k, err) } if _, ok := pressed[uint16(kc)]; !ok { match = false break } } if match { res = append(res, v) } } return res }
muesli/magicwand
<|start_filename|>ReliableNetcode/Utils/DateTimeEx.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ReliableNetcode.Utils { internal static class DateTimeEx { public static double GetTotalSeconds(this DateTime time) { return (time.ToUniversalTime().Subtract(new DateTime(1970, 1, 1))).TotalSeconds; } /// <summary> /// Gets the Unix timestamp of the DateTime object /// </summary> public static ulong ToUnixTimestamp(this DateTime time) { return (ulong)Math.Truncate(time.GetTotalSeconds()); } } } <|start_filename|>ReliableNetcode/Utils/ObjPool.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ReliableNetcode.Utils { internal static class ObjPool<T> where T : new() { private static Queue<T> pool = new Queue<T>(); public static T Get() { lock (pool) { if (pool.Count > 0) return pool.Dequeue(); } return new T(); } public static void Return(T val) { lock (pool) { pool.Enqueue(val); } } } } <|start_filename|>ReliableNetcode/Utils/IO/ByteArrayReader.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace ReliableNetcode.Utils { /// <summary> /// Helper class for a quick non-allocating way to read or write from/to temporary byte arrays as streams /// </summary> public class ByteArrayReaderWriter : IDisposable { protected static Queue<ByteArrayReaderWriter> readerPool = new Queue<ByteArrayReaderWriter>(); /// <summary> /// Get a reader/writer for the given byte array /// </summary> public static ByteArrayReaderWriter Get(byte[] byteArray) { ByteArrayReaderWriter reader = null; lock (readerPool) { if (readerPool.Count > 0) { reader = readerPool.Dequeue(); } else { reader = new ByteArrayReaderWriter(); } } reader.SetStream(byteArray); return reader; } /// <summary> /// Release a reader/writer to the pool /// </summary> public static void Release(ByteArrayReaderWriter reader) { lock (readerPool) { readerPool.Enqueue(reader); } } public long ReadPosition { get { return readStream.Position; } } public bool IsDoneReading { get { return readStream.Position >= readStream.Length; } } public long WritePosition { get { return writeStream.Position; } } protected ByteStream readStream; protected ByteStream writeStream; public ByteArrayReaderWriter() { this.readStream = new ByteStream(); this.writeStream = new ByteStream(); } public void SetStream(byte[] byteArray) { this.readStream.SetStreamSource(byteArray); this.writeStream.SetStreamSource(byteArray); } public void SeekRead(long pos) { this.readStream.Seek(pos, SeekOrigin.Begin); } public void SeekWrite(long pos) { this.writeStream.Seek(pos, SeekOrigin.Begin); } public void Write(byte val) { writeStream.Write(val); } public void Write(byte[] val) { writeStream.Write(val); } public void Write(char val) { writeStream.Write(val); } public void Write(char[] val) { writeStream.Write(val); } public void Write(string val) { writeStream.Write(val); } public void Write(short val) { writeStream.Write(val); } public void Write(int val) { writeStream.Write(val); } public void Write(long val) { writeStream.Write(val); } public void Write(ushort val) { writeStream.Write(val); } public void Write(uint val) { writeStream.Write(val); } public void Write(ulong val) { writeStream.Write(val); } public void Write(float val) { writeStream.Write(val); } public void Write(double val) { writeStream.Write(val); } public void WriteASCII(char[] chars) { for (int i = 0; i < chars.Length; i++) { byte asciiCode = (byte)(chars[i] & 0xFF); Write(asciiCode); } } public void WriteASCII(string str) { for (int i = 0; i < str.Length; i++) { byte asciiCode = (byte)(str[i] & 0xFF); Write(asciiCode); } } public void WriteBuffer(byte[] buffer, int length) { for (int i = 0; i < length; i++) Write(buffer[i]); } public byte ReadByte() { return readStream.ReadByte(); } public byte[] ReadBytes(int length) { return readStream.ReadBytes(length); } public char ReadChar() { return readStream.ReadChar(); } public char[] ReadChars(int length) { return readStream.ReadChars(length); } public string ReadString() { return readStream.ReadString(); } public short ReadInt16() { return readStream.ReadInt16(); } public int ReadInt32() { return readStream.ReadInt32(); } public long ReadInt64() { return readStream.ReadInt64(); } public ushort ReadUInt16() { return readStream.ReadUInt16(); } public uint ReadUInt32() { return readStream.ReadUInt32(); } public ulong ReadUInt64() { return readStream.ReadUInt64(); } public float ReadSingle() { return readStream.ReadSingle(); } public double ReadDouble() { return readStream.ReadDouble(); } public void ReadASCIICharsIntoBuffer(char[] buffer, int length) { for (int i = 0; i < length; i++) buffer[i] = (char)ReadByte(); } public void ReadBytesIntoBuffer(byte[] buffer, int length) { for (int i = 0; i < length; i++) buffer[i] = ReadByte(); } public void Dispose() { Release(this); } } } <|start_filename|>ReliableNetcode/Utils/ByteBuffer.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ReliableNetcode.Utils { internal class ByteBuffer { public int Length { get { return size; } } public byte[] InternalBuffer { get { return _buffer; } } protected byte[] _buffer; protected int size; public ByteBuffer() { _buffer = null; this.size = 0; } public ByteBuffer(int size = 0) { _buffer = new byte[size]; this.size = size; } public void SetSize(int newSize) { if (_buffer == null || _buffer.Length < newSize) { byte[] newBuffer = new byte[newSize]; if (_buffer != null) System.Buffer.BlockCopy(_buffer, 0, newBuffer, 0, _buffer.Length); _buffer = newBuffer; } size = newSize; } public void BufferCopy(byte[] source, int src, int dest, int length) { System.Buffer.BlockCopy(source, src, _buffer, dest, length); } public void BufferCopy(ByteBuffer source, int src, int dest, int length) { System.Buffer.BlockCopy(source._buffer, src, _buffer, dest, length); } public byte this[int index] { get { if (index < 0 || index > size) throw new System.IndexOutOfRangeException(); return _buffer[index]; } set { if (index < 0 || index > size) throw new System.IndexOutOfRangeException(); _buffer[index] = value; } } } } <|start_filename|>ReliableNetcode/PacketHeader.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Text; using ReliableNetcode.Utils; namespace ReliableNetcode { internal class SentPacketData { public double time; public bool acked; public uint packetBytes; } internal class ReceivedPacketData { public double time; public uint packetBytes; } internal class FragmentReassemblyData { public ushort Sequence; public ushort Ack; public uint AckBits; public int NumFragmentsReceived; public int NumFragmentsTotal; public ByteBuffer PacketDataBuffer = new ByteBuffer(); public int PacketBytes; public int HeaderOffset; public bool[] FragmentReceived = new bool[256]; public void StoreFragmentData(byte channelID, ushort sequence, ushort ack, uint ackBits, int fragmentID, int fragmentSize, byte[] fragmentData, int fragmentBytes) { int copyOffset = 0; if (fragmentID == 0) { byte[] packetHeader = BufferPool.GetBuffer(Defines.MAX_PACKET_HEADER_BYTES); int headerBytes = PacketIO.WritePacketHeader(packetHeader, channelID, sequence, ack, ackBits); this.HeaderOffset = Defines.MAX_PACKET_HEADER_BYTES - headerBytes; if (this.PacketDataBuffer.Length < (Defines.MAX_PACKET_HEADER_BYTES + fragmentSize)) this.PacketDataBuffer.SetSize(Defines.MAX_PACKET_HEADER_BYTES + fragmentSize); this.PacketDataBuffer.BufferCopy(packetHeader, 0, this.HeaderOffset, headerBytes); copyOffset = headerBytes; fragmentBytes -= headerBytes; BufferPool.ReturnBuffer(packetHeader); } int writePos = Defines.MAX_PACKET_HEADER_BYTES + fragmentID * fragmentSize; int end = writePos + fragmentBytes; if (this.PacketDataBuffer.Length < end) this.PacketDataBuffer.SetSize(end); if (fragmentID == NumFragmentsTotal - 1) { this.PacketBytes = (this.NumFragmentsTotal - 1) * fragmentSize + fragmentBytes; } this.PacketDataBuffer.BufferCopy(fragmentData, copyOffset, Defines.MAX_PACKET_HEADER_BYTES + fragmentID * fragmentSize, fragmentBytes); } } }
gresolio/ReliableNetcode.NET
<|start_filename|>sources/converter.cpp<|end_filename|> #include "converter.hpp" int32_t* cvtMat2Int32(const cv::Mat& srcImage) { int32_t *result = new int32_t[srcImage.cols*srcImage.rows]; int offset = 0; for (int i = 0; i<srcImage.cols*srcImage.rows * 3; i += 3) { int32_t blue = srcImage.data[i]; int32_t green = srcImage.data[i + 1]; int32_t red = srcImage.data[i + 2]; result[offset++] = 0xff000000 | ((((int32_t)red) << 16) & 0xff0000) | ((((int32_t)green) << 8) & 0xff00) | ((int32_t)blue); } return result; } void cvtInt322Mat(int32_t *pxArray, cv::Mat& outImage) { int offset = 0; for (int i = 0; i<outImage.cols*outImage.rows * 3; i += 3) { int32_t a = pxArray[offset++]; int32_t blue = a & 0xff; int32_t green = ((a >> 8) & 0xff); int32_t red = ((a >> 16) & 0xff); outImage.data[i] = blue; outImage.data[i + 1] = green; outImage.data[i + 2] = red; } return; } <|start_filename|>sources/resizeOMP.cpp<|end_filename|> #include "resizeOMP.hpp" //#include "omp.h" int* resizeBilinear_omp(int* pixels, int w, int h, int w2, int h2) { int32_t* temp = new int32_t[w2*h2]; float x_ratio = ((float)(w - 1)) / w2; float y_ratio = ((float)(h - 1)) / h2; omp_set_num_threads(24); #pragma omp parallel //num_threads(8) { #pragma omp for //schedule(static, w /24) for (int i = 0; i < h2; i++) { int32_t a, b, c, d, x, y, index; float x_diff, y_diff, blue, red, green; int offset = i*w2; for (int j = 0; j < w2; j++) { x = (int)(x_ratio * j); y = (int)(y_ratio * i); x_diff = (x_ratio * j) - x; y_diff = (y_ratio * i) - y; index = (y*w + x); a = pixels[index]; b = pixels[index + 1]; c = pixels[index + w]; d = pixels[index + w + 1]; // blue element // Yb = Ab(1-w)(1-h) + Bb(w)(1-h) + Cb(h)(1-w) + Db(wh) blue = (a & 0xff)*(1 - x_diff)*(1 - y_diff) + (b & 0xff)*(x_diff)*(1 - y_diff) + (c & 0xff)*(y_diff)*(1 - x_diff) + (d & 0xff)*(x_diff*y_diff); // green element // Yg = Ag(1-w)(1-h) + Bg(w)(1-h) + Cg(h)(1-w) + Dg(wh) green = ((a >> 8) & 0xff)*(1 - x_diff)*(1 - y_diff) + ((b >> 8) & 0xff)*(x_diff)*(1 - y_diff) + ((c >> 8) & 0xff)*(y_diff)*(1 - x_diff) + ((d >> 8) & 0xff)*(x_diff*y_diff); // red element // Yr = Ar(1-w)(1-h) + Br(w)(1-h) + Cr(h)(1-w) + Dr(wh) red = ((a >> 16) & 0xff)*(1 - x_diff)*(1 - y_diff) + ((b >> 16) & 0xff)*(x_diff)*(1 - y_diff) + ((c >> 16) & 0xff)*(y_diff)*(1 - x_diff) + ((d >> 16) & 0xff)*(x_diff*y_diff); temp[offset++] = 0xff000000 | ((((int32_t)red) << 16) & 0xff0000) | ((((int32_t)green) << 8) & 0xff00) | ((int32_t)blue); } } } return temp; } <|start_filename|>include/converter.hpp<|end_filename|> #include <stdint.h> #include <opencv2/opencv.hpp> int32_t* cvtMat2Int32(const cv::Mat& srcImage); void cvtInt322Mat(int32_t *pxArray, cv::Mat& outImage); <|start_filename|>include/resizeOMP.hpp<|end_filename|> #include <stdint.h> #include <omp.h> #include <stdio.h> int* resizeBilinear_omp(int* pixels, int w, int h, int w2, int h2); <|start_filename|>include/resizeGPU.cuh<|end_filename|> #include <cuda.h> #include <stdint.h> #include <stdio.h> int* resizeBilinear_gpu(int w, int h, int w2, int h2); void initGPU(const int maxResolutionX, const int maxResolutionY); void deinitGPU(); void reAllocPinned(int w, int h, int w2, int h2, int32_t* dataSource); void freePinned(); <|start_filename|>include/resizeCPU.hpp<|end_filename|> #include <stdint.h> int* resizeBilinear_cpu(int* pixels, int w, int h, int w2, int h2);
royinx/BilinearImageResize
<|start_filename|>css/osgh.user.css<|end_filename|> /* ==UserStyle== @name Old School GitHub @version 1.8.0 @description Reverts most of GitHub to its classic look @license MIT @author daattali @homepageURL https://github.com/daattali/oldschool-github-extension @namespace daattali ==/UserStyle== */ @-moz-document url-prefix("https://github.com/"), url-prefix("https://gist.github.com/") { /* Move page headers to the middle */ @media (min-width: 1280px) { main > div.color-bg-secondary, main > div.hx_page-header-bg { box-shadow: inset 0 -1px 0 #e1e4e8; } main > div.color-bg-secondary > div, main > div.color-bg-secondary > nav, main > div.hx_page-header-bg > div, main > div.hx_page-header-bg > nav { max-width: 1280px; margin-left: auto; margin-right: auto; } main > div.color-bg-secondary > nav > ul > li > a, main > div.hx_page-header-bg > nav > ul > li > a { visibility: visible !important; } main > div.color-bg-secondary > nav .js-responsive-underlinenav-overflow, main > div.hx_page-header-bg > nav .js-responsive-underlinenav-overflow { display: none; } } /* Slightly more compact header tabs (excluding sticky header on user profile page) */ body:not(.page-profile) .UnderlineNav-body .UnderlineNav-item { padding: 5px 14px 3px; } /* Highlight the selected page in the header (excluding sticky header on user profile page) */ body:not(.page-profile) .UnderlineNav-item.selected { border-radius: 3px 3px 0 0; background: #fff; border-left: 1px solid #e1e4e8; border-right: 1px solid #e1e4e8; border-bottom: none; border-top: 3px solid #e36209; padding-top: 0; } /* Add the row separators in the list of files on a repo's main page */ .js-active-navigation-container .Box-row + .Box-row { border-top: 1px solid #eaecef !important; } /* Slightly more compact file list rows and box headers */ .js-active-navigation-container .Box-row { padding-top: 6px !important; padding-bottom: 6px !important; } .js-active-navigation-container .Box-row.p-0 { padding-top: 0 !important; padding-bottom: 0 !important; } .repository-content .gutter-condensed .Box .Box-header { padding-top: 10px; padding-bottom: 10px; } /* Content boxes border radius revert */ body .Box { border-radius: 3px; } body .Box .Box-header, body .Box-row:first-of-type { border-top-left-radius: 3px; border-top-right-radius: 3px; } /* Buttons border radius revert - excluding button groups and other special buttons */ /* By chaining all these :not() selectors this rule is very specific and hard to override. So it will need to grown even longer as more button types need to be excluded. It's possible that setting all button border radiuses to 3px and then overriding where they should be square would be a better approach. */ :not(.input-group-button) > :not(.BtnGroup):not(.subnav-search-context):not(.input-group-button) > .btn:not(.BtnGroup-item):not(.btn-with-count):not(.get-repo-btn) { border-radius: 3px; } /* Button groups & special buttons border radius revert - only affects specific corners */ body .BtnGroup-item:first-child, body .BtnGroup-parent:first-child .BtnGroup-item, .input-group .input-group-button:first-child .btn, body .subnav-item:first-child, .subnav-search-context .btn, body .btn.btn-with-count { border-radius: 3px 0 0 3px; } body .BtnGroup-item:last-child, body .BtnGroup-parent:last-child .BtnGroup-item, .input-group .input-group-button:last-child .btn, body .subnav-item:last-child, .subnav-search-context + .subnav-search .subnav-search-input, body .social-count { border-radius: 0 3px 3px 0; } /* Status/state and issue labels border radius revert */ body .IssueLabel { border-radius: 2px; } body .IssueLabel--big.lh-condensed, body .State { border-radius: 3px; } /* Remove the circular user images */ body .avatar-user { border-radius: 3px !important; } /* Box border was slightly darker in classic design */ body .Box:not(.Box--danger), body .Box-header { border-color: #d1d5da; } /* Hide duplicated red top border of danger boxes - probably a github oversight */ body .Box--danger .Box-row:first-of-type { border-top-color: transparent; } /* Form field borders were slightly darker in classic design */ body .form-control { border-color: #d1d5da; } /* README should have a slight background */ #readme .Box-header { background: #f6f8fa !important; border: 1px solid #d1d5da !important; } /* Font weight revert for issue counters and labels */ main > div.bg-gray-light > nav .Counter, body .IssueLabel--big.lh-condensed, .IssueLabel { font-weight: 600; } /* Rows in Issues page have way too much whitespace */ .js-issue-row.Box-row { padding-top: 0 !important; padding-bottom: 0 !important; } /* Classic buttons */ body .btn { transition: none !important; font-weight: 600; background-image: linear-gradient(-180deg, #fafbfc 0%, #eff3f6 90%); /* Set only border color here (not width) to avoid adding extra borders that shouldn't exists */ border-color: rgba(27,31,35,0.2); /* these three background properties help the border color blend in better with the button color*/ background-repeat: repeat-x; background-position: -1px -1px; background-size: 110% 110%; box-shadow: none; } body .btn:hover { background-image: linear-gradient(-180deg, #f0f3f6 0%, #e6ebf1 90%); border-color: rgba(27,31,35,0.35); } body [open] > .btn, body [open] > summary > .btn, body .btn:active { background: #e9ecef; border-color: rgba(27,31,35,0.35); box-shadow: inset 0 0.15em 0.3em rgba(27,31,35,0.15); } /* The github stylesheet contains this rule: body.intent-mouse a:focus { box-shadow: none } It overrides the rule above and removes the inset shadow. This extra rule has higher specificity to beat it and put the shadow back. Adding !important to box-shadow above could also do the trick. */ html > body.intent-mouse [open] > .btn, html > body.intent-mouse .btn:active { box-shadow: inset 0 0.15em 0.3em rgba(27,31,35,0.15); } body .btn[disabled] { cursor: not-allowed; color: #959da5; background: #fafbfc; border-color: rgba(27,31,35,.15); } /* Revert button icon colors/opacity */ body .btn .octicon { color: #24292e; } body .btn .dropdown-caret { opacity: 1; } body .btn-primary .octicon { color: #fff; } /* Match social count boxes to button styles */ body .social-count { border-color: rgba(27,31,35,0.2); box-shadow: none; } body .btn-primary { background-image: linear-gradient(-180deg, #34d058 0%, #28a745 90%); } body .btn-primary:hover { background-image: linear-gradient(-180deg, #2fcb53 0%, #269f42 90%); border-color: rgba(27,31,35,0.5); } body [open]>.btn-primary, body .btn-primary:active { background: #279f43; border-color: rgba(27,31,35,0.5); box-shadow: inset 0 0.15em 0.3em rgba(27,31,35,0.15); } body .btn-primary[disabled] { color: hsla(0,0%,100%,.8); background: #94d3a2; border-color: rgba(27,31,35,.1); box-shadow: 0 1px 0 rgba(27,31,35,.1), inset 0 1px 0 hsla(0,0%,100%,.03); } body .btn-danger { color: #cb2431; } body .btn-danger:hover { color: #fff; background: #cb2431; border-color: rgba(27,31,35,.15); box-shadow: 0 1px 0 rgba(27,31,35,.1), inset 0 1px 0 hsla(0,0%,100%,.03); } body [open]>.btn-danger, body .btn-danger:active { color: #fff; background: #be222e; border-color: rgba(27,31,35,.15); box-shadow: inset 0 1px 0 rgba(134,24,29,.2); } body .btn-danger[disabled] { color: rgba(203,36,49,.5); background: #fafbfc; border-color: rgba(27,31,35,.15); box-shadow: 0 1px 0 rgba(27,31,35,.04), inset 0 1px 0 hsla(0,0%,100%,.25); } body .btn-outline { color: #0366d6; background: #fff; } body .btn-outline:hover, body .full-commit .btn-outline:not(:disabled):hover { color: #fff; background: #0366d6; border-color: rgba(27,31,35,.15); box-shadow: 0 1px 0 rgba(27,31,35,.1), inset 0 1px 0 hsla(0,0%,100%,.03); } body [open]>.btn-outline, body .btn-outline:active { color: #fff; background: #035fc7; border-color: rgba(27,31,35,.15); box-shadow: inset 0 1px 0 rgba(5,38,76,.2); } body .btn-outline[disabled] { color: rgba(3,102,214,.5); background: #fafbfc; border-color: rgba(27,31,35,.15); box-shadow: 0 1px 0 rgba(27,31,35,.04), inset 0 1px 0 hsla(0,0%,100%,.25); } /* User profile page: move status badge back below avatar image */ .user-status-container .user-status-circle-badge-container { position: unset; width: auto; height: auto; margin: 4px 0 0; } .user-status-circle-badge-container .user-status-circle-badge { border-radius: 3px; width: 100%; } body .user-status-circle-badge .user-status-message-wrapper { width: 100%; opacity: 1; } body .user-status-circle-badge-container .user-status-emoji-container { margin-right: 8px !important; } body .user-status-circle-badge-container .user-status-circle-badge, body .user-status-circle-badge-container:hover .user-status-circle-badge { box-shadow: none; } .user-status-message-wrapper .css-truncate.css-truncate-target { white-space: auto; } .user-status-message-wrapper.no-wrap { white-space: normal !important; } } <|start_filename|>manifest.json<|end_filename|> { "name": "Old School GitHub", "version": "1.8.0", "manifest_version": 2, "description": "Revert GitHub's UI back to its classic look (before the June 23, 2020 update that has a flat, rounded and more whitespaced design).", "icons": { "16": "img/icon-16.png", "48": "img/icon-48.png", "128": "img/icon-128.png" }, "content_scripts": [ { "matches": [ "https://github.com/*", "https://gist.github.com/*" ], "css": ["css/osgh.css"], "run_at": "document_start" } ], "homepage_url": "https://github.com/daattali/oldschool-github-extension" }
daattali/oldschool-github-extension
<|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/UserLoginLogQueryReq.java<|end_filename|> package org.clever.security.dto.request; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.request.QueryByPage; import java.util.Date; /** * 作者: lzw<br/> * 创建时间:2018-10-21 22:12 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class UserLoginLogQueryReq extends QueryByPage { @ApiModelProperty("用户登录名") private String username; @ApiModelProperty("系统名称") private String sysName; @ApiModelProperty("登录时间 - 开始") private Date loginTimeStart; @ApiModelProperty("登录时间 - 结束") private Date loginTimeEnd; @ApiModelProperty("登录状态,0:未知;1:已登录;2:登录已过期") private Integer loginState; @ApiModelProperty("手机号") private String telephone; @ApiModelProperty("邮箱") private String email; } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/exception/BadLoginTypeException.java<|end_filename|> package org.clever.security.exception; import org.springframework.security.core.AuthenticationException; /** * 不支持的登录类型 * <p> * 作者: lzw<br/> * 创建时间:2018-09-24 12:51 <br/> */ public class BadLoginTypeException extends AuthenticationException { public BadLoginTypeException(String msg) { super(msg); } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/Constant.java<|end_filename|> package org.clever.security; /** * 作者: lzw<br/> * 创建时间:2019-04-25 19:57 <br/> */ public class Constant { /** * 配置文件前缀 */ public static final String ConfigPrefix = "clever.security"; /** * 登录请求数据 Key */ public static final String Login_Data_Body_Request_Key = "Login_Data_Body_Request_Key"; /** * 请求登录用户名 Key */ public static final String Login_Username_Request_Key = "Login_Username_Request_Key"; /** * 登录验证码 Key */ public static final String Login_Captcha_Session_Key = "Login_Captcha_Session_Key"; /** * 登录失败次数 Key */ public static final String Login_Fail_Count_Session_Key = "Login_Fail_Count_Session_Key"; } <|start_filename|>clever-security-server/src/main/java/org/clever/security/service/ServiceSysService.java<|end_filename|> package org.clever.security.service; import lombok.extern.slf4j.Slf4j; import org.clever.common.exception.BusinessException; import org.clever.security.entity.ServiceSys; import org.clever.security.mapper.ServiceSysMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Objects; /** * 作者: lzw<br/> * 创建时间:2018-10-22 20:36 <br/> */ @Transactional(readOnly = true) @Service @Slf4j public class ServiceSysService { @Autowired private ServiceSysMapper serviceSysMapper; public List<ServiceSys> selectAll() { return serviceSysMapper.selectList(null); } @Transactional public ServiceSys registerSys(ServiceSys serviceSys) { ServiceSys existsSys = serviceSysMapper.getByUnique(serviceSys.getSysName(), serviceSys.getRedisNameSpace()); if (existsSys != null) { if (!Objects.equals(existsSys.getSysName(), serviceSys.getSysName()) || !Objects.equals(existsSys.getRedisNameSpace(), serviceSys.getRedisNameSpace()) || !Objects.equals(existsSys.getLoginModel(), serviceSys.getLoginModel())) { throw new BusinessException( "服务系统注册失败,存在冲突(SysName: " + existsSys.getSysName() + ", redisNameSpace: " + existsSys.getRedisNameSpace() + ", loginModel: " + existsSys.getLoginModel() + ")" ); } return existsSys; } // 注册系统 serviceSysMapper.insert(serviceSys); return serviceSysMapper.selectById(serviceSys.getId()); } @Transactional public ServiceSys delServiceSys(String sysName) { ServiceSys existsSys = serviceSysMapper.getBySysName(sysName); if (existsSys == null) { throw new BusinessException("系统不存在:" + sysName); } serviceSysMapper.deleteById(existsSys.getId()); return existsSys; } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/token/login/UsernamePasswordToken.java<|end_filename|> package org.clever.security.token.login; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.clever.security.LoginTypeConstant; /** * 作者: lzw<br/> * 创建时间:2019-04-27 21:19 <br/> */ @ToString public class UsernamePasswordToken extends BaseLoginToken { /** * 用户名 */ @JsonProperty(value = "principal", access = JsonProperty.Access.WRITE_ONLY) @Setter @Getter private String username; /** * 密码 */ @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) @Setter @Getter private String password; public UsernamePasswordToken() { super(LoginTypeConstant.UsernamePassword); } public UsernamePasswordToken(String username, String password) { this(); this.username = username; this.password = password; } /** * 擦除密码 */ @Override public void eraseCredentials() { super.eraseCredentials(); password = ""; } /** * 返回密码 */ @Override public Object getCredentials() { return password; } /** * 返回用户登录唯一ID */ @Override public Object getPrincipal() { return username; } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/handler/UserLoginSuccessHandler.java<|end_filename|> package org.clever.security.handler; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.clever.common.utils.CookieUtils; import org.clever.common.utils.mapper.JacksonMapper; import org.clever.security.Constant; import org.clever.security.LoginModel; import org.clever.security.client.UserLoginLogClient; import org.clever.security.config.SecurityConfig; import org.clever.security.config.model.LoginConfig; import org.clever.security.dto.request.UserLoginLogAddReq; import org.clever.security.dto.response.JwtLoginRes; import org.clever.security.dto.response.LoginRes; import org.clever.security.dto.response.UserRes; import org.clever.security.entity.EnumConstant; import org.clever.security.repository.LoginFailCountRepository; import org.clever.security.repository.RedisJwtRepository; import org.clever.security.token.JwtAccessToken; import org.clever.security.utils.AuthenticationUtils; import org.clever.security.utils.HttpRequestUtils; import org.clever.security.utils.HttpResponseUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.RedirectStrategy; import org.springframework.security.web.WebAttributes; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.security.web.savedrequest.HttpSessionRequestCache; import org.springframework.security.web.savedrequest.NullRequestCache; import org.springframework.security.web.savedrequest.RequestCache; import org.springframework.security.web.savedrequest.SavedRequest; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.Date; import java.util.List; /** * 自定义登录成功处理类 * <p> * 作者: lzw<br/> * 创建时间:2018-03-16 11:06 <br/> */ @Component @Slf4j public class UserLoginSuccessHandler implements AuthenticationSuccessHandler { private final String defaultRedirectUrl = "/home.html"; private SecurityConfig securityConfig; private RequestCache requestCache; private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); @Autowired private RedisJwtRepository redisJwtRepository; @Autowired private LoginFailCountRepository loginFailCountRepository; @Autowired private UserLoginLogClient userLoginLogClient; public UserLoginSuccessHandler(SecurityConfig securityConfig) { this.securityConfig = securityConfig; if (LoginModel.jwt.equals(securityConfig.getLoginModel())) { requestCache = new NullRequestCache(); } else { requestCache = new HttpSessionRequestCache(); } } @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { SavedRequest savedRequest = null; if (LoginModel.session.equals(securityConfig.getLoginModel())) { savedRequest = requestCache.getRequest(request, response); } requestCache.removeRequest(request, response); clearAuthenticationAttributes(request, authentication.getName()); if (LoginModel.jwt.equals(securityConfig.getLoginModel())) { // 登录成功保存 JwtAccessToken JwtRefreshToken JwtAccessToken jwtAccessToken = redisJwtRepository.saveJwtToken(AuthenticationUtils.getSecurityContextToken(authentication)); redisJwtRepository.saveSecurityContext(new SecurityContextImpl(authentication)); log.info("### 已保存 JWT Token 和 SecurityContext"); // 写入登录成功日志 addLoginLog(authentication, jwtAccessToken); // 登录成功 - 返回JSon数据 sendJsonData(response, authentication, jwtAccessToken); return; } LoginConfig login = securityConfig.getLogin(); if (login.getLoginSuccessNeedRedirect() != null) { if (login.getLoginSuccessNeedRedirect()) { // 跳转 sendRedirect(request, response, getRedirectUrl(savedRequest, login.getLoginSuccessRedirectPage())); } else { // 不跳转 sendJsonData(response, authentication, null); } return; } // 根据当前请求类型判断是否需要跳转页面 if (HttpRequestUtils.isJsonResponseByLogin(request)) { sendJsonData(response, authentication, null); return; } // 根据savedRequest判断是否需要跳转 (之前访问的Url是一个页面才跳转) if (savedRequest != null && isJsonResponseBySavedRequest(savedRequest)) { sendJsonData(response, authentication, null); return; } sendRedirect(request, response, getRedirectUrl(savedRequest, login.getLoginSuccessRedirectPage())); } /** * 清除登录异常信息 */ private void clearAuthenticationAttributes(HttpServletRequest request, String username) { if (LoginModel.jwt.equals(securityConfig.getLoginModel())) { loginFailCountRepository.deleteLoginFailCount(username); } HttpSession session = request.getSession(false); if (session == null) { return; } session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); session.removeAttribute(Constant.Login_Captcha_Session_Key); session.removeAttribute(Constant.Login_Fail_Count_Session_Key); } /** * 写入登录成功日志(JwtToken日志) */ @SuppressWarnings("Duplicates") private void addLoginLog(Authentication authentication, JwtAccessToken jwtAccessToken) { String JwtTokenId = jwtAccessToken.getClaims().getId(); String loginIp = null; if (authentication.getDetails() instanceof WebAuthenticationDetails) { WebAuthenticationDetails webAuthenticationDetails = (WebAuthenticationDetails) authentication.getDetails(); loginIp = webAuthenticationDetails.getRemoteAddress(); } UserLoginLogAddReq userLoginLog = new UserLoginLogAddReq(); userLoginLog.setSysName(securityConfig.getSysName()); userLoginLog.setUsername(authentication.getName()); userLoginLog.setLoginTime(new Date()); userLoginLog.setLoginIp(StringUtils.trimToEmpty(loginIp)); userLoginLog.setAuthenticationInfo(JacksonMapper.nonEmptyMapper().toJson(authentication)); userLoginLog.setLoginModel(EnumConstant.ServiceSys_LoginModel_1); userLoginLog.setSessionId(StringUtils.trimToEmpty(JwtTokenId)); userLoginLog.setLoginState(EnumConstant.UserLoginLog_LoginState_1); try { userLoginLogClient.addUserLoginLog(userLoginLog); log.info("### 写入登录成功日志 [{}]", authentication.getName()); } catch (Exception e) { log.error("写入登录成功日志失败 [{}]", authentication.getName(), e); } } /** * 根据savedRequest判断是否需要跳转 */ private boolean isJsonResponseBySavedRequest(SavedRequest savedRequest) { if (savedRequest == null) { return true; } boolean jsonFlag = false; boolean ajaxFlag = false; List<String> acceptHeaders = savedRequest.getHeaderValues("Accept"); if (acceptHeaders != null) { for (String accept : acceptHeaders) { if ("application/json".equalsIgnoreCase(accept)) { jsonFlag = true; break; } } } List<String> ajaxHeaders = savedRequest.getHeaderValues("X-Requested-With"); if (ajaxHeaders != null) { for (String ajax : ajaxHeaders) { if ("XMLHttpRequest".equalsIgnoreCase(ajax)) { ajaxFlag = true; break; } } } return jsonFlag || ajaxFlag; } /** * 获取需要跳转的Url */ private String getRedirectUrl(SavedRequest savedRequest, String defaultUrl) { String url = null; if (savedRequest != null && !isJsonResponseBySavedRequest(savedRequest)) { url = savedRequest.getRedirectUrl(); } if (StringUtils.isBlank(url)) { url = defaultUrl; } if (StringUtils.isBlank(url)) { url = defaultRedirectUrl; } return url; } /** * 直接返回Json数据 */ private void sendJsonData(HttpServletResponse response, Authentication authentication, JwtAccessToken jwtAccessToken) { Object resData; if (jwtAccessToken == null) { UserRes userRes = AuthenticationUtils.getUserRes(authentication); resData = new LoginRes(true, "登录成功", userRes); } else { if (securityConfig.getTokenConfig().isUseCookie()) { CookieUtils.setRooPathCookie(response, securityConfig.getTokenConfig().getJwtTokenKey(), jwtAccessToken.getToken()); } response.setHeader(securityConfig.getTokenConfig().getJwtTokenKey(), jwtAccessToken.getToken()); UserRes userRes = AuthenticationUtils.getUserRes(authentication); resData = new JwtLoginRes(true, "登录成功", userRes, jwtAccessToken.getToken(), jwtAccessToken.getRefreshToken()); } HttpResponseUtils.sendJsonBy200(response, resData); log.info("### 登录成功不需要跳转 -> [{}]", resData); } /** * 页面跳转 (重定向) */ private void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException { if (StringUtils.isBlank(url)) { url = defaultRedirectUrl; } log.info("### 登录成功跳转Url(重定向) -> {}", url); if (!response.isCommitted()) { redirectStrategy.sendRedirect(request, response, url); } } } <|start_filename|>clever-security-server/src/main/java/org/clever/security/service/ManageByRoleService.java<|end_filename|> package org.clever.security.service; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.clever.common.exception.BusinessException; import org.clever.common.utils.mapper.BeanMapper; import org.clever.security.dto.request.RoleQueryPageReq; import org.clever.security.dto.request.RoleUpdateReq; import org.clever.security.dto.response.RoleInfoRes; import org.clever.security.entity.Role; import org.clever.security.mapper.PermissionMapper; import org.clever.security.mapper.RoleMapper; import org.clever.security.service.internal.ReLoadSessionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Objects; /** * 作者: lzw<br/> * 创建时间:2018-10-02 23:52 <br/> */ @Transactional(readOnly = true) @Service @Slf4j public class ManageByRoleService { @Autowired private RoleMapper roleMapper; @Autowired private PermissionMapper permissionMapper; @Autowired private ReLoadSessionService reLoadSessionService; public IPage<Role> findByPage(RoleQueryPageReq roleQueryPageReq) { Page<Role> page = new Page<>(roleQueryPageReq.getPageNo(), roleQueryPageReq.getPageSize()); page.setRecords(roleMapper.findByPage(roleQueryPageReq, page)); return page; } @Transactional public Role addRole(Role role) { Role oldRole = roleMapper.getByName(role.getName()); if (oldRole != null) { throw new BusinessException("角色[" + role.getName() + "]已经存在"); } roleMapper.insert(role); return roleMapper.selectById(role.getId()); } @Transactional public Role updateRole(String name, RoleUpdateReq roleUpdateReq) { Role oldRole = roleMapper.getByName(name); if (oldRole == null) { throw new BusinessException("角色[" + roleUpdateReq.getName() + "]不存在"); } Role update = new Role(); update.setId(oldRole.getId()); if (StringUtils.isNotBlank(roleUpdateReq.getName()) && !Objects.equals(roleUpdateReq.getName(), oldRole.getName())) { update.setName(roleUpdateReq.getName()); } update.setDescription(roleUpdateReq.getDescription()); roleMapper.updateById(update); if (update.getName() != null) { roleMapper.updateUserRoleByRoleName(oldRole.getName(), roleUpdateReq.getName()); roleMapper.updateRolePermissionByRoleName(oldRole.getName(), roleUpdateReq.getName()); // 更新受影响用户的Session reLoadSessionService.onChangeRole(update.getName()); } return roleMapper.getByName(roleUpdateReq.getName()); } @Transactional public Role delRole(String name) { Role oldRole = roleMapper.getByName(name); if (oldRole == null) { throw new BusinessException("角色[" + name + "]不存在"); } int count = roleMapper.deleteById(oldRole.getId()); if (count > 0) { roleMapper.delUserRoleByRoleName(oldRole.getName()); roleMapper.delRolePermissionByRoleName(oldRole.getName()); // 更新受影响用户的Session reLoadSessionService.onChangeRole(name); } return oldRole; } public RoleInfoRes getRoleInfo(String name) { Role role = roleMapper.getByName(name); if (role == null) { return null; } RoleInfoRes roleInfoRes = BeanMapper.mapper(role, RoleInfoRes.class); roleInfoRes.setPermissionList(permissionMapper.findByRoleName(role.getName())); return roleInfoRes; } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/RoleUpdateReq.java<|end_filename|> package org.clever.security.dto.request; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.request.BaseRequest; import org.hibernate.validator.constraints.Length; /** * 作者: lzw<br/> * 创建时间:2018-10-03 9:30 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class RoleUpdateReq extends BaseRequest { @ApiModelProperty("角色名称") @Length(max = 63) private String name; @ApiModelProperty("角色说明") @Length(max = 1023) private String description; } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/UserBindSysRes.java<|end_filename|> package org.clever.security.dto.response; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.response.BaseResponse; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-10-03 21:44 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class UserBindSysRes extends BaseResponse { @ApiModelProperty("用户名") private String username; @ApiModelProperty("系统名集合") private List<String> sysNameList; } <|start_filename|>clever-security-server/src/main/java/org/clever/security/mapper/RoleMapper.java<|end_filename|> package org.clever.security.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.metadata.IPage; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.clever.security.dto.request.RoleQueryPageReq; import org.clever.security.entity.Permission; import org.clever.security.entity.Role; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Set; /** * 作者: lzw<br/> * 创建时间:2018-09-17 9:11 <br/> */ @Repository @Mapper public interface RoleMapper extends BaseMapper<Role> { Role getByName(@Param("name") String name); List<Role> findByUsername(@Param("username") String username); List<Role> findByPage(@Param("query") RoleQueryPageReq query, IPage page); int updateUserRoleByRoleName(@Param("oldName") String oldName, @Param("newName") String newName); int updateRolePermissionByRoleName(@Param("oldName") String oldName, @Param("newName") String newName); int updateRolePermissionByPermissionStr(@Param("oldPermissionStr") String oldPermissionStr, @Param("newPermissionStr") String newPermissionStr); int delUserRoleByRoleName(@Param("name") String name); int delRolePermissionByRoleName(@Param("name") String name); int addPermission(@Param("roleName") String roleName, @Param("permissionStr") String permissionStr); int delPermission(@Param("roleName") String roleName, @Param("permissionStr") String permissionStr); int existsByRole(@Param("roleName") String roleName); List<Permission> findPermissionByRoleName(@Param("roleName") String roleName); int existsRolePermission(@Param("roleName") String roleName, @Param("permissionStr") String permissionStr); List<String> findUsernameByRoleName(@Param("roleName") String roleName); List<String> findRoleNameByPermissionStr(@Param("permissionStr") String permissionStr); List<String> findRoleNameByPermissionStrList(@Param("permissionStrList") Set<String> permissionStrList); } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/rememberme/RememberMeRepository.java<|end_filename|> package org.clever.security.rememberme; import lombok.extern.slf4j.Slf4j; import org.clever.security.Constant; import org.clever.security.client.RememberMeTokenClient; import org.clever.security.config.SecurityConfig; import org.clever.security.dto.request.RememberMeTokenAddReq; import org.clever.security.dto.request.RememberMeTokenUpdateReq; import org.clever.security.entity.RememberMeToken; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.security.web.authentication.rememberme.PersistentRememberMeToken; import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository; import org.springframework.stereotype.Component; import java.util.Date; /** * 存储“记住我”功能产生的Token * 作者: lzw<br/> * 创建时间:2018-09-21 19:52 <br/> */ @ConditionalOnProperty(prefix = Constant.ConfigPrefix, name = "login-model", havingValue = "session") @Component @Slf4j public class RememberMeRepository implements PersistentTokenRepository { @Autowired private SecurityConfig securityConfig; @Autowired private RememberMeTokenClient rememberMeTokenClient; @Override public void createNewToken(PersistentRememberMeToken token) { RememberMeTokenAddReq req = new RememberMeTokenAddReq(); req.setSysName(securityConfig.getSysName()); req.setSeries(token.getSeries()); req.setUsername(token.getUsername()); req.setToken(token.getTokenValue()); req.setLastUsed(token.getDate()); rememberMeTokenClient.addRememberMeToken(req); } @Override public void updateToken(String series, String tokenValue, Date lastUsed) { RememberMeTokenUpdateReq req = new RememberMeTokenUpdateReq(); req.setToken(tokenValue); req.setLastUsed(lastUsed); rememberMeTokenClient.updateRememberMeToken(series, req); } @Override public PersistentRememberMeToken getTokenForSeries(String seriesId) { RememberMeToken rememberMeToken = rememberMeTokenClient.getRememberMeToken(seriesId); if (rememberMeToken == null) { return null; } return new PersistentRememberMeToken( rememberMeToken.getUsername(), rememberMeToken.getSeries(), rememberMeToken.getToken(), rememberMeToken.getLastUsed() ); } @Override public void removeUserTokens(String username) { rememberMeTokenClient.delRememberMeToken(username); } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/UserAuthenticationRes.java<|end_filename|> package org.clever.security.dto.response; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.response.BaseResponse; /** * 作者: lzw<br/> * 创建时间:2018-10-24 11:06 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class UserAuthenticationRes extends BaseResponse { @ApiModelProperty("登录是否成功") private Boolean success = false; @ApiModelProperty("登录失败消息") private String failMessage; } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/rememberme/RememberMeUserDetailsChecker.java<|end_filename|> package org.clever.security.rememberme; import lombok.extern.slf4j.Slf4j; import org.clever.security.Constant; import org.clever.security.exception.CanNotLoginSysException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsChecker; import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException; import org.springframework.stereotype.Component; /** * 作者: lzw<br/> * 创建时间:2018-10-22 15:50 <br/> */ @ConditionalOnProperty(prefix = Constant.ConfigPrefix, name = "login-model", havingValue = "session") @Component @Slf4j public class RememberMeUserDetailsChecker implements UserDetailsChecker { @Autowired @Qualifier("DefaultPreAuthenticationChecks") private UserDetailsChecker preAuthenticationChecks; @Autowired @Qualifier("DefaultPostAuthenticationChecks") private UserDetailsChecker postAuthenticationChecks; /** * {@link org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices#autoLogin}只处理一下异常 * 1.CookieTheftException<br /> * 2.UsernameNotFoundException<br /> * 3.InvalidCookieException<br /> * 4.AccountStatusException<br /> * 5.RememberMeAuthenticationException<br /> * 由于使用自定义UserDetailsService会抛出其他异常,所以包装处理 */ @Override public void check(UserDetails toCheck) { try { preAuthenticationChecks.check(toCheck); postAuthenticationChecks.check(toCheck); } catch (CanNotLoginSysException e) { throw new RememberMeAuthenticationException(e.getMessage(), e); } } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/authentication/CollectLoginToken.java<|end_filename|> package org.clever.security.authentication; import org.clever.security.token.login.BaseLoginToken; import org.springframework.security.core.AuthenticationException; import javax.servlet.http.HttpServletRequest; import java.io.IOException; /** * 收集用户登录认证信息接口 * <p> * 作者: lzw<br/> * 创建时间:2019-04-26 16:36 <br/> * @see org.clever.security.authentication.collect.CollectUsernamePasswordToken */ public interface CollectLoginToken { String LOGIN_TYPE_PARAM = "loginType"; String CAPTCHA_PARAM = "captcha"; String CAPTCHA_DIGEST_PARAM = "captchaDigest"; String REMEMBER_ME_PARAM = "rememberMe"; /** * 是否支持收集当前请求的登录信息 * * @param request 请求对象 * @param isSubmitBody 提交数据是否是JsonBody格式 * @return 支持解析返回true */ boolean supports(HttpServletRequest request, boolean isSubmitBody) throws IOException; /** * 收集用户登录认证信息 * * @param request 请求对象 * @param isSubmitBody 提交数据是否是JsonBody格式 * @return 返回Authentication子类 */ BaseLoginToken attemptAuthentication(HttpServletRequest request, boolean isSubmitBody) throws AuthenticationException, IOException; } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/PermissionQueryReq.java<|end_filename|> package org.clever.security.dto.request; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.request.QueryByPage; /** * 作者: lzw<br/> * 创建时间:2018-10-03 12:55 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class PermissionQueryReq extends QueryByPage { @ApiModelProperty("系统(或服务)名称") private String sysName; @ApiModelProperty("资源标题(模糊匹配)") private String title; @ApiModelProperty("资源访问所需要的权限标识字符串(模糊匹配)") private String permissionStr; @ApiModelProperty("资源类型(1:请求URL地址, 2:其他资源)") private Integer resourcesType; @ApiModelProperty("Spring Controller类名称(模糊匹配)") private String targetClass; @ApiModelProperty("Spring Controller类的方法名称") private String targetMethod; @ApiModelProperty("资源URL地址(模糊匹配)") private String resourcesUrl; @ApiModelProperty("需要授权才允许访问(1:需要;2:不需要)") private Integer needAuthorization; @ApiModelProperty("Spring Controller路由资源是否存在,0:不存在;1:存在") private Integer targetExist; } <|start_filename|>clever-security-server/src/main/java/org/clever/security/config/GlobalConfig.java<|end_filename|> package org.clever.security.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; /** * 作者: lzw<br/> * 创建时间:2017-12-04 12:44 <br/> */ @Component @ConfigurationProperties(prefix = "clever.config") @Data public class GlobalConfig { /** * 请求数据AES加密 key(Hex编码) */ private String reqAesKey = "<KEY>"; /** * 请求数据AES加密 iv(Hex编码) */ private String reqAesIv = "f0021ea5a06d5a7bade961afe47e9ad9"; } <|start_filename|>clever-security-server/src/main/java/org/clever/security/controller/ManageBySecurityController.java<|end_filename|> package org.clever.security.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.clever.common.server.controller.BaseController; import org.clever.security.dto.request.*; import org.clever.security.dto.response.RoleBindPermissionRes; import org.clever.security.dto.response.UserBindRoleRes; import org.clever.security.dto.response.UserBindSysRes; import org.clever.security.service.ManageBySecurityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-10-03 21:22 <br/> */ @Api("系统、角色、权限分配管理") @RestController @RequestMapping("/api/manage/security") public class ManageBySecurityController extends BaseController { @Autowired private ManageBySecurityService manageBySecurityService; @ApiOperation("为用户设置登录的系统(批量)") @PostMapping("/user_sys") public List<UserBindSysRes> userBindSys(@RequestBody @Validated UserBindSysReq userBindSysReq) { return manageBySecurityService.userBindSys(userBindSysReq); } @ApiOperation("为用户分配角色(批量)") @PostMapping("/user_role") public List<UserBindRoleRes> userBindRole(@RequestBody @Validated UserBindRoleReq userBindSysReq) { return manageBySecurityService.userBindRole(userBindSysReq); } @ApiOperation("为角色分配权限(批量)") @PostMapping("/role_permission") public List<RoleBindPermissionRes> roleBindPermission(@RequestBody @Validated RoleBindPermissionReq roleBindPermissionReq) { return manageBySecurityService.roleBindPermission(roleBindPermissionReq); } @ApiOperation("为用户添加登录的系统(单个)") @PostMapping("/user_sys/bind") public UserBindSysRes userBindSys(@RequestBody @Validated UserSysReq userSysReq) { return manageBySecurityService.userBindSys(userSysReq); } @ApiOperation("为用户删除登录的系统(单个)") @PostMapping("/user_sys/un_bind") public UserBindSysRes userUnBindSys(@RequestBody @Validated UserSysReq userSysReq) { return manageBySecurityService.userUnBindSys(userSysReq); } @ApiOperation("为用户添加角色(单个)") @PostMapping("/user_role/bind") public UserBindRoleRes userBindRole(@RequestBody @Validated UserRoleReq userRoleReq) { return manageBySecurityService.userBindRole(userRoleReq); } @ApiOperation("为用户删除角色(单个)") @PostMapping("/user_role/un_bind") public UserBindRoleRes userUnBindRole(@RequestBody @Validated UserRoleReq userRoleReq) { return manageBySecurityService.userUnBindRole(userRoleReq); } @ApiOperation("为角色添加权限(单个)") @PostMapping("/role_permission/bind") public RoleBindPermissionRes roleBindPermission(@RequestBody @Validated RolePermissionReq rolePermissionReq) { return manageBySecurityService.roleBindPermission(rolePermissionReq); } @ApiOperation("为角色删除权限(单个)") @PostMapping("/role_permission/un_bind") public RoleBindPermissionRes roleUnBindPermission(@RequestBody @Validated RolePermissionReq rolePermissionReq) { return manageBySecurityService.roleUnBindPermission(rolePermissionReq); } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/utils/HttpResponseUtils.java<|end_filename|> package org.clever.security.utils; import org.clever.common.utils.StringUtils; import org.clever.common.utils.mapper.JacksonMapper; import org.springframework.security.authentication.InternalAuthenticationServiceException; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 作者: lzw<br/> * 创建时间:2019-04-29 09:19 <br/> */ public class HttpResponseUtils { private static void sendJson(HttpServletResponse response, Object resData, int status) { if (!response.isCommitted()) { String json; if (resData instanceof String || resData instanceof Byte || resData instanceof Short || resData instanceof Integer || resData instanceof Float || resData instanceof Long || resData instanceof Double || resData instanceof Boolean) { json = String.valueOf(resData); } else { json = JacksonMapper.nonEmptyMapper().toJson(resData); } response.setStatus(status); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json;charset=utf-8"); try { response.getWriter().print(json); } catch (IOException e) { throw new InternalAuthenticationServiceException("返回数据写入响应流失败", e); } } } /** * 写入响应Json数据 */ public static void sendJsonBy200(HttpServletResponse response, Object resData) { sendJson(response, resData, HttpServletResponse.SC_OK); } /** * 写入响应Json数据 */ public static void sendJsonBy401(HttpServletResponse response, Object resData) { sendJson(response, resData, HttpServletResponse.SC_UNAUTHORIZED); } /** * 写入响应Json数据 */ public static void sendJsonBy403(HttpServletResponse response, Object resData) { sendJson(response, resData, HttpServletResponse.SC_FORBIDDEN); } /** * 重定向页面(客户端跳转) * * @param redirectUrl 跳转地址 */ public static void sendRedirect(HttpServletResponse response, String redirectUrl) throws IOException { if (StringUtils.isNotBlank(redirectUrl)) { response.sendRedirect(redirectUrl); } } } <|start_filename|>clever-security-server/src/main/java/org/clever/security/service/ISecurityContextService.java<|end_filename|> package org.clever.security.service; import org.springframework.security.core.context.SecurityContext; import java.util.List; import java.util.Map; /** * 作者: lzw<br/> * 创建时间:2018-11-22 19:32 <br/> */ public interface ISecurityContextService { /** * 读取用户 SecurityContext * * @param sysName 系统名 * @param userName 用户名 * @return 不存在返回null */ Map<String, SecurityContext> getSecurityContext(String sysName, String userName); /** * 读取用户 SecurityContext * * @param sessionId Session ID */ SecurityContext getSecurityContext(String sessionId); /** * 重新加载所有系统用户权限信息(sessionAttr:SPRING_SECURITY_CONTEXT) * * @param sysName 系统名 * @param userName 用户名 */ List<SecurityContext> reloadSecurityContext(String sysName, String userName); /** * 重新加载所有系统用户权限信息(sessionAttr:SPRING_SECURITY_CONTEXT) * * @param userName 用户名 */ Map<String, List<SecurityContext>> reloadSecurityContext(String userName); /** * 踢出用户(强制下线) * * @param sysName 系统名 * @param userName 用户名 * @return 下线Session数量 */ int forcedOffline(String sysName, String userName); /** * 删除用户Session(所有的系统) * * @param userName 用户信息 */ void delSession(String userName); /** * 删除用户Session * * @param sysName 系统名 * @param userName 用户名 */ void delSession(String sysName, String userName); } <|start_filename|>clever-security-model/src/main/java/org/clever/security/entity/RolePermission.java<|end_filename|> package org.clever.security.entity; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * 角色-权限(RolePermission)实体类 * * @author lizw * @since 2018-09-16 21:24:44 */ @Data public class RolePermission implements Serializable { private static final long serialVersionUID = 148599893038494346L; /** 角色名称 */ private String roleName; /** 资源访问所需要的权限标识字符串 */ private String permissionStr; /** 创建时间 */ private Date createAt; /** 更新时间 */ private Date updateAt; } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/UserAddRes.java<|end_filename|> package org.clever.security.dto.response; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.response.BaseResponse; import java.util.Date; /** * 作者: lzw<br/> * 创建时间:2018-09-17 20:57 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class UserAddRes extends BaseResponse { /** 主键id */ private Long id; /** 登录名 */ private String username; /** 用户类型,0:系统内建,1:外部系统用户 */ private Integer userType; /** 手机号 */ private String telephone; /** 邮箱 */ private String email; /** 帐号过期时间 */ private Date expiredTime; /** 帐号是否锁定,0:未锁定;1:锁定 */ private Integer locked; /** 是否启用,0:禁用;1:启用 */ private Integer enabled; /** 说明 */ private String description; /** 创建时间 */ private Date createAt; /** 更新时间 */ private Date updateAt; } <|start_filename|>clever-security-model/src/main/java/org/clever/security/jackson2/CleverSecurityJackson2Module.java<|end_filename|> package org.clever.security.jackson2; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.module.SimpleModule; import org.clever.security.model.LoginUserDetails; import org.clever.security.model.UserAuthority; import org.clever.security.token.SecurityContextToken; /** * 作者: lzw<br/> * 创建时间:2018-09-22 21:21 <br/> */ public class CleverSecurityJackson2Module extends SimpleModule { public CleverSecurityJackson2Module() { super(CleverSecurityJackson2Module.class.getName(), new Version(1, 0, 0, null, null, null)); } @Override public void setupModule(SetupContext context) { context.setMixInAnnotations(SecurityContextToken.class, SecurityContextTokenMixin.class); context.setMixInAnnotations(LoginUserDetails.class, LoginUserDetailsMixin.class); context.setMixInAnnotations(UserAuthority.class, UserAuthorityMixin.class); } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/UserAddReq.java<|end_filename|> package org.clever.security.dto.request; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.request.BaseRequest; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.Range; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import java.util.Date; import java.util.Set; /** * 作者: lzw<br/> * 创建时间:2018-09-17 20:57 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class UserAddReq extends BaseRequest { @ApiModelProperty("登录名") @NotBlank @Pattern(regexp = "[a-zA-Z0-9_-]{3,16}") private String username; @ApiModelProperty("密码") @NotBlank @Length(min = 6, max = 127) private String password; @ApiModelProperty("用户类型,0:系统内建,1:外部系统用户") @Range(min = 0, max = 1) private Integer userType; @ApiModelProperty("手机号") @Pattern(regexp = "1[0-9]{10}") private String telephone; @ApiModelProperty("邮箱") @Email private String email; @ApiModelProperty("帐号过期时间") private Date expiredTime; @ApiModelProperty("帐号是否锁定,0:未锁定;1:锁定") @Range(min = 0, max = 1) private Integer locked; @ApiModelProperty("是否启用,0:禁用;1:启用") @Range(min = 0, max = 1) private Integer enabled; @ApiModelProperty("说明") @Length(max = 511) private String description; @ApiModelProperty("系统名称列表") @Size(max = 100) private Set<String> sysNameList; } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/repository/JwtRedisSecurityContextRepository.java<|end_filename|> package org.clever.security.repository; import lombok.extern.slf4j.Slf4j; import org.clever.common.exception.BusinessException; import org.clever.security.token.JwtAccessToken; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationTrustResolver; import org.springframework.security.authentication.AuthenticationTrustResolverImpl; import org.springframework.security.authentication.InternalAuthenticationServiceException; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.context.HttpRequestResponseHolder; import org.springframework.security.web.context.SecurityContextRepository; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 作者: lzw<br/> * 创建时间:2018-11-18 17:27 <br/> */ @Component @Slf4j public class JwtRedisSecurityContextRepository implements SecurityContextRepository { private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl(); @Autowired private RedisJwtRepository redisJwtRepository; /** * 从Redis读取Jwt Token */ @Override public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) { HttpServletRequest request = requestResponseHolder.getRequest(); JwtAccessToken jwtAccessToken; try { jwtAccessToken = redisJwtRepository.getJwtToken(request); log.info("### JwtToken 验证成功"); } catch (Throwable e) { if (e instanceof BusinessException) { log.warn("### JwtToken 验证失败: {}", e.getMessage()); } else { log.warn("### JwtToken 验证失败", e); } return SecurityContextHolder.createEmptyContext(); } // 读取 context SecurityContext securityContext; try { securityContext = redisJwtRepository.getSecurityContext(jwtAccessToken); log.info("### 读取SecurityContext成功"); } catch (Throwable e) { throw new InternalAuthenticationServiceException("读取SecurityContext失败", e); } return securityContext; } /** * 保存Jwt Token到Redis */ @Override public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) { final Authentication authentication = context.getAuthentication(); // 认证信息不存在或者是匿名认证不保存 if (authentication == null || trustResolver.isAnonymous(authentication)) { return; } // 验证当前请求 JWT Token if (redisJwtRepository.validationToken(request)) { return; } // 保存 context redisJwtRepository.saveSecurityContext(context); log.info("### 已保存SecurityContext"); } @Override public boolean containsContext(HttpServletRequest request) { // 验证 JWT Token return redisJwtRepository.validationToken(request); } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/RememberMeTokenAddReq.java<|end_filename|> package org.clever.security.dto.request; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.request.BaseRequest; import org.hibernate.validator.constraints.Length; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.util.Date; /** * 作者: lzw<br/> * 创建时间:2018-09-24 16:39 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class RememberMeTokenAddReq extends BaseRequest { @NotBlank @Length(max = 127) @ApiModelProperty("系统(或服务)名称") private String sysName; @NotBlank @Length(max = 63) @ApiModelProperty("token序列号") private String series; @NotBlank @Length(max = 63) @ApiModelProperty("用户登录名") private String username; @NotBlank @Length(max = 63) @ApiModelProperty("token数据") private String token; @NotNull @ApiModelProperty("最后使用时间") private Date lastUsed; } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/LogoutRes.java<|end_filename|> package org.clever.security.dto.response; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.response.BaseResponse; /** * 作者: lzw<br/> * 创建时间:2018-03-21 10:22 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class LogoutRes extends BaseResponse { /** * 是否登出成功 */ private Boolean success; /** * 错误消息 */ private String message; /** * 时间戳 */ private Long timestamp = System.currentTimeMillis(); /** * 当前登出用户信息 */ private UserRes user; public LogoutRes(Boolean success, String message) { this.success = success; this.message = message; } public LogoutRes(Boolean success, String message, UserRes user) { this.success = success; this.message = message; this.user = user; } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/service/GlobalUserDetailsService.java<|end_filename|> package org.clever.security.service; import lombok.extern.slf4j.Slf4j; import org.clever.security.client.UserClient; import org.clever.security.config.SecurityConfig; import org.clever.security.entity.Permission; import org.clever.security.entity.User; import org.clever.security.model.LoginUserDetails; import org.clever.security.model.UserAuthority; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-03-16 10:54 <br/> */ @Component @Slf4j public class GlobalUserDetailsService implements UserDetailsService { @Autowired private SecurityConfig securityConfig; @Autowired private UserClient userClient; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { log.info("### 开始加载用户信息 [usernameOrTelephone={}]", username); // 从本地数据库查询 User user = userClient.getUser(username); if (user == null) { log.info("### 用户不存在 [usernameOrTelephone={}]", username); throw new UsernameNotFoundException("用户不存在,usernameOrTelephone=" + username); } // 获取用户所有权限 List<Permission> permissionList = userClient.findAllPermission(user.getUsername(), securityConfig.getSysName()); // 获取用所有权限 LoginUserDetails userDetails = new LoginUserDetails(user); for (Permission permission : permissionList) { userDetails.getAuthorities().add(new UserAuthority(permission.getPermissionStr(), permission.getTitle())); } // TODO 加载角色信息 // userDetails.getRoles().add() return userDetails; } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/RefreshTokenReq.java<|end_filename|> package org.clever.security.dto.request; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.request.BaseRequest; import javax.validation.constraints.NotBlank; /** * 作者: lzw<br/> * 创建时间:2018-11-19 21:23 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class RefreshTokenReq extends BaseRequest { /** * JWT 刷新 Token 字符串 */ @NotBlank private String refreshToken; } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/authentication/AuthenticationLoginToken.java<|end_filename|> package org.clever.security.authentication; import org.clever.security.service.RequestCryptoService; import org.clever.security.token.login.BaseLoginToken; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; /** * 认证登录用户信息接口 * <p> * 作者: lzw<br/> * 创建时间:2019-04-26 16:45 <br/> */ public interface AuthenticationLoginToken { /** * 是否支持验证此身份类型(BaseLoginToken.class.isAssignableFrom(loginToken)) * * @param loginToken Token类型 * @return 返回true表示支持认证 */ boolean supports(Class<?> loginToken); /** * loginToken 数据完整性校验(登录认证之前的校验 BadCredentialsException) */ void preAuthenticationCheck(BaseLoginToken loginToken) throws AuthenticationException; /** * Token验证(密码验证等) * * @param loginToken 登录Token * @param loadedUser 数据库中的数据 * @param requestCryptoService 请求参数加密/解密 * @param bCryptPasswordEncoder 密码匹配 * @throws AuthenticationException (BadCredentialsException) */ void mainAuthenticationChecks( BaseLoginToken loginToken, UserDetails loadedUser, RequestCryptoService requestCryptoService, BCryptPasswordEncoder bCryptPasswordEncoder) throws AuthenticationException; } <|start_filename|>clever-security-server/src/main/java/org/clever/security/service/local/WebPermissionServiceProxy.java<|end_filename|> package org.clever.security.service.local; import lombok.extern.slf4j.Slf4j; import org.clever.security.client.WebPermissionClient; import org.clever.security.dto.request.WebPermissionInitReq; import org.clever.security.dto.request.WebPermissionModelGetReq; import org.clever.security.dto.response.WebPermissionInitRes; import org.clever.security.entity.model.WebPermissionModel; import org.clever.security.service.WebPermissionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-11-11 19:30 <br/> */ @Component @Slf4j public class WebPermissionServiceProxy implements WebPermissionClient { @Autowired private WebPermissionService webPermissionService; @Override public WebPermissionModel getWebPermissionModel(WebPermissionModelGetReq req) { return webPermissionService.getWebPermissionModel(req); } @Override public List<WebPermissionModel> findAllWebPermissionModel(String sysName) { return webPermissionService.findAllWebPermissionModel(sysName); } @Override public WebPermissionInitRes initWebPermission(String sysName, WebPermissionInitReq req) { return webPermissionService.initWebPermission(sysName, req); } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/utils/AuthenticationUtils.java<|end_filename|> package org.clever.security.utils; import org.clever.security.dto.response.UserRes; import org.clever.security.model.LoginUserDetails; import org.clever.security.token.SecurityContextToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; /** * 作者: lzw<br/> * 创建时间:2018-09-17 15:26 <br/> */ public class AuthenticationUtils { public static SecurityContextToken getSecurityContextToken() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); return getSecurityContextToken(authentication); } public static SecurityContextToken getSecurityContextToken(Authentication authentication) { if (authentication == null) { return null; } if (!(authentication instanceof SecurityContextToken)) { throw new ClassCastException(String.format("Authentication类型错误,%s | %s", authentication.getClass(), authentication)); } return (SecurityContextToken) authentication; } public static UserRes getUserRes() { SecurityContextToken securityContextToken = getSecurityContextToken(); return getUserRes(securityContextToken); } public static UserRes getUserRes(Authentication authentication) { SecurityContextToken securityContextToken = getSecurityContextToken(authentication); return getUserRes(securityContextToken); } public static UserRes getUserRes(SecurityContextToken securityContextToken) { if (securityContextToken == null) { return null; } LoginUserDetails loginUserDetails = securityContextToken.getUserDetails(); if (loginUserDetails == null) { return null; } UserRes userRes = new UserRes(); userRes.setUsername(loginUserDetails.getUsername()); userRes.setTelephone(loginUserDetails.getTelephone()); userRes.setEmail(loginUserDetails.getEmail()); userRes.setUserType(loginUserDetails.getUserType()); // 读取角色信息 userRes.getRoleNames().addAll(loginUserDetails.getRoles()); // 读取权限信息 if (loginUserDetails.getAuthorities() != null) { for (GrantedAuthority grantedAuthority : loginUserDetails.getAuthorities()) { userRes.getAuthorities().add(grantedAuthority.getAuthority()); } } return userRes; } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/repository/CaptchaInfoRepository.java<|end_filename|> package org.clever.security.repository; import lombok.extern.slf4j.Slf4j; import org.clever.security.model.CaptchaInfo; import org.clever.security.service.GenerateKeyService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import java.util.concurrent.TimeUnit; /** * 作者: lzw<br/> * 创建时间:2018-11-20 19:57 <br/> */ @Component @Slf4j public class CaptchaInfoRepository { @Autowired private RedisTemplate<String, Object> redisTemplate; @Autowired private GenerateKeyService generateKeyService; public void saveCaptchaInfo(CaptchaInfo captchaInfo) { String captchaInfoKey = generateKeyService.getCaptchaInfoKey(captchaInfo.getCode().toUpperCase(), captchaInfo.getImageDigest()); redisTemplate.opsForValue().set(captchaInfoKey, captchaInfo, captchaInfo.getEffectiveTime(), TimeUnit.MILLISECONDS); } /** * 读取验证码,不存在返回null */ public CaptchaInfo getCaptchaInfo(String code, String imageDigest) { String captchaInfoKey = generateKeyService.getCaptchaInfoKey(code.toUpperCase(), imageDigest); Object object = redisTemplate.opsForValue().get(captchaInfoKey); if (object instanceof CaptchaInfo) { return (CaptchaInfo) object; } return null; } public void deleteCaptchaInfo(String code, String imageDigest) { String captchaInfoKey = generateKeyService.getCaptchaInfoKey(code.toUpperCase(), imageDigest); redisTemplate.delete(captchaInfoKey); } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/utils/HttpRequestUtils.java<|end_filename|> package org.clever.security.utils; import org.apache.commons.lang3.StringUtils; import javax.servlet.http.HttpServletRequest; import java.util.Objects; /** * 作者: lzw<br/> * 创建时间:2018-03-17 21:38 <br/> */ public class HttpRequestUtils { /** * 判断是否要返回Json */ public static boolean isJsonResponse(HttpServletRequest request) { String getFlag = request.getMethod(); String jsonFlag = StringUtils.trimToEmpty(request.getHeader("Accept")); String ajaxFlag = request.getHeader("X-Requested-With"); return !getFlag.equalsIgnoreCase("GET") || jsonFlag.contains("application/json") || Objects.equals("XMLHttpRequest", ajaxFlag); } /** * 判断是否要返回Json (只用用于判断登录请求) */ public static boolean isJsonResponseByLogin(HttpServletRequest request) { String jsonFlag = StringUtils.trimToEmpty(request.getHeader("Accept")); String ajaxFlag = request.getHeader("X-Requested-With"); return jsonFlag.contains("application/json") || Objects.equals("XMLHttpRequest", ajaxFlag); } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/JwtLoginRes.java<|end_filename|> package org.clever.security.dto.response; import lombok.Data; import lombok.EqualsAndHashCode; /** * 作者: lzw<br/> * 创建时间:2018-11-19 11:56 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class JwtLoginRes extends LoginRes { /** * JWT Token 字符串 */ private String token; /** * JWT 刷新 Token 字符串 */ private String refreshToken; public JwtLoginRes(Boolean success, String message, String token, String refreshToken) { super(success, message); this.token = token; this.refreshToken = refreshToken; } public JwtLoginRes(Boolean success, String message, UserRes user, String token, String refreshToken) { super(success, message, user); this.token = token; this.refreshToken = refreshToken; } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/authentication/collect/CollectUsernamePasswordToken.java<|end_filename|> package org.clever.security.authentication.collect; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.clever.security.Constant; import org.clever.security.LoginTypeConstant; import org.clever.security.authentication.CollectLoginToken; import org.clever.security.token.login.BaseLoginToken; import org.clever.security.token.login.UsernamePasswordToken; import org.json.JSONObject; import org.springframework.security.core.AuthenticationException; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import java.io.IOException; /** * 收集用户信息 UsernamePasswordToken * <p> * 作者: lzw<br/> * 创建时间:2019-04-28 15:59 <br/> */ @Component @Slf4j public class CollectUsernamePasswordToken implements CollectLoginToken { private static final String USERNAME_PARAM = "username"; private static final String PASSWORD_PARAM = "password"; private UsernamePasswordToken readUsernamePasswordToken(HttpServletRequest request, boolean isSubmitBody) throws IOException { String loginType; String username; String password; String captcha; String captchaDigest; boolean rememberMe; if (isSubmitBody) { // 使用Json方式提交数据 Object json = request.getAttribute(Constant.Login_Data_Body_Request_Key); if (json == null) { json = IOUtils.toString(request.getReader()); request.setAttribute(Constant.Login_Data_Body_Request_Key, json); } JSONObject object = new JSONObject(json.toString()); loginType = StringUtils.trimToEmpty(object.optString(LOGIN_TYPE_PARAM)); username = StringUtils.trimToEmpty(object.optString(USERNAME_PARAM)); password = StringUtils.trimToEmpty(object.optString(PASSWORD_PARAM)); captcha = StringUtils.trimToEmpty(object.optString(CAPTCHA_PARAM)); captchaDigest = StringUtils.trimToEmpty(object.optString(CAPTCHA_DIGEST_PARAM)); rememberMe = Boolean.parseBoolean(StringUtils.trimToEmpty(object.optString(REMEMBER_ME_PARAM))); } else { // 使用Parameter提交数据 loginType = StringUtils.trimToEmpty(request.getParameter(LOGIN_TYPE_PARAM)); username = StringUtils.trimToEmpty(request.getParameter(USERNAME_PARAM)); password = StringUtils.trimToEmpty(request.getParameter(PASSWORD_PARAM)); captcha = StringUtils.trimToEmpty(request.getParameter(CAPTCHA_PARAM)); captchaDigest = StringUtils.trimToEmpty(request.getParameter(CAPTCHA_DIGEST_PARAM)); rememberMe = Boolean.parseBoolean(StringUtils.trimToEmpty(request.getParameter(REMEMBER_ME_PARAM))); } // 创建Token UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password); usernamePasswordToken.setLoginType(loginType); usernamePasswordToken.setCaptcha(captcha); usernamePasswordToken.setCaptchaDigest(captchaDigest); usernamePasswordToken.setRememberMe(rememberMe); return usernamePasswordToken; } @Override public boolean supports(HttpServletRequest request, boolean isSubmitBody) throws IOException { UsernamePasswordToken usernamePasswordToken = readUsernamePasswordToken(request, isSubmitBody); if (StringUtils.isNotBlank(usernamePasswordToken.getLoginType())) { return LoginTypeConstant.UsernamePassword.equalsIgnoreCase(usernamePasswordToken.getLoginType()); } return StringUtils.isNotBlank(usernamePasswordToken.getUsername()) && StringUtils.isNotBlank(usernamePasswordToken.getPassword()); } @Override public BaseLoginToken attemptAuthentication(HttpServletRequest request, boolean isSubmitBody) throws AuthenticationException, IOException { return readUsernamePasswordToken(request, isSubmitBody); } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/UserLoginLogAddReq.java<|end_filename|> package org.clever.security.dto.request; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.request.BaseRequest; import org.clever.common.validation.ValidIntegerStatus; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.Range; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.util.Date; /** * 作者: lzw<br/> * 创建时间:2018-09-24 19:57 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class UserLoginLogAddReq extends BaseRequest { @NotBlank @Length(max = 127) @ApiModelProperty("系统(或服务)名称") private String sysName; @NotBlank @Length(max = 63) @ApiModelProperty("用户登录名") private String username; @NotNull @ApiModelProperty("登录时间") private Date loginTime; @NotBlank @Length(max = 63) @ApiModelProperty("登录IP") private String loginIp; @NotBlank @ApiModelProperty("登录的用户信息") private String authenticationInfo; @ApiModelProperty("登录类型,0:sesion-cookie,1:jwt-token") @NotNull @ValidIntegerStatus({0, 1}) private Integer loginModel; @NotBlank @Length(max = 63) @ApiModelProperty("登录SessionID") private String sessionId; @NotNull @Range(min = 0, max = 2) @ApiModelProperty("登录状态,0:未知;1:已登录;2:登录已过期") private Integer loginState; } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/UserRes.java<|end_filename|> package org.clever.security.dto.response; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.response.BaseResponse; import java.util.ArrayList; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-03-20 16:13 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class UserRes extends BaseResponse { /** * 登录名 */ private String username; /** * 手机号 */ private String telephone; /** * 邮箱 */ private String email; /** * 用户类型,0:系统内建,1:外部系统用户 */ private Integer userType; /** * 用户有角色名 */ private List<String> roleNames = new ArrayList<>(); /** * 拥有的权限字符串 */ private List<String> authorities = new ArrayList<>(); } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/event/HttpSessionDestroyedListener.java<|end_filename|> package org.clever.security.event; import lombok.extern.slf4j.Slf4j; import org.clever.security.LoginModel; import org.clever.security.client.UserLoginLogClient; import org.clever.security.config.SecurityConfig; import org.clever.security.dto.request.UserLoginLogUpdateReq; import org.clever.security.entity.EnumConstant; import org.clever.security.entity.UserLoginLog; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.security.core.session.SessionDestroyedEvent; import org.springframework.stereotype.Component; /** * 作者: lzw<br/> * 创建时间:2018-09-23 19:33 <br/> */ @Component @Slf4j public class HttpSessionDestroyedListener implements ApplicationListener<SessionDestroyedEvent> { @Autowired private SecurityConfig securityConfig; @Autowired private UserLoginLogClient userLoginLogClient; @SuppressWarnings("NullableProblems") @Override public void onApplicationEvent(SessionDestroyedEvent event) { // org.springframework.session.events.SessionDestroyedEvent; if (LoginModel.jwt.equals(securityConfig.getLoginModel())) { log.error("### 注销Session [{}] -> 不应该创建HttpSession", event.getId()); } else { try { log.info("### 注销Session [{}]", event.getId()); UserLoginLog userLoginLog = userLoginLogClient.getUserLoginLog(event.getId()); if (userLoginLog == null) { log.warn("### 注销Session未能找到对应的登录日志 [{}]", event.getId()); return; } // 设置登录过期 UserLoginLogUpdateReq req = new UserLoginLogUpdateReq(); req.setLoginState(EnumConstant.UserLoginLog_LoginState_2); userLoginLogClient.updateUserLoginLog(event.getId(), req); } catch (Exception e) { log.error("更新Session注销信息失败", e); } } } } <|start_filename|>clever-security-server/src/main/java/org/clever/security/mapper/PermissionMapper.java<|end_filename|> package org.clever.security.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.metadata.IPage; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.clever.security.dto.request.PermissionQueryReq; import org.clever.security.entity.Permission; import org.clever.security.entity.model.WebPermissionModel; import org.springframework.stereotype.Repository; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-09-17 9:13 <br/> */ @Repository @Mapper public interface PermissionMapper extends BaseMapper<Permission> { List<Permission> findByUsername(@Param("username") String username); List<Permission> findByRoleName(@Param("roleName") String roleName); List<WebPermissionModel> findByPage(@Param("query") PermissionQueryReq query, IPage page); int existsPermission(@Param("permissionStr") String permissionStr); WebPermissionModel getByPermissionStr(@Param("permissionStr") String permissionStr); int delRolePermission(@Param("permissionStr") String permissionStr); } <|start_filename|>clever-security-server/src/main/java/org/clever/security/service/internal/UserBindRoleService.java<|end_filename|> package org.clever.security.service.internal; import lombok.extern.slf4j.Slf4j; import org.clever.security.mapper.QueryMapper; import org.clever.security.mapper.UserMapper; import org.clever.security.service.ISecurityContextService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.*; /** * 作者: lzw<br/> * 创建时间:2018-10-11 20:39 <br/> */ @Transactional(readOnly = true) @Service @Slf4j public class UserBindRoleService { @Autowired private UserMapper userMapper; @Autowired private QueryMapper queryMapper; @Autowired private ISecurityContextService sessionService; /** * 重新为用户分配角色 * * @param userName 用户登录名 * @param roleNameList 角色名称集合 */ @Transactional public void resetUserBindRole(String userName, Collection<String> roleNameList) { if (roleNameList == null) { roleNameList = new ArrayList<>(); } // 获取关联角色列表 List<String> oldRoleNameList = queryMapper.findRoleNameByUser(userName); Set<String> addRoleName = new HashSet<>(roleNameList); addRoleName.removeAll(oldRoleNameList); Set<String> delRoleName = new HashSet<>(oldRoleNameList); delRoleName.removeAll(roleNameList); // 新增 for (String roleName : addRoleName) { userMapper.addRole(userName, roleName); } // 删除 for (String roleName : delRoleName) { userMapper.delRole(userName, roleName); } // 更新Session sessionService.reloadSecurityContext(userName); } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/config/JwtWebSecurityConfig.java<|end_filename|> package org.clever.security.config; import lombok.extern.slf4j.Slf4j; import org.clever.security.Constant; import org.clever.security.authentication.UserLoginEntryPoint; import org.clever.security.authentication.filter.UserLoginFilter; import org.clever.security.handler.UserAccessDeniedHandler; import org.clever.security.handler.UserLogoutHandler; import org.clever.security.handler.UserLogoutSuccessHandler; import org.clever.security.repository.SecurityContextRepositoryProxy; import org.clever.security.service.GlobalUserDetailsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.access.AccessDecisionManager; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.config.BeanIds; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.context.SecurityContextRepository; import org.springframework.security.web.savedrequest.NullRequestCache; import org.springframework.security.web.savedrequest.RequestCache; import java.util.List; /** * Jwt Token 登录配置 * 作者: lzw<br/> * 创建时间:2018-03-14 14:45 <br/> */ @Configuration @ConditionalOnProperty(prefix = Constant.ConfigPrefix, name = "login-model", havingValue = "jwt") @Slf4j public class JwtWebSecurityConfig extends BaseWebSecurityConfig { @Autowired private SecurityConfig securityConfig; @Autowired private UserLoginFilter userLoginFilter; @Autowired private GlobalUserDetailsService globalUserDetailsService; @Autowired private List<AuthenticationProvider> authenticationProviderList; @Autowired private UserLoginEntryPoint userLoginEntryPoint; @Autowired private UserLogoutHandler userLogoutHandler; @Autowired private UserLogoutSuccessHandler userLogoutSuccessHandler; @Autowired private UserAccessDeniedHandler userAccessDeniedHandler; @Autowired private AccessDecisionManager accessDecisionManager; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; @Autowired private SecurityContextRepositoryProxy securityContextRepositoryProxy; @Override PasswordEncoder getPasswordEncoder() { return bCryptPasswordEncoder; } @Override UserDetailsService getUserDetailsService() { return globalUserDetailsService; } @Override List<AuthenticationProvider> getAuthenticationProviderList() { return authenticationProviderList; } @Override SecurityConfig getSecurityConfig() { return securityConfig; } /** * 在Spring容器中注册 AuthenticationManager */ @Bean(name = BeanIds.AUTHENTICATION_MANAGER) @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } /** * 具体的权限控制规则配置 */ @Override protected void configure(HttpSecurity http) throws Exception { // Jwt Token不需要使用HttpSession http.setSharedObject(SecurityContextRepository.class, securityContextRepositoryProxy); http.setSharedObject(RequestCache.class, new NullRequestCache()); // 自定义登录 Filter --> UserLoginFilter http.addFilterAt(userLoginFilter, UsernamePasswordAuthenticationFilter.class); // http // .csrf().and() // .addFilter(new WebAsyncManagerIntegrationFilter()) // .exceptionHandling().and() // .headers().and() // .sessionManagement().and() // .securityContext().and() // .requestCache().and() // .anonymous().and() // .servletApi().and() // .apply(new DefaultLoginPageConfigurer<>()).and() // .logout(); // ClassLoader classLoader = this.getApplicationContext().getClassLoader(); // List<AbstractHttpConfigurer> defaultHttpConfigurers = SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, classLoader); // for(AbstractHttpConfigurer configurer : defaultHttpConfigurers) { // http.apply(configurer); // } // 过滤器配置 http .csrf().disable() .sessionManagement().disable() .exceptionHandling().authenticationEntryPoint(userLoginEntryPoint).accessDeniedHandler(userAccessDeniedHandler) .and() .authorizeRequests().anyRequest().authenticated().accessDecisionManager(accessDecisionManager) .and() .formLogin().disable() .logout().logoutUrl(securityConfig.getLogout().getLogoutUrl()).addLogoutHandler(userLogoutHandler).logoutSuccessHandler(userLogoutSuccessHandler).permitAll() ; // 禁用"记住我功能配置"(Token的记住我功能仅仅只是Token过期时间加长) http.rememberMe().disable(); log.info("### HttpSecurity 配置完成!"); } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/config/model/RememberMeConfig.java<|end_filename|> package org.clever.security.config.model; import lombok.Data; import java.time.Duration; /** * 记住我功能配置 * 作者: lzw<br/> * 创建时间:2019-04-25 19:26 <br/> */ @Data public class RememberMeConfig { /** * 启用"记住我"功能 */ private Boolean enable = true; /** * 总是"记住我" */ private Boolean alwaysRemember = false; /** * "记住我"有效时间(单位秒,默认一个月) */ private Duration validity = Duration.ofDays(30); } <|start_filename|>clever-security-server/src/main/java/org/clever/security/service/local/UserLoginLogServiceProxy.java<|end_filename|> package org.clever.security.service.local; import lombok.extern.slf4j.Slf4j; import org.clever.common.utils.mapper.BeanMapper; import org.clever.security.client.UserLoginLogClient; import org.clever.security.dto.request.UserLoginLogAddReq; import org.clever.security.dto.request.UserLoginLogUpdateReq; import org.clever.security.entity.UserLoginLog; import org.clever.security.service.UserLoginLogService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * 参考 UserLoginLogController * <p> * 作者: lzw<br/> * 创建时间:2018-11-11 19:30 <br/> */ @Component @Slf4j public class UserLoginLogServiceProxy implements UserLoginLogClient { @Autowired private UserLoginLogService userLoginLogService; @Override public UserLoginLog addUserLoginLog(UserLoginLogAddReq req) { UserLoginLog userLoginLog = BeanMapper.mapper(req, UserLoginLog.class); return userLoginLogService.addUserLoginLog(userLoginLog); } @Override public UserLoginLog getUserLoginLog(String sessionId) { return userLoginLogService.getUserLoginLog(sessionId); } @Override public UserLoginLog updateUserLoginLog(String sessionId, UserLoginLogUpdateReq req) { UserLoginLog update = BeanMapper.mapper(req, UserLoginLog.class); return userLoginLogService.updateUserLoginLog(sessionId, update); } } <|start_filename|>clever-security-server/src/main/java/org/clever/security/service/internal/ReLoadSessionService.java<|end_filename|> package org.clever.security.service.internal; import lombok.extern.slf4j.Slf4j; import org.clever.security.mapper.RoleMapper; import org.clever.security.service.ISecurityContextService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; /** * 重新加载Session * 作者: lzw<br/> * 创建时间:2018-11-16 11:54 <br/> */ @Transactional(readOnly = true) @Service @Slf4j public class ReLoadSessionService { // @Autowired // private UserMapper userMapper; // @Autowired // private RedisOperationsSessionRepository sessionRepository; @Autowired private RoleMapper roleMapper; @Autowired private ISecurityContextService sessionService; /** * 角色所拥有的权限发生变化 - 重新加载Session */ public void onChangeRole(String roleName) { List<String> usernameList = roleMapper.findUsernameByRoleName(roleName); for (String username : usernameList) { sessionService.reloadSecurityContext(username); } } /** * 角色所拥有的权限发生变化 - 重新加载Session */ public void onChangeRole(Collection<String> roleNameList) { Set<String> usernameList = new HashSet<>(); for (String roleName : roleNameList) { usernameList.addAll(roleMapper.findUsernameByRoleName(roleName)); } for (String username : usernameList) { sessionService.reloadSecurityContext(username); } } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/event/LoginSuccessListener.java<|end_filename|> package org.clever.security.event; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.clever.common.utils.mapper.JacksonMapper; import org.clever.security.Constant; import org.clever.security.LoginModel; import org.clever.security.client.UserLoginLogClient; import org.clever.security.config.SecurityConfig; import org.clever.security.dto.request.UserLoginLogAddReq; import org.clever.security.entity.EnumConstant; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.ApplicationListener; import org.springframework.security.authentication.event.AuthenticationSuccessEvent; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.stereotype.Component; import java.util.Date; /** * 登录事件监听(写入登录成功的SessionID日志) * 作者: lzw<br/> * 创建时间:2018-09-18 13:55 <br/> */ @ConditionalOnProperty(prefix = Constant.ConfigPrefix, name = "login-model", havingValue = "session") @Component @Slf4j public class LoginSuccessListener implements ApplicationListener<AuthenticationSuccessEvent> { @Autowired private SecurityConfig securityConfig; @Autowired private UserLoginLogClient userLoginLogClient; @SuppressWarnings("Duplicates") @Override public void onApplicationEvent(AuthenticationSuccessEvent event) { Authentication authentication = event.getAuthentication(); if (LoginModel.jwt.equals(securityConfig.getLoginModel())) { log.info("### 登录成功 -> {}", authentication); } else { String loginIp = null; String sessionId = null; if (authentication.getDetails() != null && authentication.getDetails() instanceof WebAuthenticationDetails) { WebAuthenticationDetails webAuthenticationDetails = (WebAuthenticationDetails) authentication.getDetails(); loginIp = webAuthenticationDetails.getRemoteAddress(); sessionId = webAuthenticationDetails.getSessionId(); } else { log.warn("### 登录成功未能得到SessionID [{}]", authentication.getName()); } UserLoginLogAddReq userLoginLog = new UserLoginLogAddReq(); userLoginLog.setSysName(securityConfig.getSysName()); userLoginLog.setUsername(authentication.getName()); userLoginLog.setLoginTime(new Date()); userLoginLog.setLoginIp(StringUtils.trimToEmpty(loginIp)); userLoginLog.setAuthenticationInfo(JacksonMapper.nonEmptyMapper().toJson(authentication)); userLoginLog.setLoginModel(EnumConstant.ServiceSys_LoginModel_0); userLoginLog.setSessionId(StringUtils.trimToEmpty(sessionId)); userLoginLog.setLoginState(EnumConstant.UserLoginLog_LoginState_1); try { userLoginLogClient.addUserLoginLog(userLoginLog); log.info("### 写入登录成功日志 [{}]", authentication.getName()); } catch (Exception e) { log.error("写入登录成功日志失败 [{}]", authentication.getName(), e); } } } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/model/LoginUserDetails.java<|end_filename|> package org.clever.security.model; import lombok.Getter; import lombok.ToString; import org.clever.security.entity.EnumConstant; import org.clever.security.entity.User; import org.springframework.security.core.CredentialsContainer; import org.springframework.security.core.userdetails.UserDetails; import java.util.*; /** * 登录的用户信息 * <p> * 作者: lzw<br/> * 创建时间:2018-03-16 17:41 <br/> */ @ToString(includeFieldNames = false, of = {"username"}) public class LoginUserDetails implements UserDetails, CredentialsContainer { /** * 主键id */ @Getter private final Long id; /** * 登录名(一条记录的手机号不能当另一条记录的用户名用) */ private final String username; /** * 密码 */ private String password; /** * 用户类型,0:系统内建,1:外部系统用户 */ @Getter private final Integer userType; /** * 手机号 */ @Getter private final String telephone; /** * 邮箱 */ @Getter private final String email; /** * 帐号过期时间 */ @Getter private final Date expiredTime; /** * 帐号锁定标识 */ private final boolean locked; /** * 是否启用 */ private final boolean enabled; /** * 说明 */ @Getter private String description; /** * 创建时间 */ @Getter private Date createAt; /** * 更新时间 */ @Getter private Date updateAt; /** * 凭证过期标识 */ private final boolean credentialsNonExpired; /** * 帐号过期标识 */ private final boolean accountNonExpired; /** * 用户权限信息 */ private final Set<UserAuthority> authorities = new HashSet<>(); /** * 角色信息 */ @Getter private final Set<String> roles = new HashSet<>(); public LoginUserDetails(User user) { this.id = user.getId(); this.username = user.getUsername(); this.password = <PASSWORD>(); this.userType = user.getUserType(); this.telephone = user.getTelephone(); this.email = user.getEmail(); this.expiredTime = user.getExpiredTime(); this.locked = Objects.equals(user.getLocked(), EnumConstant.User_Locked_0); this.enabled = Objects.equals(user.getEnabled(), EnumConstant.User_Enabled_1); this.description = user.getDescription(); this.createAt = user.getCreateAt(); this.updateAt = user.getUpdateAt(); this.credentialsNonExpired = true; this.accountNonExpired = user.getExpiredTime() == null || user.getExpiredTime().compareTo(new Date()) > 0; } /** * 用于反序列化构造 */ public LoginUserDetails( Long id, String username, String password, Integer userType, String telephone, String email, Date expiredTime, boolean locked, boolean enabled, String description, Date createAt, Date updateAt) { this.id = id; this.username = username; this.password = password; this.userType = userType; this.telephone = telephone; this.email = email; this.expiredTime = expiredTime; this.locked = locked; this.enabled = enabled; this.description = description; this.createAt = createAt; this.updateAt = updateAt; this.credentialsNonExpired = true; this.accountNonExpired = expiredTime == null || expiredTime.compareTo(new Date()) > 0; } @Override public void eraseCredentials() { this.password = ""; } @Override public Collection<UserAuthority> getAuthorities() { return authorities; } @Override public String getPassword() { return password; } @Override public String getUsername() { return username; } @Override public boolean isAccountNonExpired() { return accountNonExpired; } @Override public boolean isAccountNonLocked() { return locked; } @Override public boolean isCredentialsNonExpired() { return credentialsNonExpired; } @Override public boolean isEnabled() { return enabled; } @Override public int hashCode() { if (username == null) { return super.hashCode(); } return username.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof LoginUserDetails)) { return false; } LoginUserDetails objTmp = (LoginUserDetails) obj; if (this.username == null) { return objTmp.username == null; } return this.username.equals(objTmp.username); } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/jackson2/LoginUserDetailsMixin.java<|end_filename|> package org.clever.security.jackson2; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Date; /** * 作者: lzw<br/> * 创建时间:2018-09-22 21:28 <br/> */ //@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_ARRAY) @JsonAutoDetect @JsonIgnoreProperties(ignoreUnknown = true) class LoginUserDetailsMixin { @JsonCreator public LoginUserDetailsMixin( @JsonProperty("id") Long id, @JsonProperty("username") String username, @JsonProperty("password") String password, @JsonProperty("userType") Integer userType, @JsonProperty("telephone") String telephone, @JsonProperty("email") String email, @JsonProperty("expiredTime") Date expiredTime, @JsonProperty("accountNonLocked") boolean locked, @JsonProperty("enabled") boolean enabled, @JsonProperty("description") String description, @JsonProperty("createAt") Date createAt, @JsonProperty("updateAt") Date updateAt) { } } <|start_filename|>clever-security-server/src/main/java/org/clever/security/service/UserService.java<|end_filename|> package org.clever.security.service; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.clever.common.exception.BusinessException; import org.clever.common.server.service.BaseService; import org.clever.security.dto.request.UserAuthenticationReq; import org.clever.security.dto.response.UserAuthenticationRes; import org.clever.security.entity.EnumConstant; import org.clever.security.entity.Permission; import org.clever.security.entity.User; import org.clever.security.mapper.UserMapper; import org.clever.security.service.internal.ManageCryptoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Date; import java.util.List; import java.util.Objects; /** * 作者: lzw<br/> * 创建时间:2018-09-17 9:20 <br/> */ @Transactional(readOnly = true) @Service @Slf4j public class UserService extends BaseService { @Autowired private UserMapper userMapper; @Autowired private ManageCryptoService manageCryptoService; public User getUser(String unique) { return userMapper.getByUnique(unique); } public List<Permission> findAllPermission(String username, String sysName) { return userMapper.findByUsername(username, sysName); } public Boolean canLogin(String username, String sysName) { return userMapper.existsUserBySysName(username, sysName) >= 1; } // TODO 认证 public Boolean authentication(UserAuthenticationReq req) { User user = userMapper.getByUnique(req.getLoginName()); if (user == null) { throw new BusinessException("用户不存在"); } // if (!user.isCredentialsNonExpired()) { // log.info("帐号密码已过期 [username={}]", user.getUsername()); // throw new CredentialsExpiredException("帐号密码已过期"); // } if (!Objects.equals(user.getLocked(), EnumConstant.User_Locked_0)) { log.info("帐号已锁定 [username={}]", user.getUsername()); throw new BusinessException("帐号已锁定"); } if (!Objects.equals(user.getEnabled(), EnumConstant.User_Enabled_1)) { log.info("帐号已禁用 [username={}]", user.getUsername()); throw new BusinessException("帐号已禁用"); } if (!(user.getExpiredTime() == null || user.getExpiredTime().compareTo(new Date()) > 0)) { log.info("帐号已过期 [username={}]", user.getUsername()); throw new BusinessException("帐号已过期"); } // 校验用户是否有权登录当前系统 if (StringUtils.isNotBlank(req.getSysName())) { if (!canLogin(user.getUsername(), req.getSysName())) { throw new BusinessException("您无权登录当前系统,请联系管理员授权"); } } // 校验密码 if (UserAuthenticationReq.LoginType_Username.equals(req.getLoginType())) { // 密码先解密再加密 req.setPassword(manageCryptoService.reqAesDecrypt(req.getPassword())); req.setPassword(manageCryptoService.dbEncode(req.getPassword())); // 用户名、密码校验 if (!req.getLoginName().equals(user.getUsername()) || !manageCryptoService.dbMatches(req.getPassword(), user.getPassword())) { log.info("### 用户名密码验证失败 [{}]", req.toString()); throw new BusinessException("用户名密码验证失败"); } log.info("### 用户名密码验证成功 [{}]", req.toString()); } else if (UserAuthenticationReq.LoginType_Telephone.equals(req.getLoginType())) { // TODO 手机号验证码登录 throw new BusinessException("暂不支持手机号验证码登录"); } else { throw new BusinessException("不支持的登录类型"); } return true; } public UserAuthenticationRes authenticationAndRes(UserAuthenticationReq req) { UserAuthenticationRes userAuthenticationRes = new UserAuthenticationRes(); if (StringUtils.isBlank(req.getLoginType())) { req.setLoginType("username"); } try { userAuthenticationRes.setSuccess(authentication(req)); } catch (Exception e) { userAuthenticationRes.setSuccess(false); userAuthenticationRes.setFailMessage(e.getMessage()); } return userAuthenticationRes; } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/token/JwtRefreshToken.java<|end_filename|> package org.clever.security.token; import lombok.Data; import java.io.Serializable; /** * 作者: lzw<br/> * 创建时间:2018-11-20 9:11 <br/> */ @Data public class JwtRefreshToken implements Serializable { /** * 用户名 */ private String username; /** * Token ID */ private String tokenId; public JwtRefreshToken() { } public JwtRefreshToken(String username, String tokenId) { this.username = username; this.tokenId = tokenId; } } <|start_filename|>clever-security-server/src/main/java/org/clever/security/service/ManageByUserService.java<|end_filename|> package org.clever.security.service; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.clever.common.exception.BusinessException; import org.clever.common.utils.mapper.BeanMapper; import org.clever.security.dto.request.UserAddReq; import org.clever.security.dto.request.UserQueryPageReq; import org.clever.security.dto.request.UserUpdateReq; import org.clever.security.dto.response.UserInfoRes; import org.clever.security.entity.EnumConstant; import org.clever.security.entity.User; import org.clever.security.mapper.PermissionMapper; import org.clever.security.mapper.RememberMeTokenMapper; import org.clever.security.mapper.RoleMapper; import org.clever.security.mapper.UserMapper; import org.clever.security.service.internal.ManageCryptoService; import org.clever.security.service.internal.UserBindSysNameService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Date; import java.util.HashSet; import java.util.Objects; /** * 作者: lzw<br/> * 创建时间:2018-10-02 20:53 <br/> */ @Transactional(readOnly = true) @Service @Slf4j public class ManageByUserService { @Autowired private ManageCryptoService manageCryptoService; @Autowired private UserMapper userMapper; @Autowired private RoleMapper roleMapper; @Autowired private PermissionMapper permissionMapper; @Autowired private RememberMeTokenMapper rememberMeTokenMapper; @Autowired private UserBindSysNameService userBindSysNameService; @Autowired private ISecurityContextService sessionService; public IPage<User> findByPage(UserQueryPageReq userQueryPageReq) { Page<User> page = new Page<>(userQueryPageReq.getPageNo(), userQueryPageReq.getPageSize()); page.setRecords(userMapper.findByPage(userQueryPageReq, page)); return page; } public UserInfoRes getUserInfo(String username) { User user = userMapper.getByUsername(username); if (user == null) { return null; } UserInfoRes userInfoRes = BeanMapper.mapper(user, UserInfoRes.class); userInfoRes.setRoleList(roleMapper.findByUsername(user.getUsername())); userInfoRes.setPermissionList(permissionMapper.findByUsername(user.getUsername())); userInfoRes.setSysNameList(userMapper.findSysNameByUsername(user.getUsername())); return userInfoRes; } @Transactional public User addUser(UserAddReq userAddReq) { User user = BeanMapper.mapper(userAddReq, User.class); final Date now = new Date(); if (user.getExpiredTime() != null && now.compareTo(user.getExpiredTime()) >= 0) { throw new BusinessException("设置过期时间小于当前时间"); } if (userMapper.existsByUserName(user.getUsername()) > 0) { throw new BusinessException("用户名已经存在"); } if (StringUtils.isNotBlank(user.getTelephone()) && userMapper.existsByTelephone(user.getTelephone()) > 0) { throw new BusinessException("手机号已经被绑定"); } if (StringUtils.isNotBlank(user.getEmail()) && userMapper.existsByEmail(user.getEmail()) > 0) { throw new BusinessException("邮箱已经被绑定"); } // 登录名(一条记录的手机号不能当另一条记录的用户名用) if (StringUtils.isNotBlank(user.getTelephone()) && userMapper.existsByUserName(user.getTelephone()) > 0) { // 手机号不能是已存在用户的登录名 throw new BusinessException("手机号已经被绑定"); } if (user.getUsername().matches("1[0-9]{10}") && userMapper.existsByTelephone(user.getUsername()) > 0) { // 登录名符合手机号格式,而且该手机号已经存在 throw new BusinessException("手机号已经被绑定"); } // 密码先解密再加密 user.setPassword(manageCryptoService.reqAesDecrypt(user.getPassword())); user.setPassword(manageCryptoService.dbEncode(user.getPassword())); userMapper.insert(user); if (userAddReq.getSysNameList() != null) { for (String sysName : userAddReq.getSysNameList()) { userMapper.addUserSys(user.getUsername(), sysName); } } return userMapper.selectById(user.getId()); } @Transactional public User updateUser(String username, UserUpdateReq req) { User oldUser = userMapper.getByUsername(username); if (oldUser == null) { throw new BusinessException("用户不存在"); } boolean delRememberMeToken = false; // Session 操作标识,0 不操作;1 更新;2 删除 int sessionFlag = 0; // 修改了密码 if (StringUtils.isNotBlank(req.getPassword())) { // 密码先解密再加密 req.setPassword(manageCryptoService.reqAesDecrypt(req.getPassword())); req.setPassword(manageCryptoService.dbEncode(req.getPassword())); // 设置删除 RememberMeToken delRememberMeToken = true; // 更新Session sessionFlag = 1; } else { req.setPassword(null); } // 修改了手机号 if (StringUtils.isNotBlank(req.getTelephone()) && !req.getTelephone().equals(oldUser.getTelephone())) { if (userMapper.existsByTelephone(req.getTelephone()) > 0 || userMapper.existsByUserName(req.getTelephone()) > 0) { throw new BusinessException("手机号已经被绑定"); } } else { req.setTelephone(null); } // 修改了邮箱 if (StringUtils.isNotBlank(req.getEmail()) && !req.getEmail().equals(oldUser.getEmail())) { if (userMapper.existsByEmail(req.getEmail()) > 0) { throw new BusinessException("邮箱已经被绑定"); } } else { req.setEmail(null); } // 设置了过期、锁定、禁用 if ((req.getExpiredTime() != null && req.getExpiredTime().compareTo(new Date()) <= 0) || Objects.equals(req.getLocked(), EnumConstant.User_Locked_1) || Objects.equals(req.getEnabled(), EnumConstant.User_Enabled_0)) { // 设置删除 RememberMeToken delRememberMeToken = true; // 删除Session sessionFlag = 2; } User user = BeanMapper.mapper(req, User.class); user.setId(oldUser.getId()); userMapper.updateById(user); user = userMapper.selectById(oldUser.getId()); // 更新关联系统 if (req.getSysNameList() == null) { req.setSysNameList(new HashSet<>()); } userBindSysNameService.resetUserBindSys(user.getUsername(), req.getSysNameList()); if (delRememberMeToken) { // 删除RememberMe Token rememberMeTokenMapper.deleteByUsername(user.getUsername()); } if (sessionFlag == 1) { // 更新Session sessionService.reloadSecurityContext(user.getUsername()); } if (sessionFlag == 2) { // 删除Session sessionService.delSession(user.getUsername()); } return user; } @Transactional public User deleteUser(String username) { User user = userMapper.getByUsername(username); if (user == null) { throw new BusinessException("用户不存在"); } userMapper.deleteById(user.getId()); userMapper.delUserRole(user.getUsername()); userMapper.delAllUserSys(user.getUsername()); rememberMeTokenMapper.deleteByUsername(user.getUsername()); // 删除Session sessionService.delSession(user.getUsername()); return user; } } <|start_filename|>clever-security-server/src/main/java/org/clever/security/service/ManageByQueryService.java<|end_filename|> package org.clever.security.service; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import lombok.extern.slf4j.Slf4j; import org.clever.security.dto.request.RememberMeTokenQueryReq; import org.clever.security.dto.request.ServiceSysQueryReq; import org.clever.security.dto.request.UserLoginLogQueryReq; import org.clever.security.entity.ServiceSys; import org.clever.security.entity.model.UserLoginLogModel; import org.clever.security.entity.model.UserRememberMeToken; import org.clever.security.mapper.QueryMapper; import org.clever.security.mapper.ServiceSysMapper; import org.clever.security.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-10-07 19:38 <br/> */ @Transactional(readOnly = true) @Service @Slf4j public class ManageByQueryService { @Autowired private UserMapper userMapper; @Autowired private QueryMapper queryMapper; @Autowired private ServiceSysMapper serviceSysMapper; public Boolean existsUserByUsername(String username) { return userMapper.existsByUserName(username) > 0; } public Boolean existsUserByTelephone(String telephone) { return userMapper.existsByTelephone(telephone) > 0; } public Boolean existsUserByEmail(String email) { return userMapper.existsByEmail(email) > 0; } public List<String> allSysName() { List<String> sysNameList = serviceSysMapper.allSysName(); List<String> tmp = queryMapper.allSysName(); for (String sysName : tmp) { if (!sysNameList.contains(sysName)) { sysNameList.add(sysName); } } return sysNameList; } public List<String> findSysNameByUser(String username) { return userMapper.findSysNameByUsername(username); } public List<String> allRoleName() { return queryMapper.allRoleName(); } public List<String> findRoleNameByUser(String username) { return queryMapper.findRoleNameByUser(username); } public List<String> findPermissionStrByRole(String roleName) { return queryMapper.findPermissionStrByRole(roleName); } public IPage<UserRememberMeToken> findRememberMeToken(RememberMeTokenQueryReq req) { Page<UserRememberMeToken> page = new Page<>(req.getPageNo(), req.getPageSize()); page.setRecords(queryMapper.findRememberMeToken(req, page)); return page; } public IPage<UserLoginLogModel> findUserLoginLog(UserLoginLogQueryReq req) { Page<UserLoginLogModel> page = new Page<>(req.getPageNo(), req.getPageSize()); page.setRecords(queryMapper.findUserLoginLog(req, page)); return page; } public IPage<ServiceSys> findServiceSys(ServiceSysQueryReq req) { Page<ServiceSys> page = new Page<>(req.getPageNo(), req.getPageSize()); page.setRecords(queryMapper.findServiceSys(req, page)); return page; } } <|start_filename|>clever-security-server/src/main/java/org/clever/security/controller/ManageByQueryController.java<|end_filename|> package org.clever.security.controller; import com.baomidou.mybatisplus.core.metadata.IPage; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.clever.common.model.response.AjaxMessage; import org.clever.common.server.controller.BaseController; import org.clever.security.dto.request.RememberMeTokenQueryReq; import org.clever.security.dto.request.ServiceSysQueryReq; import org.clever.security.dto.request.UserLoginLogQueryReq; import org.clever.security.entity.ServiceSys; import org.clever.security.entity.model.UserLoginLogModel; import org.clever.security.entity.model.UserRememberMeToken; import org.clever.security.service.ManageByQueryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-10-02 20:50 <br/> */ @Api("管理页面查询") @RestController @RequestMapping("/api/manage") public class ManageByQueryController extends BaseController { @Autowired private ManageByQueryService manageByQueryService; @ApiOperation("查询username是否存在") @GetMapping("/user/username/{username}/exists") public AjaxMessage<Boolean> existsUserByUsername(@PathVariable("username") String username) { return new AjaxMessage<>(manageByQueryService.existsUserByUsername(username), "查询成功"); } @ApiOperation("查询telephone是否存在") @GetMapping("/user/telephone/{telephone}/exists") public AjaxMessage<Boolean> existsUserByTelephone(@PathVariable("telephone") String telephone) { return new AjaxMessage<>(manageByQueryService.existsUserByTelephone(telephone), "查询成功"); } @ApiOperation("查询email是否存在") @GetMapping("/user/email/{email}/exists") public AjaxMessage<Boolean> existsUserByEmail(@PathVariable("email") String email) { return new AjaxMessage<>(manageByQueryService.existsUserByEmail(email), "查询成功"); } @ApiOperation("查询所有系统名称") @GetMapping("/sys_name") public List<String> allSysName() { return manageByQueryService.allSysName(); } @ApiOperation("查询用户绑定的系统") @GetMapping("/sys_name/{username}") public List<String> findSysNameByUser(@PathVariable("username") String username) { return manageByQueryService.findSysNameByUser(username); } @ApiOperation("查询所有角色名称") @GetMapping("/role_name") public List<String> allRoleName() { return manageByQueryService.allRoleName(); } @ApiOperation("查询用户拥有的角色") @GetMapping("/role_name/{username}") public List<String> findRoleNameByUser(@PathVariable("username") String username) { return manageByQueryService.findRoleNameByUser(username); } @ApiOperation("查询角色拥有的权限字符串") @GetMapping("/permission_str/{roleName}") public List<String> findPermissionStrByRole(@PathVariable("roleName") String roleName) { return manageByQueryService.findPermissionStrByRole(roleName); } @ApiOperation("分页查询“记住我”功能的Token") @GetMapping("/remember_me_token") public IPage<UserRememberMeToken> findRememberMeToken(RememberMeTokenQueryReq req) { return manageByQueryService.findRememberMeToken(req); } @ApiOperation("分页查询用户登录日志") @GetMapping("/user_login_log") public IPage<UserLoginLogModel> findUserLoginLog(UserLoginLogQueryReq req) { return manageByQueryService.findUserLoginLog(req); } @ApiOperation("分页查询接入系统") @GetMapping("/service_sys") public IPage<ServiceSys> findServiceSys(ServiceSysQueryReq req) { return manageByQueryService.findServiceSys(req); } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/authentication/provider/AuthenticationUsernamePasswordToken.java<|end_filename|> package org.clever.security.authentication.provider; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.clever.security.authentication.AuthenticationLoginToken; import org.clever.security.exception.BadLoginTypeException; import org.clever.security.service.RequestCryptoService; import org.clever.security.token.login.BaseLoginToken; import org.clever.security.token.login.UsernamePasswordToken; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Component; /** * UsernamePasswordToken 验证逻辑 * 作者: lzw<br/> * 创建时间:2019-04-28 15:21 <br/> */ @Component @Slf4j public class AuthenticationUsernamePasswordToken implements AuthenticationLoginToken { private UsernamePasswordToken getUsernamePasswordToken(BaseLoginToken loginToken) { if (!(loginToken instanceof UsernamePasswordToken)) { throw new BadLoginTypeException(String.format("loginToken类型错误,%s | %s", loginToken.getClass(), loginToken.toString())); } return (UsernamePasswordToken) loginToken; } @Override public boolean supports(Class<?> loginToken) { return UsernamePasswordToken.class.isAssignableFrom(loginToken); } @Override public void preAuthenticationCheck(BaseLoginToken loginToken) throws AuthenticationException { UsernamePasswordToken usernamePasswordToken = getUsernamePasswordToken(loginToken); if (StringUtils.isBlank(usernamePasswordToken.getUsername())) { throw new BadCredentialsException("用户名不能为空"); } if (StringUtils.isBlank(usernamePasswordToken.getPassword())) { throw new BadCredentialsException("密码不能为空"); } } @Override public void mainAuthenticationChecks(BaseLoginToken loginToken, UserDetails loadedUser, RequestCryptoService requestCryptoService, BCryptPasswordEncoder bCryptPasswordEncoder) throws AuthenticationException { UsernamePasswordToken usernamePasswordToken = getUsernamePasswordToken(loginToken); // 用户密码需要AES对称加解密 网络密文传输 usernamePasswordToken.setPassword(requestCryptoService.reqAesDecrypt(usernamePasswordToken.getPassword())); // 用户名、密码校验 if (!usernamePasswordToken.getUsername().equals(loadedUser.getUsername()) || !bCryptPasswordEncoder.matches(usernamePasswordToken.getPassword(), loadedUser.getPassword())) { log.info("### 用户名密码验证失败 [{}]", loginToken.toString()); throw new BadCredentialsException("用户名密码验证失败"); } log.info("### 用户名密码验证成功 [{}]", loginToken.toString()); } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/entity/UserLoginLog.java<|end_filename|> package org.clever.security.entity; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * 用户登录日志(UserLoginLog)实体类 * * @author lizw * @since 2018-09-23 19:55:43 */ @Data public class UserLoginLog implements Serializable { private static final long serialVersionUID = -11162979906700377L; /** * 主键id */ private Long id; /** * 系统(或服务)名称 */ private String sysName; /** * 用户登录名 */ private String username; /** * 登录时间 */ private Date loginTime; /** * 登录IP */ private String loginIp; /** * 登录的用户信息 */ private String authenticationInfo; /** * 登录类型,0:sesion-cookie,1:jwt-token */ private Integer loginModel; /** * 登录SessionID */ private String sessionId; /** * 登录状态,0:未知;1:已登录;2:登录已过期 */ private Integer loginState; /** * 创建时间 */ private Date createAt; /** * 更新时间 */ private Date updateAt; } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/exception/BadCaptchaException.java<|end_filename|> package org.clever.security.exception; import org.springframework.security.core.AuthenticationException; /** * 验证码错误 * <p> * 作者: lzw<br/> * 创建时间:2018-09-19 22:33 <br/> */ public class BadCaptchaException extends AuthenticationException { public BadCaptchaException(String msg) { super(msg); } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/entity/Role.java<|end_filename|> package org.clever.security.entity; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * 角色表(Role)实体类 * * @author lizw * @since 2018-09-16 21:24:44 */ @Data public class Role implements Serializable { private static final long serialVersionUID = -72497893232578795L; /** 主键id */ private Long id; /** 角色名称 */ private String name; /** 角色说明 */ private String description; /** 创建时间 */ private Date createAt; /** 更新时间 */ private Date updateAt; } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/handler/UserLoginFailureHandler.java<|end_filename|> package org.clever.security.handler; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.clever.security.Constant; import org.clever.security.LoginModel; import org.clever.security.client.UserClient; import org.clever.security.config.SecurityConfig; import org.clever.security.config.model.LoginConfig; import org.clever.security.dto.response.LoginRes; import org.clever.security.exception.BadCaptchaException; import org.clever.security.exception.BadLoginTypeException; import org.clever.security.exception.CanNotLoginSysException; import org.clever.security.exception.ConcurrentLoginException; import org.clever.security.repository.LoginFailCountRepository; import org.clever.security.utils.HttpResponseUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.*; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.RedirectStrategy; import org.springframework.security.web.WebAttributes; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.stereotype.Component; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * 自定义登录失败处理类 * <p> * 作者: lzw<br/> * 创建时间:2018-03-17 23:04 <br/> */ @Component @Slf4j public class UserLoginFailureHandler implements AuthenticationFailureHandler { private final String defaultRedirectUrl = "/index.html"; private final Map<String, String> failureMessageMap = new HashMap<>(); @Autowired private SecurityConfig securityConfig; @Autowired private LoginFailCountRepository loginFailCountRepository; @Autowired private UserClient userClient; private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); private boolean hideUserNotFoundExceptions = true; public UserLoginFailureHandler(SecurityConfig securityConfig) { failureMessageMap.put(UsernameNotFoundException.class.getName(), "用户不存在"); failureMessageMap.put(BadCredentialsException.class.getName(), "用户名或密码错误"); failureMessageMap.put(AccountStatusException.class.getName(), "账户状态异常"); failureMessageMap.put(AccountExpiredException.class.getName(), "账户已过期"); failureMessageMap.put(LockedException.class.getName(), "账户被锁定"); failureMessageMap.put(DisabledException.class.getName(), "账户被禁用"); failureMessageMap.put(CredentialsExpiredException.class.getName(), "密码已过期"); failureMessageMap.put(BadCaptchaException.class.getName(), "验证码错误"); failureMessageMap.put(BadLoginTypeException.class.getName(), "不支持的登录类型"); failureMessageMap.put(CanNotLoginSysException.class.getName(), "您无权登录当前系统,请联系管理员授权"); failureMessageMap.put(ConcurrentLoginException.class.getName(), "并发登录数量超限"); if (securityConfig.getHideUserNotFoundExceptions() != null) { hideUserNotFoundExceptions = securityConfig.getHideUserNotFoundExceptions(); } } @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { Integer loginFailCount = null; LoginConfig login = securityConfig.getLogin(); if (login.getNeedCaptcha()) { if (LoginModel.jwt.equals(securityConfig.getLoginModel())) { // JwtToken 记录登录失败次数 Object object = request.getAttribute(Constant.Login_Username_Request_Key); if (object != null && StringUtils.isNotBlank(object.toString()) && userClient.canLogin(object.toString(), securityConfig.getSysName())) { loginFailCount = Long.valueOf(loginFailCountRepository.incrementLoginFailCount(object.toString())).intValue(); } } else { // Session 记录登录次数 Object loginFailCountStr = request.getSession().getAttribute(Constant.Login_Fail_Count_Session_Key); loginFailCount = 1; if (loginFailCountStr != null) { loginFailCount = NumberUtils.toInt(loginFailCountStr.toString(), 0) + 1; } request.getSession().setAttribute(Constant.Login_Fail_Count_Session_Key, loginFailCount); } } // 登录失败 - 是否需要跳转 if (login.getLoginFailureNeedRedirect() != null && login.getLoginFailureNeedRedirect()) { // 跳转 HttpSession session = request.getSession(false); if (session != null) { request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception); } sendRedirect(request, response, login.getLoginFailureRedirectPage()); return; } // 请求转发 if (login.getLoginFailureNeedForward() != null && login.getLoginFailureNeedForward()) { request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception); sendForward(request, response, login.getLoginFailureRedirectPage()); return; } // 不需要跳转 sendJsonData(response, exception, login, loginFailCount); } /** * 直接返回Json数据 */ private void sendJsonData(HttpServletResponse response, AuthenticationException exception, LoginConfig login, Integer loginFailCount) { String message = failureMessageMap.get(exception.getClass().getName()); if (hideUserNotFoundExceptions && exception instanceof UsernameNotFoundException) { message = failureMessageMap.get(BadCredentialsException.class.getName()); } if (StringUtils.isBlank(message)) { message = "登录失败"; } LoginRes loginRes = new LoginRes(false, message); if (loginFailCount != null) { if (login.getNeedCaptcha() && login.getNeedCaptchaByLoginFailCount() <= loginFailCount) { // 下次登录需要验证码 loginRes.setNeedCaptcha(true); } } log.info("### 登录失败不需要跳转 -> [{}]", loginRes); HttpResponseUtils.sendJsonBy401(response, loginRes); } /** * 页面跳转 (重定向) */ private void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException { if (StringUtils.isBlank(url)) { url = defaultRedirectUrl; } log.info("### 登录失败跳转Url(重定向) -> {}", url); if (!response.isCommitted()) { redirectStrategy.sendRedirect(request, response, url); } } /** * 页面跳转 (请求转发) */ private void sendForward(HttpServletRequest request, HttpServletResponse response, String url) throws ServletException, IOException { if (StringUtils.isBlank(url)) { url = defaultRedirectUrl; } log.info("### 登录失败跳转Url(请求转发) -> {}", url); request.getRequestDispatcher(url).forward(request, response); } } <|start_filename|>clever-security-server/src/main/java/org/clever/security/service/internal/UserBindSysNameService.java<|end_filename|> package org.clever.security.service.internal; import lombok.extern.slf4j.Slf4j; import org.clever.security.mapper.UserMapper; import org.clever.security.service.ISecurityContextService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.*; /** * 操作用户系统绑定的Service * <p> * 作者: lzw<br/> * 创建时间:2018-10-11 9:44 <br/> */ @Transactional(readOnly = true) @Service @Slf4j public class UserBindSysNameService { @Autowired private UserMapper userMapper; @Autowired private ISecurityContextService sessionService; /** * 重置用户系统绑定 * * @param userName 用户登录名 * @param sysNameList 系统名称集合 */ @Transactional public void resetUserBindSys(String userName, Collection<String> sysNameList) { if (sysNameList == null) { sysNameList = new ArrayList<>(); } // 获取关联系统列表 List<String> oldSysNameList = userMapper.findSysNameByUsername(userName); Set<String> addSysName = new HashSet<>(sysNameList); addSysName.removeAll(oldSysNameList); Set<String> delSysName = new HashSet<>(oldSysNameList); delSysName.removeAll(sysNameList); // 新增 for (String sysName : addSysName) { userMapper.addUserSys(userName, sysName); } // 删除 for (String sysName : delSysName) { userMapper.delUserSys(userName, sysName); // 删除Session sessionService.delSession(sysName, userName); } } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/repository/RedisJwtRepository.java<|end_filename|> package org.clever.security.repository; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jws; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.clever.common.exception.BusinessException; import org.clever.common.utils.CookieUtils; import org.clever.security.config.SecurityConfig; import org.clever.security.config.model.TokenConfig; import org.clever.security.service.GenerateKeyService; import org.clever.security.service.JwtTokenService; import org.clever.security.token.JwtAccessToken; import org.clever.security.token.JwtRefreshToken; import org.clever.security.token.SecurityContextToken; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.security.core.context.SecurityContext; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import java.time.Duration; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.concurrent.TimeUnit; /** * 作者: lzw<br/> * 创建时间:2018-11-20 11:12 <br/> */ @Component @Slf4j public class RedisJwtRepository { /** * 刷新令牌有效时间 */ private final Duration refreshTokenValidity; /** * JWT Token配置 */ private final TokenConfig tokenConfig; @Autowired private JwtTokenService jwtTokenService; @Autowired private RedisTemplate<String, Object> redisTemplate; @Autowired private GenerateKeyService generateKeyService; protected RedisJwtRepository(SecurityConfig securityConfig) { tokenConfig = securityConfig.getTokenConfig(); if (tokenConfig == null || tokenConfig.getRefreshTokenValidity() == null) { throw new IllegalArgumentException("未配置TokenConfig"); } refreshTokenValidity = tokenConfig.getRefreshTokenValidity(); } // -------------------------------------------------------------------------------------------------------------------------------------- JwtAccessToken public JwtAccessToken saveJwtToken(SecurityContextToken securityContextToken) { boolean rememberMe = securityContextToken.getLoginToken().isRememberMe(); // 保存 JwtAccessToken JwtAccessToken jwtAccessToken = jwtTokenService.createToken(securityContextToken, rememberMe); String JwtTokenKey = generateKeyService.getJwtTokenKey(jwtAccessToken.getClaims()); if (jwtAccessToken.getClaims().getExpiration() == null) { redisTemplate.opsForValue().set(JwtTokenKey, jwtAccessToken); } else { long timeout = jwtAccessToken.getClaims().getExpiration().getTime() - System.currentTimeMillis(); redisTemplate.opsForValue().set(JwtTokenKey, jwtAccessToken, timeout, TimeUnit.MILLISECONDS); } // 保存 JwtRefreshToken String jwtRefreshTokenKey = generateKeyService.getJwtRefreshTokenKey(jwtAccessToken.getRefreshToken()); JwtRefreshToken jwtRefreshToken = new JwtRefreshToken(securityContextToken.getName(), jwtAccessToken.getClaims().getId()); if (refreshTokenValidity.getSeconds() <= 0) { redisTemplate.opsForValue().set(jwtRefreshTokenKey, jwtRefreshToken); } else { redisTemplate.opsForValue().set(jwtRefreshTokenKey, jwtRefreshToken, refreshTokenValidity.getSeconds(), TimeUnit.SECONDS); } return jwtAccessToken; } public void deleteJwtTokenByKey(String JwtTokenKey) { JwtAccessToken jwtAccessToken = getJwtTokenByKey(JwtTokenKey); deleteJwtToken(jwtAccessToken); } public void deleteJwtToken(JwtAccessToken jwtAccessToken) { // 删除 JwtAccessToken String JwtTokenKey = generateKeyService.getJwtTokenKey(jwtAccessToken.getClaims()); redisTemplate.delete(JwtTokenKey); // 删除 JwtRefreshToken String jwtRefreshTokenKey = generateKeyService.getJwtRefreshTokenKey(jwtAccessToken.getRefreshToken()); redisTemplate.delete(jwtRefreshTokenKey); } public JwtAccessToken getJwtToken(HttpServletRequest request) { String token; if (Objects.equals(tokenConfig.isUseCookie(), true)) { token = CookieUtils.getCookie(request, tokenConfig.getJwtTokenKey()); } else { token = request.getHeader(tokenConfig.getJwtTokenKey()); } if (StringUtils.isBlank(token)) { throw new BusinessException("Token不存在"); } return getJwtToken(token); } public JwtAccessToken getJwtToken(String token) { Jws<Claims> claimsJws = jwtTokenService.getClaimsJws(token); return getJwtToken(claimsJws.getBody()); } public JwtAccessToken getJwtToken(Claims claims) { return getJwtToken(claims.getSubject(), claims.getId()); } public JwtAccessToken getJwtToken(String username, String tokenId) { String JwtTokenKey = generateKeyService.getJwtTokenKey(username, tokenId); return getJwtTokenByKey(JwtTokenKey); } public JwtAccessToken getJwtTokenByKey(String JwtTokenKey) { Object object = redisTemplate.opsForValue().get(JwtTokenKey); if (object == null) { throw new BusinessException("JwtToken已过期"); } if (!(object instanceof JwtAccessToken)) { throw new BusinessException("JwtToken类型错误"); } return (JwtAccessToken) object; } public Set<String> getJwtTokenPatternKey(String username) { Set<String> ketSet = redisTemplate.keys(generateKeyService.getJwtTokenPatternKey(username)); if (ketSet == null) { ketSet = new HashSet<>(0); } return ketSet; } // -------------------------------------------------------------------------------------------------------------------------------------- JwtRefreshToken public JwtRefreshToken getRefreshToken(String refreshToken) { String jwtRefreshTokenKey = generateKeyService.getJwtRefreshTokenKey(refreshToken); Object object = redisTemplate.opsForValue().get(jwtRefreshTokenKey); if (object == null) { throw new BusinessException("刷新令牌错误或已过期"); } if (!(object instanceof JwtRefreshToken)) { throw new BusinessException("刷新令牌类型错误"); } return (JwtRefreshToken) object; } // -------------------------------------------------------------------------------------------------------------------------------------- SecurityContext public void saveSecurityContext(SecurityContext context) { String securityContextKey = generateKeyService.getSecurityContextKey(context.getAuthentication().getName()); redisTemplate.opsForValue().set(securityContextKey, context); } public void deleteSecurityContext(String username) { String securityContextKey = generateKeyService.getSecurityContextKey(username); redisTemplate.delete(securityContextKey); } public SecurityContext getSecurityContext(JwtAccessToken jwtAccessToken) { return getSecurityContext(jwtAccessToken.getClaims().getSubject()); } public SecurityContext getSecurityContext(Claims claims) { return getSecurityContext(claims.getSubject()); } public SecurityContext getSecurityContext(String username) { String securityContextKey = generateKeyService.getSecurityContextKey(username); Object object = redisTemplate.opsForValue().get(securityContextKey); if (object == null) { throw new BusinessException("SecurityContext不存在"); } if (!(object instanceof SecurityContext)) { throw new BusinessException("SecurityContext类型错误"); } return (SecurityContext) object; } // -------------------------------------------------------------------------------------------------------------------------------------- validationToken /** * 验证令牌 (不会抛出异常) */ public boolean validationToken(HttpServletRequest request) { String token = request.getHeader(tokenConfig.getJwtTokenKey()); if (StringUtils.isBlank(token) && tokenConfig.isUseCookie()) { token = CookieUtils.getCookie(request, tokenConfig.getJwtTokenKey()); } if (StringUtils.isBlank(token)) { return false; } return validationToken(token); } /** * 验证令牌 (不会抛出异常) */ public boolean validationToken(String token) { try { Jws<Claims> claimsJws = jwtTokenService.getClaimsJws(token); if (claimsJws != null) { return true; } } catch (Throwable ignored) { } return false; } } <|start_filename|>clever-security-client/src/main/java/org/clever/security/config/CleverSecurityFeignConfiguration.java<|end_filename|> package org.clever.security.config; import feign.RequestInterceptor; import feign.RequestTemplate; import lombok.extern.slf4j.Slf4j; import org.clever.common.utils.spring.SpringContextHolder; import java.util.Map; /** * 作者: lzw<br/> * 创建时间:2019-05-15 17:58 <br/> */ @Slf4j public class CleverSecurityFeignConfiguration implements RequestInterceptor { /** * 服务访问Token */ private CleverSecurityAccessTokenConfig accessTokenConfig; @Override public void apply(RequestTemplate template) { if (accessTokenConfig == null) { accessTokenConfig = SpringContextHolder.getBean(CleverSecurityAccessTokenConfig.class); // log.debug("读取访问clever-security-server服务API的授权Token请求头: {}", accessTokenConfig.getAccessTokenHeads()); } if (accessTokenConfig.getAccessTokenHeads() != null && accessTokenConfig.getAccessTokenHeads().size() > 0) { // log.debug("[访问clever-security-server的AccessToken请求头] --> {}", accessTokenConfig.getAccessTokenHeads()); for (Map.Entry<String, String> entry : accessTokenConfig.getAccessTokenHeads().entrySet()) { template.header(entry.getKey(), entry.getValue()); } } } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/event/HttpSessionCreatedListener.java<|end_filename|> package org.clever.security.event;//package org.clever.security.event; import lombok.extern.slf4j.Slf4j; import org.clever.security.LoginModel; import org.clever.security.config.SecurityConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.security.web.session.HttpSessionCreatedEvent; import org.springframework.stereotype.Component; import javax.servlet.http.HttpSession; /** * Session 创建监听 * <p> * 作者: lzw<br/> * 创建时间:2018-09-23 19:28 <br/> */ @Component @Slf4j public class HttpSessionCreatedListener implements ApplicationListener<HttpSessionCreatedEvent> { @Autowired private SecurityConfig securityConfig; @Override public void onApplicationEvent(HttpSessionCreatedEvent event) { HttpSession session = event.getSession(); if (LoginModel.jwt.equals(securityConfig.getLoginModel())) { log.error("### 新建Session [{}] -> JWT Token 不应该创建HttpSession", session.getId()); } else { log.info("### 新建Session [{}]", session.getId()); } } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/token/login/RememberMeToken.java<|end_filename|> package org.clever.security.token.login; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; import lombok.Setter; import org.clever.security.LoginTypeConstant; /** * 作者: lzw<br/> * 创建时间:2019-04-28 18:25 <br/> */ public class RememberMeToken extends BaseLoginToken { /** * 用户名 */ @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) @Setter @Getter private String username; public RememberMeToken() { super(LoginTypeConstant.RememberMe); } /** * 返回密码 */ @Override public Object getCredentials() { return null; } /** * 返回用户登录唯一ID */ @Override public Object getPrincipal() { return username; } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/RoleBindPermissionRes.java<|end_filename|> package org.clever.security.dto.response; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.response.BaseResponse; import org.clever.security.entity.Permission; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-10-04 12:56 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class RoleBindPermissionRes extends BaseResponse { @ApiModelProperty("角色名称") private String roleName; @ApiModelProperty("权限列表") private List<Permission> permissionList; } <|start_filename|>clever-security-server/src/main/java/org/clever/security/controller/ManageBySessionController.java<|end_filename|> package org.clever.security.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.clever.security.dto.response.ForcedOfflineRes; import org.clever.security.service.ISecurityContextService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContext; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Map; /** * 作者: lzw<br/> * 创建时间:2018-11-12 10:21 <br/> */ @Api("Session管理") @RestController @RequestMapping("/api/manage") public class ManageBySessionController { @Autowired private ISecurityContextService sessionService; @ApiOperation("重新加载用户SessionSecurityContext") @GetMapping("/reload_session_security_context/{username}") public Map<String, List<SecurityContext>> reloadSessionSecurityContext(@PathVariable("username") String username) { return sessionService.reloadSecurityContext(username); } @ApiOperation("读取用户SessionSecurityContext") @GetMapping("/session_security_context/{sysName}/{username}") public Map<String, SecurityContext> getSessionSecurityContext(@PathVariable("sysName") String sysName, @PathVariable("username") String username) { return sessionService.getSecurityContext(sysName, username); } @ApiOperation("读取用户SessionSecurityContext") @GetMapping("/session_security_context/{sessionId}") public SecurityContext getSessionSecurityContext(@PathVariable("sessionId") String sessionId) { return sessionService.getSecurityContext(sessionId); } @ApiOperation("踢出用户(强制下线)") @GetMapping("/forced_offline/{sysName}/{username}") public ForcedOfflineRes forcedOffline(@PathVariable("sysName") String sysName, @PathVariable("username") String username) { int count = sessionService.forcedOffline(sysName, username); ForcedOfflineRes forcedOfflineRes = new ForcedOfflineRes(); forcedOfflineRes.setCount(count); forcedOfflineRes.setSysName(sysName); forcedOfflineRes.setUsername(username); return forcedOfflineRes; } } <|start_filename|>clever-security-server/src/main/java/org/clever/security/service/internal/RoleBindPermissionService.java<|end_filename|> package org.clever.security.service.internal; import lombok.extern.slf4j.Slf4j; import org.clever.security.mapper.QueryMapper; import org.clever.security.mapper.RoleMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.*; /** * 作者: lzw<br/> * 创建时间:2018-10-19 19:30 <br/> */ @Transactional(readOnly = true) @Service @Slf4j public class RoleBindPermissionService { @Autowired private RoleMapper roleMapper; @Autowired private QueryMapper queryMapper; @Autowired private ReLoadSessionService reLoadSessionService; /** * 重新为角色分配权限 * * @param roleName 角色名称 * @param permissionStrList 权限名称集合 */ @Transactional public void resetRoleBindPermission(String roleName, Collection<String> permissionStrList) { if (permissionStrList == null) { permissionStrList = new ArrayList<>(); } // 获取关联角色列表 List<String> oldPermissionStrList = queryMapper.findPermissionStrByRole(roleName); Set<String> addPermissionStr = new HashSet<>(permissionStrList); addPermissionStr.removeAll(oldPermissionStrList); Set<String> delPermissionStr = new HashSet<>(oldPermissionStrList); delPermissionStr.removeAll(permissionStrList); // 新增 for (String permissionStr : addPermissionStr) { roleMapper.addPermission(roleName, permissionStr); } // 删除 for (String permissionStr : delPermissionStr) { roleMapper.delPermission(roleName, permissionStr); } // 分析受影响的用户并更新对应的Session reLoadSessionService.onChangeRole(roleName); } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/authentication/LoadThirdUser.java<|end_filename|> package org.clever.security.authentication; import org.clever.security.client.ManageByUserClient; import org.clever.security.client.UserClient; import org.clever.security.model.LoginUserDetails; import org.clever.security.token.login.BaseLoginToken; /** * 加载第三方用户信息 * <p> * 作者: lzw<br/> * 创建时间:2019-04-28 18:55 <br/> */ public interface LoadThirdUser { /** * 是否支持当前loginToken从第三方加载用户信息 * * @param loginToken 当前登录Token * @return 支持返回true */ boolean supports(BaseLoginToken loginToken); /** * 从第三方系统加载用户信息 * * @param loginToken 当前登录Token * @param userClient 读取系统用户 * @param manageByUserClient 新增系统用户 * @return 如仍需从权限系统读取用户信息则返回null,如果不需要则返回LoginUserDetails实体(建议把三方系统用户同步到当前系统并返回null) */ LoginUserDetails loadUser(BaseLoginToken loginToken, UserClient userClient, ManageByUserClient manageByUserClient); } <|start_filename|>clever-security-server/src/main/java/org/clever/security/mapper/UserLoginLogMapper.java<|end_filename|> package org.clever.security.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.clever.security.entity.UserLoginLog; import org.springframework.stereotype.Repository; /** * 作者: lzw<br/> * 创建时间:2018-09-23 16:02 <br/> */ @Repository @Mapper public interface UserLoginLogMapper extends BaseMapper<UserLoginLog> { UserLoginLog getBySessionId(@Param("sessionId") String sessionId); } <|start_filename|>clever-security-model/src/main/java/org/clever/security/model/UserAuthority.java<|end_filename|> package org.clever.security.model; import lombok.Getter; import org.springframework.security.core.GrantedAuthority; /** * 权限信息 * <p> * 作者: lzw<br/> * 创建时间:2018-03-18 14:05 <br/> */ @Getter public final class UserAuthority implements GrantedAuthority { /** 权限字符串 */ private final String authority; /** 权限标题 */ private final String title; public UserAuthority(String authority, String title) { this.authority = authority; this.title = title; } @Override public String getAuthority() { return authority; } } <|start_filename|>clever-security-server/src/main/java/org/clever/security/controller/ManageByRoleController.java<|end_filename|> package org.clever.security.controller; import com.baomidou.mybatisplus.core.metadata.IPage; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.clever.common.server.controller.BaseController; import org.clever.common.utils.mapper.BeanMapper; import org.clever.security.dto.request.RoleAddReq; import org.clever.security.dto.request.RoleQueryPageReq; import org.clever.security.dto.request.RoleUpdateReq; import org.clever.security.dto.response.RoleInfoRes; import org.clever.security.entity.Role; import org.clever.security.service.ManageByRoleService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; /** * 作者: lzw<br/> * 创建时间:2018-10-02 20:47 <br/> */ @Api("角色管理") @RestController @RequestMapping("/api/manage") public class ManageByRoleController extends BaseController { @Autowired private ManageByRoleService manageByRoleService; @ApiOperation("查询权限列表") @GetMapping("/role") public IPage<Role> findByPage(RoleQueryPageReq roleQueryPageReq) { return manageByRoleService.findByPage(roleQueryPageReq); } @ApiOperation("新增权限") @PostMapping("/role") public Role addRole(@RequestBody @Validated RoleAddReq roleAddReq) { Role role = BeanMapper.mapper(roleAddReq, Role.class); return manageByRoleService.addRole(role); } @ApiOperation("更新权限") @PutMapping("/role/{name}") public Role updateRole(@PathVariable("name") String name, @RequestBody @Validated RoleUpdateReq roleUpdateReq) { return manageByRoleService.updateRole(name, roleUpdateReq); } @ApiOperation("删除权限") @DeleteMapping("/role/{name}") public Role delRole(@PathVariable("name") String name) { return manageByRoleService.delRole(name); } @ApiOperation("获取权限信息") @GetMapping("/role/{name}") public RoleInfoRes getRoleInfo(@PathVariable("name") String name) { return manageByRoleService.getRoleInfo(name); } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/authentication/TokenAuthenticationManager.java<|end_filename|> package org.clever.security.authentication; import lombok.extern.slf4j.Slf4j; import org.clever.common.exception.BusinessException; import org.clever.security.LoginModel; import org.clever.security.client.ManageByUserClient; import org.clever.security.client.UserClient; import org.clever.security.config.SecurityConfig; import org.clever.security.config.model.LoginConfig; import org.clever.security.exception.BadLoginTypeException; import org.clever.security.exception.ConcurrentLoginException; import org.clever.security.model.LoginUserDetails; import org.clever.security.repository.RedisJwtRepository; import org.clever.security.service.GlobalUserDetailsService; import org.clever.security.service.RequestCryptoService; import org.clever.security.token.JwtAccessToken; import org.clever.security.token.SecurityContextToken; import org.clever.security.token.login.BaseLoginToken; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.AuthenticationTrustResolver; import org.springframework.security.authentication.AuthenticationTrustResolverImpl; import org.springframework.security.authentication.InternalAuthenticationServiceException; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserCache; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsChecker; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.core.userdetails.cache.NullUserCache; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Component; import java.util.List; import java.util.Set; import java.util.stream.Collectors; /** * 登录Token认证 BaseLoginToken * <p> * 作者: lzw<br/> * 创建时间:2018-03-15 17:41 <br/> */ @Component @Slf4j public class TokenAuthenticationManager implements AuthenticationProvider { /** * 登入模式 */ private LoginModel loginModel; /** * 同一个用户并发登录次数限制(-1表示不限制) */ private final int concurrentLoginCount; /** * 同一个用户并发登录次数达到最大值之后,是否不允许之后的登录(false 之后登录的把之前登录的挤下来) */ private final boolean notAllowAfterLogin; /** * 密码处理 */ @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; /** * 加载用户信息 */ @Autowired private GlobalUserDetailsService globalUserDetailsService; /** * 读取系统用户 */ @Autowired private UserClient userClient; /** * 新增系统用户 */ @Autowired private ManageByUserClient manageByUserClient; /** * 从第三方加载用户信息支持 */ @Autowired(required = false) private List<LoadThirdUser> loadThirdUserList; /** * 帐号校验(密码认证之前) */ @Autowired @Qualifier("DefaultPreAuthenticationChecks") private UserDetailsChecker preAuthenticationChecks; /** * 帐号校验(密码认证之后) */ @Autowired @Qualifier("DefaultPostAuthenticationChecks") private UserDetailsChecker postAuthenticationChecks; /** * 请求参数加密/解密 */ @Autowired private RequestCryptoService requestCryptoService; /** * JwtToken数据存取操作组件 */ @Autowired private RedisJwtRepository redisJwtRepository; /** * Token认证登录 */ @Autowired private List<AuthenticationLoginToken> authenticationLoginTokenList; /** * 用户数据本地缓存 */ private UserCache userCache = new NullUserCache(); /** * 解析授权信息 */ private AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl(); public TokenAuthenticationManager(SecurityConfig securityConfig) { LoginConfig login = securityConfig.getLogin(); if (login == null) { throw new BusinessException("未配置Login配置"); } concurrentLoginCount = login.getConcurrentLoginCount(); notAllowAfterLogin = login.getNotAllowAfterLogin(); loginModel = securityConfig.getLoginModel(); } /** * 是否支持验证此身份类型 */ @Override public boolean supports(Class<?> authentication) { if (BaseLoginToken.class.isAssignableFrom(authentication)) { if (authenticationLoginTokenList == null) { log.warn("未注入Token认证登录组件"); } else { for (AuthenticationLoginToken authenticationLoginToken : authenticationLoginTokenList) { if (authenticationLoginToken.supports(authentication)) { return true; } } } } return false; } /** * 认证用户登录 */ @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { Authentication currentLogined = SecurityContextHolder.getContext().getAuthentication(); if (currentLogined != null && currentLogined.isAuthenticated() && !authenticationTrustResolver.isRememberMe(currentLogined)) { log.info("### 当前用户已登录拦截 [{}]", currentLogined.toString()); return currentLogined; } if (authentication.isAuthenticated()) { log.info("### 取消认证,Authentication已经认证成功 [{}]", authentication.toString()); return authentication; } log.info("### 开始验证用户[{}]", authentication.toString()); if (!(authentication instanceof BaseLoginToken)) { throw new BadLoginTypeException(String.format("不支持的登录信息,%s | %s", authentication.getClass(), authentication.toString())); } // 获取对应的认证组件 AuthenticationLoginToken authenticationLoginToken = null; for (AuthenticationLoginToken tmp : authenticationLoginTokenList) { if (tmp.supports(authentication.getClass())) { authenticationLoginToken = tmp; break; } } if (authenticationLoginToken == null) { throw new InternalAuthenticationServiceException("找不到Token认证登录组件"); } BaseLoginToken loginToken = (BaseLoginToken) authentication; authenticationLoginToken.preAuthenticationCheck(loginToken); // 查询帐号信息 boolean cacheWasUsed = true; UserDetails loadedUser = this.userCache.getUserFromCache(loginToken.getName()); if (loadedUser == null) { cacheWasUsed = false; try { loadedUser = retrieveUser(loginToken); } catch (UsernameNotFoundException notFound) { log.info("### 用户不存在[username={}]", loginToken.getName()); throw notFound; } log.info("### 已查询到用户信息[{}]", loadedUser.toString()); } // 验证帐号信息 try { preAuthenticationChecks.check(loadedUser); authenticationLoginToken.mainAuthenticationChecks(loginToken, loadedUser, requestCryptoService, bCryptPasswordEncoder); } catch (AuthenticationException exception) { if (cacheWasUsed) { // 缓存中的数据不一定准确,如果使用缓存数据身份认证异常,则直接使用数据库的数据 cacheWasUsed = false; // 检查此处的 hideUserNotFoundExceptions 是否需要判断 loadedUser = retrieveUser(loginToken); preAuthenticationChecks.check(loadedUser); authenticationLoginToken.mainAuthenticationChecks(loginToken, loadedUser, requestCryptoService, bCryptPasswordEncoder); } else { throw exception; } } postAuthenticationChecks.check(loadedUser); log.info("### 用户认证成功 [{}]", loadedUser.toString()); // 帐号信息存入缓存 if (!cacheWasUsed) { this.userCache.putUserInCache(loadedUser); } // 返回认证成功的 Authentication Authentication successAuthentication = createSuccessAuthentication(loginToken, loadedUser); // JwtToken 并发登录控制 if (LoginModel.jwt.equals(loginModel)) { concurrentLogin(loadedUser.getUsername()); } return successAuthentication; } /** * 查询用户 */ private UserDetails retrieveUser(BaseLoginToken loginToken) { UserDetails loadedUser = null; try { // 从第三方加载用户数据 LoadThirdUser loadThirdUser = null; if (loadThirdUserList != null) { for (LoadThirdUser tmp : loadThirdUserList) { if (tmp.supports(loginToken)) { loadThirdUser = tmp; break; } } } if (loadThirdUser != null) { loadedUser = loadThirdUser.loadUser(loginToken, userClient, manageByUserClient); } if (loadedUser == null) { loadedUser = globalUserDetailsService.loadUserByUsername(loginToken.getName()); } } catch (UsernameNotFoundException notFound) { throw notFound; } catch (Exception repositoryProblem) { throw new InternalAuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem); } return loadedUser; } /** * 创建认证成功的Authentication */ private SecurityContextToken createSuccessAuthentication(BaseLoginToken loginToken, UserDetails userDetails) { LoginUserDetails loginUserDetails; if (!(userDetails instanceof LoginUserDetails)) { throw new InternalAuthenticationServiceException(String.format("加载的用户类型不正确,%s | %s", userDetails.getClass(), userDetails.toString())); } loginUserDetails = (LoginUserDetails) userDetails; return new SecurityContextToken(loginToken, loginUserDetails); } /** * JwtToken 并发登录控制 */ private void concurrentLogin(String username) { if (concurrentLoginCount <= 0) { return; } Set<String> ketSet = redisJwtRepository.getJwtTokenPatternKey(username); if (ketSet != null && ketSet.size() >= concurrentLoginCount) { if (notAllowAfterLogin) { throw new ConcurrentLoginException("并发登录数量超限"); } // 删除之前登录的Token 和 刷新令牌 List<String> list = ketSet.stream().sorted().collect(Collectors.toList()); int delCount = list.size() - concurrentLoginCount + 1; for (int i = 0; i < delCount; i++) { String JwtTokenKey = list.get(i); JwtAccessToken jwtAccessToken = null; try { jwtAccessToken = redisJwtRepository.getJwtTokenByKey(JwtTokenKey); } catch (Throwable ignored) { } assert jwtAccessToken != null; redisJwtRepository.deleteJwtToken(jwtAccessToken); } } } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/authentication/DefaultPostAuthenticationChecks.java<|end_filename|> package org.clever.security.authentication; import lombok.extern.slf4j.Slf4j; import org.springframework.security.authentication.CredentialsExpiredException; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsChecker; import org.springframework.stereotype.Component; /** * 验证帐号信息成功之后的校验 * <p> * 作者: lzw<br/> * 创建时间:2018-09-19 16:33 <br/> */ @Component("DefaultPostAuthenticationChecks") @Slf4j public class DefaultPostAuthenticationChecks implements UserDetailsChecker { @Override public void check(UserDetails user) { if (!user.isCredentialsNonExpired()) { log.info("帐号密码已过期 [username={}]", user.getUsername()); throw new CredentialsExpiredException("帐号密码已过期"); } } } <|start_filename|>clever-security-server/src/main/java/org/clever/security/service/local/UserServiceProxy.java<|end_filename|> package org.clever.security.service.local; import lombok.extern.slf4j.Slf4j; import org.clever.security.client.UserClient; import org.clever.security.dto.request.UserAuthenticationReq; import org.clever.security.dto.response.UserAuthenticationRes; import org.clever.security.entity.Permission; import org.clever.security.entity.User; import org.clever.security.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-11-11 19:29 <br/> */ @Component @Slf4j public class UserServiceProxy implements UserClient { @Autowired private UserService userService; @Override public User getUser(String unique) { return userService.getUser(unique); } @Override public List<Permission> findAllPermission(String username, String sysName) { return userService.findAllPermission(username, sysName); } @Override public Boolean canLogin(String username, String sysName) { return userService.canLogin(username, sysName); } @Override public UserAuthenticationRes authentication(UserAuthenticationReq req) { return userService.authenticationAndRes(req); } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/config/BaseWebSecurityConfig.java<|end_filename|> package org.clever.security.config; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.password.PasswordEncoder; import java.util.ArrayList; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2019-04-26 10:06 <br/> */ @Slf4j public abstract class BaseWebSecurityConfig extends WebSecurityConfigurerAdapter { public BaseWebSecurityConfig() { super(false); } /** * 密码编码码器 */ abstract PasswordEncoder getPasswordEncoder(); /** * 获取用户信息组件 */ abstract UserDetailsService getUserDetailsService(); /** * 用户认证组件 */ abstract List<AuthenticationProvider> getAuthenticationProviderList(); /** * 配置信息 */ abstract SecurityConfig getSecurityConfig(); /** * 设置AuthenticationManager组件配置 */ @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { super.configure(auth); // 添加认证组件 List<AuthenticationProvider> authenticationProviderList = getAuthenticationProviderList(); if (authenticationProviderList == null || authenticationProviderList.size() <= 0) { throw new RuntimeException("缺少认证组件"); } for (AuthenticationProvider authenticationProvider : authenticationProviderList) { auth.authenticationProvider(authenticationProvider); } auth // 设置认证事件发布组件 // .authenticationEventPublisher(null) // 是否擦除认证凭证 .eraseCredentials(true) // 设置获取用户认证信息和授权信息组件 .userDetailsService(getUserDetailsService()) // 设置密码编码码器 .passwordEncoder(getPasswordEncoder()); } /** * 使用自定义的 UserDetailsService */ @Override protected UserDetailsService userDetailsService() { return getUserDetailsService(); } /** * 全局请求忽略规则配置(比如说静态文件,比如说注册页面)<br/> * 全局HttpFirewall配置 <br/> * 是否debug配置 <br/> * 全局SecurityFilterChain配置 <br/> * privilegeEvaluator、expressionHandler、securityInterceptor、 <br/> */ @Override public void configure(WebSecurity web) { SecurityConfig securityConfig = getSecurityConfig(); // 设置调试 if (securityConfig.getEnableDebug() != null) { web.debug(securityConfig.getEnableDebug()); } // 配置忽略的路径 if (securityConfig.getIgnoreUrls() == null) { securityConfig.setIgnoreUrls(new ArrayList<>()); } // 加入 /403.html if (StringUtils.isNotBlank(securityConfig.getForbiddenForwardPage()) && !securityConfig.getIgnoreUrls().contains(securityConfig.getForbiddenForwardPage())) { securityConfig.getIgnoreUrls().add(securityConfig.getForbiddenForwardPage()); } // 加入 /login.html if (StringUtils.isNotBlank(securityConfig.getLogin().getLoginPage()) && !securityConfig.getIgnoreUrls().contains(securityConfig.getLogin().getLoginPage())) { securityConfig.getIgnoreUrls().add(securityConfig.getLogin().getLoginPage()); } // 加入 login-failure-redirect-page if (StringUtils.isNotBlank(securityConfig.getLogin().getLoginFailureRedirectPage()) && !securityConfig.getIgnoreUrls().contains(securityConfig.getLogin().getLoginFailureRedirectPage())) { securityConfig.getIgnoreUrls().add(securityConfig.getLogin().getLoginFailureRedirectPage()); } // 加入 logout-success-redirect-page if (StringUtils.isNotBlank(securityConfig.getLogout().getLogoutSuccessRedirectPage()) && !securityConfig.getIgnoreUrls().contains(securityConfig.getLogout().getLogoutSuccessRedirectPage())) { securityConfig.getIgnoreUrls().add(securityConfig.getLogout().getLogoutSuccessRedirectPage()); } if (securityConfig.getIgnoreUrls().size() > 0) { web.ignoring().antMatchers(securityConfig.getIgnoreUrls().toArray(new String[0])); // 打印相应的日志 if (log.isInfoEnabled()) { StringBuilder strTmp = new StringBuilder(); strTmp.append("\r\n"); strTmp.append("#=======================================================================================================================#\r\n"); strTmp.append("不需要登录认证的资源:\r\n"); for (String url : securityConfig.getIgnoreUrls()) { strTmp.append("\t").append(url).append("\r\n"); } strTmp.append("#=======================================================================================================================#"); log.info(strTmp.toString()); } } } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/repository/LoginFailCountRepository.java<|end_filename|> package org.clever.security.repository; import lombok.extern.slf4j.Slf4j; import org.clever.security.service.GenerateKeyService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import java.util.concurrent.TimeUnit; /** * 作者: lzw<br/> * 创建时间:2018-11-20 21:41 <br/> */ @Component @Slf4j public class LoginFailCountRepository { @Autowired private RedisTemplate<String, Object> redisTemplate; @Autowired private GenerateKeyService generateKeyService; public long incrementLoginFailCount(String username) { String loginFailCountKey = generateKeyService.getLoginFailCountKey(username); Long count = redisTemplate.boundValueOps(loginFailCountKey).increment(1); redisTemplate.expire(loginFailCountKey, 30, TimeUnit.MINUTES); return count == null ? 0 : count; } public void deleteLoginFailCount(String username) { String loginFailCountKey = generateKeyService.getLoginFailCountKey(username); redisTemplate.delete(loginFailCountKey); } public long getLoginFailCount(String username) { String loginFailCountKey = generateKeyService.getLoginFailCountKey(username); Boolean exists = redisTemplate.hasKey(loginFailCountKey); if (exists != null && !exists) { return 0L; } Long count = redisTemplate.boundValueOps(loginFailCountKey).increment(0); return count == null ? 0 : count; } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/config/model/TokenConfig.java<|end_filename|> package org.clever.security.config.model; import lombok.Data; import java.time.Duration; /** * JWT Token配置 * 作者: lzw<br/> * 创建时间:2019-04-25 19:04 <br/> */ @Data public class TokenConfig { /** * Token Redis前缀 */ private String redisNamespace = "jwt"; /** * Token签名密钥 */ private String secretKey = "clever-security-jwt"; /** * Token有效时间(默认:7天) */ private Duration tokenValidity = Duration.ofDays(7); /** * Token记住我有效时间(默认:15天) */ private Duration tokenValidityForRememberMe = Duration.ofDays(15); /** * 刷新令牌有效时间 */ private Duration refreshTokenValidity = Duration.ofDays(30); /** * 设置密钥过期时间 (格式 HH:mm:ss) */ private String hoursInDay = "03:45:00"; /** * iss(签发者) */ private String issuer = "clever-security-jwt"; /** * aud(接收方) */ private String audience = "clever-*"; /** * 使用Cookie读写JWT Token */ private boolean useCookie = false; /** * Head或者Cookie中的JwtToken的key值 */ private String jwtTokenKey = "Authorization"; } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/handler/UserAccessDeniedHandler.java<|end_filename|> package org.clever.security.handler; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.clever.security.config.SecurityConfig; import org.clever.security.dto.response.AccessDeniedRes; import org.clever.security.utils.HttpRequestUtils; import org.clever.security.utils.HttpResponseUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.WebAttributes; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.stereotype.Component; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 拒绝访问处理器 * 作者: lzw<br/> * 创建时间:2018-03-18 15:09 <br/> */ @Component @Getter @Slf4j public class UserAccessDeniedHandler implements AccessDeniedHandler { @SuppressWarnings("FieldCanBeLocal") private final String defaultRedirectUrl = "/403.html"; @Autowired private SecurityConfig securityConfig; @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { // 不需要跳转 if (securityConfig.getForbiddenNeedForward() != null && !securityConfig.getForbiddenNeedForward()) { sendJsonData(response); return; } // 需要跳转 - 判断请求是否需要跳转 if (HttpRequestUtils.isJsonResponse(request)) { sendJsonData(response); return; } // 需要跳转 String url = securityConfig.getForbiddenForwardPage(); if (StringUtils.isBlank(url)) { url = defaultRedirectUrl; } request.setAttribute(WebAttributes.ACCESS_DENIED_403, accessDeniedException); response.setStatus(HttpServletResponse.SC_FORBIDDEN); RequestDispatcher dispatcher = request.getRequestDispatcher(url); dispatcher.forward(request, response); } /** * 直接返回Json数据 */ private void sendJsonData(HttpServletResponse response) { AccessDeniedRes accessDeniedRes = new AccessDeniedRes("没有访问权限"); HttpResponseUtils.sendJsonBy403(response, accessDeniedRes); } } <|start_filename|>clever-security-server/src/main/java/org/clever/security/job/CheckUserLoginLogJob.java<|end_filename|> package org.clever.security.job; import lombok.extern.slf4j.Slf4j; import org.clever.common.utils.GlobalJob; import org.springframework.stereotype.Component; /** * 作者: lzw<br/> * 创建时间:2018-11-12 12:49 <br/> */ @Component @Slf4j public class CheckUserLoginLogJob extends GlobalJob { @Override protected void internalExecute() { // TODO 检查登录状态-校正Session状态 // TODO Token 状态 } @Override protected void exceptionHandle(Throwable e) { } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/repository/SessionRedisSecurityContextRepository.java<|end_filename|> //package org.clever.security.repository; // //import org.springframework.security.web.context.HttpSessionSecurityContextRepository; // ///** // * 作者: lzw<br/> // * 创建时间:2019-05-16 14:26 <br/> // */ //public class SessionRedisSecurityContextRepository extends HttpSessionSecurityContextRepository { // //} <|start_filename|>clever-security-server/src/main/java/org/clever/security/service/local/ServiceSysServiceProxy.java<|end_filename|> package org.clever.security.service.local; import lombok.extern.slf4j.Slf4j; import org.clever.common.utils.mapper.BeanMapper; import org.clever.security.client.ServiceSysClient; import org.clever.security.dto.request.ServiceSysAddReq; import org.clever.security.entity.ServiceSys; import org.clever.security.service.ServiceSysService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; /** * 参考 ServiceSysController * <p> * 作者: lzw<br/> * 创建时间:2018-11-11 19:28 <br/> */ @Component @Slf4j public class ServiceSysServiceProxy implements ServiceSysClient { @Autowired private ServiceSysService serviceSysService; @Override public List<ServiceSys> allSysName() { return serviceSysService.selectAll(); } @Override public ServiceSys registerSys(ServiceSysAddReq serviceSysAddReq) { ServiceSys serviceSys = BeanMapper.mapper(serviceSysAddReq, ServiceSys.class); return serviceSysService.registerSys(serviceSys); } @Override public ServiceSys delServiceSys(String sysName) { return serviceSysService.delServiceSys(sysName); } } <|start_filename|>clever-security-server/src/test/java/org/clever/security/test/CryptoUtilsTest.java<|end_filename|> package org.clever.security.test; import lombok.extern.slf4j.Slf4j; import org.clever.common.utils.codec.CryptoUtils; import org.clever.common.utils.codec.EncodeDecodeUtils; import org.junit.Test; /** * 作者: lzw<br/> * 创建时间:2018-10-08 10:25 <br/> */ @Slf4j public class CryptoUtilsTest { @Test public void t01() { log.info("{}",EncodeDecodeUtils.encodeHex("clever-security-server李志伟".getBytes())); String str = "李志伟123abc!@#$"; byte[] key = EncodeDecodeUtils.decodeHex("<KEY>"); byte[] iv = EncodeDecodeUtils.decodeHex("f0021ea5a06d5a7bade961afe47e9ad9"); byte[] data = CryptoUtils.aesEncrypt(str.getBytes(), key, iv); String str2 = EncodeDecodeUtils.encodeBase64(data); log.info("加密 {}", str2); log.info("解密 {}", CryptoUtils.aesDecrypt(data, key, iv)); } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/authentication/filter/UserLoginFilter.java<|end_filename|> package org.clever.security.authentication.filter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.math.NumberUtils; import org.clever.security.Constant; import org.clever.security.LoginModel; import org.clever.security.authentication.CollectLoginToken; import org.clever.security.config.SecurityConfig; import org.clever.security.config.model.LoginConfig; import org.clever.security.dto.response.JwtLoginRes; import org.clever.security.dto.response.LoginRes; import org.clever.security.dto.response.UserRes; import org.clever.security.exception.BadCaptchaException; import org.clever.security.exception.BadLoginTypeException; import org.clever.security.handler.UserLoginFailureHandler; import org.clever.security.handler.UserLoginSuccessHandler; import org.clever.security.model.CaptchaInfo; import org.clever.security.repository.CaptchaInfoRepository; import org.clever.security.repository.LoginFailCountRepository; import org.clever.security.repository.RedisJwtRepository; import org.clever.security.token.JwtAccessToken; import org.clever.security.token.login.BaseLoginToken; import org.clever.security.utils.AuthenticationUtils; import org.clever.security.utils.HttpResponseUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.authentication.AuthenticationTrustResolver; import org.springframework.security.authentication.AuthenticationTrustResolverImpl; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * 收集用户登录信息 * 作者: lzw<br/> * 创建时间:2018-03-15 12:48 <br/> */ @Component @Slf4j public class UserLoginFilter extends AbstractAuthenticationProcessingFilter { @Autowired private SecurityConfig securityConfig; @Autowired private UserLoginSuccessHandler userLoginSuccessHandler; @Autowired private UserLoginFailureHandler userLoginFailureHandler; @Autowired private RedisJwtRepository redisJwtRepository; @Autowired private CaptchaInfoRepository captchaInfoRepository; @Autowired private LoginFailCountRepository loginFailCountRepository; @Autowired private List<CollectLoginToken> collectLoginTokenList; private AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl(); private boolean postOnly = true; /** * 登录是否需要验证码 */ private Boolean needCaptcha = true; /** * 登录失败多少次才需要验证码(小于等于0,总是需要验证码) */ private Integer needCaptchaByLoginFailCount = 3; public UserLoginFilter(SecurityConfig securityConfig) { super(new AntPathRequestMatcher(securityConfig.getLogin().getLoginUrl())); } @Autowired @Override public void setAuthenticationManager(AuthenticationManager authenticationManager) { super.setAuthenticationManager(authenticationManager); } @PostConstruct public void init() { log.info("### UserLoginFilter 初始化配置"); this.setBeanName(this.toString()); // 初始化配置 LoginConfig login = securityConfig.getLogin(); if (login != null) { if (login.getPostOnly() != null) { postOnly = login.getPostOnly(); } if (login.getNeedCaptcha() != null) { needCaptcha = login.getNeedCaptcha(); } if (login.getNeedCaptchaByLoginFailCount() != null) { needCaptchaByLoginFailCount = login.getNeedCaptchaByLoginFailCount(); } } if (collectLoginTokenList == null || this.collectLoginTokenList.size() <= 0) { throw new RuntimeException("未注入收集用户登录信息组件"); } this.setAuthenticationSuccessHandler(userLoginSuccessHandler); this.setAuthenticationFailureHandler(userLoginFailureHandler); } /** * 收集认证信息 */ @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException { if (postOnly && !request.getMethod().equalsIgnoreCase("POST")) { throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod()); } // 需要防止用户重复登录 Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication != null && authentication.isAuthenticated() && !authenticationTrustResolver.isRememberMe(authentication)) { // 已经登录成功了 UserRes userRes = AuthenticationUtils.getUserRes(authentication); Object resData; if (LoginModel.jwt.equals(securityConfig.getLoginModel())) { // JWT JwtAccessToken jwtAccessToken = redisJwtRepository.getJwtToken(request); resData = new JwtLoginRes(true, "您已经登录成功了无须多次登录", userRes, jwtAccessToken.getToken(), jwtAccessToken.getRefreshToken()); } else { // Session resData = new LoginRes(true, "您已经登录成功了无须多次登录", userRes); } HttpResponseUtils.sendJsonBy200(response, resData); log.info("### 当前用户已登录 [{}]", authentication.toString()); return null; } // 获取用户登录信息 boolean isSubmitBody = securityConfig.getLogin().getJsonDataSubmit(); BaseLoginToken loginToken = null; for (CollectLoginToken collectLoginToken : collectLoginTokenList) { if (collectLoginToken.supports(request, isSubmitBody)) { loginToken = collectLoginToken.attemptAuthentication(request, isSubmitBody); break; } } if (loginToken == null) { throw new BadLoginTypeException("不支持的登录请求"); } // 设置用户 "details" 属性(设置请求IP和SessionID) -- 需要提前创建Session if (LoginModel.session.equals(securityConfig.getLoginModel())) { request.getSession(); } loginToken.setDetails(authenticationDetailsSource.buildDetails(request)); log.info("### 用户登录开始,构建LoginToken [{}]", loginToken.toString()); request.setAttribute(Constant.Login_Username_Request_Key, loginToken.getName()); // 读取验证码 - 验证 if (needCaptcha) { long loginFailCount = 0; CaptchaInfo captchaInfo; if (LoginModel.jwt.equals(securityConfig.getLoginModel())) { // JWT loginFailCount = loginFailCountRepository.getLoginFailCount(loginToken.getName()); if (loginFailCount >= needCaptchaByLoginFailCount) { captchaInfo = captchaInfoRepository.getCaptchaInfo(loginToken.getCaptcha(), loginToken.getCaptchaDigest()); verifyCaptchaInfo(captchaInfo, loginToken.getCaptcha()); captchaInfoRepository.deleteCaptchaInfo(loginToken.getCaptcha(), loginToken.getCaptchaDigest()); } } else { // Session Object loginFailCountStr = request.getSession().getAttribute(Constant.Login_Fail_Count_Session_Key); if (loginFailCountStr != null) { loginFailCount = NumberUtils.toInt(loginFailCountStr.toString(), 0); } if (loginFailCount >= needCaptchaByLoginFailCount) { captchaInfo = (CaptchaInfo) request.getSession().getAttribute(Constant.Login_Captcha_Session_Key); verifyCaptchaInfo(captchaInfo, loginToken.getCaptcha()); request.getSession().removeAttribute(Constant.Login_Captcha_Session_Key); } } log.info("### 验证码校验通过"); } // 验证登录 return this.getAuthenticationManager().authenticate(loginToken); } /** * 校验验证码 */ private void verifyCaptchaInfo(CaptchaInfo captchaInfo, String captcha) { if (captchaInfo == null) { throw new BadCaptchaException("验证码不存在"); } if (captchaInfo.getEffectiveTime() > 0 && System.currentTimeMillis() - captchaInfo.getCreateTime() >= captchaInfo.getEffectiveTime()) { throw new BadCaptchaException("验证码已过期"); } if (!captchaInfo.getCode().equalsIgnoreCase(captcha)) { throw new BadCaptchaException("验证码不匹配"); } } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/handler/UserLogoutSuccessHandler.java<|end_filename|> package org.clever.security.handler; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.clever.security.config.SecurityConfig; import org.clever.security.config.model.LogoutConfig; import org.clever.security.dto.response.LogoutRes; import org.clever.security.dto.response.UserRes; import org.clever.security.utils.AuthenticationUtils; import org.clever.security.utils.HttpRequestUtils; import org.clever.security.utils.HttpResponseUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.RedirectStrategy; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 作者: lzw<br/> * 创建时间:2018-03-21 10:21 <br/> */ @Component @Slf4j public class UserLogoutSuccessHandler implements LogoutSuccessHandler { @SuppressWarnings("FieldCanBeLocal") private final String defaultRedirectUrl = "/index.html"; @Autowired private SecurityConfig securityConfig; private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); @Override public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { if (authentication == null) { log.info("### 登出无效(还未登录)"); } else { log.info("### 用户登出成功 [username={}]", authentication.getPrincipal().toString()); } LogoutConfig logout = securityConfig.getLogout(); if (logout.getLogoutSuccessNeedRedirect() != null && logout.getLogoutSuccessNeedRedirect()) { sendRedirect(request, response, logout.getLogoutSuccessRedirectPage()); return; } // 判断是否需要跳转到页面 if (HttpRequestUtils.isJsonResponse(request)) { sendJsonData(response, authentication); return; } sendRedirect(request, response, logout.getLogoutSuccessRedirectPage()); } /** * 页面跳转 (重定向) */ private void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException { if (StringUtils.isBlank(url)) { url = defaultRedirectUrl; } log.info("### 登出成功跳转Url(重定向) -> {}", url); if (!response.isCommitted()) { redirectStrategy.sendRedirect(request, response, url); } } /** * 直接返回Json数据 */ private void sendJsonData(HttpServletResponse response, Authentication authentication) { UserRes userRes = AuthenticationUtils.getUserRes(authentication); LogoutRes logoutRes = new LogoutRes(true, "登出成功", userRes); HttpResponseUtils.sendJsonBy200(response, logoutRes); log.info("### 登出成功不需要跳转 -> [{}]", logoutRes); } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/WebPermissionModelGetReq.java<|end_filename|> package org.clever.security.dto.request; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.request.BaseRequest; import org.hibernate.validator.constraints.Length; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; /** * 作者: lzw<br/> * 创建时间:2018-09-24 19:03 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class WebPermissionModelGetReq extends BaseRequest { @NotBlank @Length(max = 127) @ApiModelProperty("系统名称") private String sysName; @NotBlank @Length(max = 255) @ApiModelProperty("Controller Class") private String targetClass; @NotBlank @Length(max = 255) @ApiModelProperty("Controller Method") private String targetMethod; @NotNull @Length(max = 255) @ApiModelProperty("Controller Method Params") private String targetMethodParams; } <|start_filename|>clever-security-client/src/main/java/org/clever/security/client/ServiceSysClient.java<|end_filename|> package org.clever.security.client; import org.clever.security.config.CleverSecurityFeignConfiguration; import org.clever.security.dto.request.ServiceSysAddReq; import org.clever.security.entity.ServiceSys; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.*; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-10-23 10:23 <br/> */ @FeignClient( contextId = "org.clever.security.client.ServiceSysClient", name = "clever-security-server", path = "/api", configuration = CleverSecurityFeignConfiguration.class ) public interface ServiceSysClient { /** * 查询所有系统信息 */ @GetMapping("/service_sys") List<ServiceSys> allSysName(); /** * 注册系统 */ @PostMapping("/service_sys") ServiceSys registerSys(@RequestBody ServiceSysAddReq serviceSysAddReq); /** * 删除系统 */ @DeleteMapping("/service_sys/{sysName}") ServiceSys delServiceSys(@PathVariable("sysName") String sysName); } <|start_filename|>clever-security-server/src/main/java/org/clever/security/mapper/UserMapper.java<|end_filename|> package org.clever.security.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.metadata.IPage; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.clever.security.dto.request.UserQueryPageReq; import org.clever.security.entity.Permission; import org.clever.security.entity.Role; import org.clever.security.entity.ServiceSys; import org.clever.security.entity.User; import org.springframework.stereotype.Repository; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-09-17 9:08 <br/> */ @Repository @Mapper public interface UserMapper extends BaseMapper<User> { User getByUnique(@Param("unique") String unique); User getByUsername(@Param("username") String username); User getByTelephone(@Param("telephone") String telephone); List<Permission> findByUsername(@Param("username") String username, @Param("sysName") String sysName); int existsUserBySysName(@Param("username") String username, @Param("sysName") String sysName); List<User> findByPage(@Param("query") UserQueryPageReq query, IPage page); List<String> findSysNameByUsername(@Param("username") String username); List<ServiceSys> findSysByUsername(@Param("username") String username); int addUserSys(@Param("username") String username, @Param("sysName") String sysName); int delUserSys(@Param("username") String username, @Param("sysName") String sysName); int existsByUserName(@Param("username") String username); int existsByTelephone(@Param("telephone") String telephone); int existsByEmail(@Param("email") String email); int addRole(@Param("username") String username, @Param("roleName") String roleName); int delRole(@Param("username") String username, @Param("roleName") String roleName); List<Role> findRoleByUsername(@Param("username") String username); int existsUserRole(@Param("username") String username, @Param("roleName") String roleName); int delUserRole(@Param("username") String username); int delAllUserSys(@Param("username") String username); } <|start_filename|>clever-security-server/src/main/java/org/clever/security/config/BeanConfiguration.java<|end_filename|> package org.clever.security.config; import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor; import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor; import com.baomidou.mybatisplus.extension.plugins.SqlExplainInterceptor; import lombok.extern.slf4j.Slf4j; import org.clever.common.server.config.CustomPaginationInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import java.security.SecureRandom; /** * 作者: lzw<br/> * 创建时间:2017-12-04 10:37 <br/> */ @Configuration @Slf4j public class BeanConfiguration { /** * 密码处理 */ @Bean protected BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(10, new SecureRandom()); } // /** // * 使用 GenericJackson2JsonRedisSerializer 替换默认序列化 // */ // @Bean("redisTemplate") // public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { // // 自定义 ObjectMapper // ObjectMapper objectMapper = new ObjectMapper(); // objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); //// objectMapper.setDateFormat(); //// objectMapper.setDefaultMergeable() //// objectMapper.setDefaultPropertyInclusion() //// objectMapper.setDefaultSetterInfo() //// objectMapper.setDefaultVisibility() // // 查看Spring的实现 SecurityJackson2Modules // List<Module> modules = SecurityJackson2Modules.getModules(getClass().getClassLoader()); // objectMapper.findAndRegisterModules(); // objectMapper.registerModules(modules); // objectMapper.registerModule(new CleverSecurityJackson2Module()); // // 创建 RedisTemplate // RedisTemplate<String, Object> template = new RedisTemplate<>(); // template.setConnectionFactory(redisConnectionFactory); // // 设置value的序列化规则和 key的序列化规则 // template.setKeySerializer(new StringRedisSerializer()); // template.setValueSerializer(new GenericJackson2JsonRedisSerializer(objectMapper)); // template.afterPropertiesSet(); // return template; // } /** * 分页插件 */ @SuppressWarnings("UnnecessaryLocalVariable") @Bean public CustomPaginationInterceptor paginationInterceptor() { CustomPaginationInterceptor paginationInterceptor = new CustomPaginationInterceptor(); // paginationInterceptor.setSqlParser() // paginationInterceptor.setDialectClazz() // paginationInterceptor.setOverflow() // paginationInterceptor.setProperties(); return paginationInterceptor; } /** * 乐观锁插件<br /> * 取出记录时,获取当前version <br /> * 更新时,带上这个version <br /> * 执行更新时, set version = yourVersion+1 where version = yourVersion <br /> * 如果version不对,就更新失败 <br /> */ @Bean public OptimisticLockerInterceptor optimisticLockerInterceptor() { return new OptimisticLockerInterceptor(); } // /** // * 逻辑删除<br /> // */ // @Bean // public ISqlInjector sqlInjector() { // return new LogicSqlInjector(); // } /** * SQL执行效率插件 */ @SuppressWarnings("UnnecessaryLocalVariable") @Bean @Profile({"dev", "test"}) public PerformanceInterceptor performanceInterceptor() { PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor(); // performanceInterceptor.setFormat(true); // performanceInterceptor.setMaxTime(); // performanceInterceptor.setWriteInLog(); return performanceInterceptor; } /** * 执行分析插件<br /> * SQL 执行分析拦截器【 目前只支持 MYSQL-5.6.3 以上版本 】 * 作用是分析 处理 DELETE UPDATE 语句 * 防止小白或者恶意 delete update 全表操作! */ @SuppressWarnings("UnnecessaryLocalVariable") @Bean @Profile({"dev", "test"}) public SqlExplainInterceptor sqlExplainInterceptor() { SqlExplainInterceptor sqlExplainInterceptor = new SqlExplainInterceptor(); // sqlExplainInterceptor.stopProceed return sqlExplainInterceptor; } } <|start_filename|>clever-security-server/src/main/java/org/clever/security/service/local/RememberMeTokenServiceProxy.java<|end_filename|> package org.clever.security.service.local; import lombok.extern.slf4j.Slf4j; import org.clever.common.utils.mapper.BeanMapper; import org.clever.security.client.RememberMeTokenClient; import org.clever.security.dto.request.RememberMeTokenAddReq; import org.clever.security.dto.request.RememberMeTokenUpdateReq; import org.clever.security.entity.RememberMeToken; import org.clever.security.service.RememberMeTokenService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.Map; /** * 参考 RememberMeTokenController * <p> * 作者: lzw<br/> * 创建时间:2018-11-11 19:21 <br/> */ @Component @Slf4j public class RememberMeTokenServiceProxy implements RememberMeTokenClient { @Autowired private RememberMeTokenService rememberMeTokenService; @Override public RememberMeToken addRememberMeToken(RememberMeTokenAddReq req) { RememberMeToken rememberMeToken = BeanMapper.mapper(req, RememberMeToken.class); return rememberMeTokenService.addRememberMeToken(rememberMeToken); } @Override public RememberMeToken getRememberMeToken(String series) { return rememberMeTokenService.getRememberMeToken(series); } @Override public Map<String, Object> delRememberMeToken(String username) { Map<String, Object> map = new HashMap<>(); Integer delCount = rememberMeTokenService.delRememberMeToken(username); map.put("delCount", delCount); return map; } @Override public RememberMeToken updateRememberMeToken(String series, RememberMeTokenUpdateReq req) { return rememberMeTokenService.updateRememberMeToken(series, req.getToken(), req.getLastUsed()); } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/authentication/DefaultPreAuthenticationChecks.java<|end_filename|> package org.clever.security.authentication; import lombok.extern.slf4j.Slf4j; import org.clever.security.client.UserClient; import org.clever.security.config.SecurityConfig; import org.clever.security.exception.CanNotLoginSysException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AccountExpiredException; import org.springframework.security.authentication.DisabledException; import org.springframework.security.authentication.LockedException; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsChecker; import org.springframework.stereotype.Component; /** * 验证帐号信息之前的校验 * <p> * 作者: lzw<br/> * 创建时间:2018-09-19 16:32 <br/> */ @Component("DefaultPreAuthenticationChecks") @Slf4j public class DefaultPreAuthenticationChecks implements UserDetailsChecker { @Autowired private SecurityConfig securityConfig; @Autowired private UserClient userClient; @Override public void check(UserDetails user) { if (!user.isAccountNonLocked()) { log.info("帐号已锁定 [username={}]", user.getUsername()); throw new LockedException("帐号已锁定"); } if (!user.isEnabled()) { log.info("帐号已禁用 [username={}]", user.getUsername()); throw new DisabledException("帐号已禁用"); } if (!user.isAccountNonExpired()) { log.info("帐号已过期 [username={}]", user.getUsername()); throw new AccountExpiredException("帐号已过期"); } // 校验用户是否有权登录当前系统 Boolean canLogin = userClient.canLogin(user.getUsername(), securityConfig.getSysName()); if (!canLogin) { throw new CanNotLoginSysException("您无权登录当前系统,请联系管理员授权"); } } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/jackson2/SecurityContextTokenMixin.java<|end_filename|> package org.clever.security.jackson2; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import org.clever.security.model.LoginUserDetails; import org.clever.security.token.login.BaseLoginToken; /** * 作者: lzw<br/> * 创建时间:2018-09-22 21:14 <br/> */ //@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_ARRAY) @JsonAutoDetect @JsonIgnoreProperties(ignoreUnknown = true) class SecurityContextTokenMixin { @JsonCreator public SecurityContextTokenMixin(@JsonProperty("credentials") BaseLoginToken loginToken, @JsonProperty("principal") LoginUserDetails userDetails) { } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/config/model/LogoutConfig.java<|end_filename|> package org.clever.security.config.model; import lombok.Data; /** * 用户登出配置 * 作者: lzw<br/> * 创建时间:2019-04-25 19:02 <br/> */ @Data public class LogoutConfig { /** * 登出请求URL */ private String logoutUrl = "/logout"; /** * 登出成功 - 是否需要跳转 */ private Boolean logoutSuccessNeedRedirect = false; /** * 登出成功默认跳转的页面 */ private String logoutSuccessRedirectPage = "/index.html"; } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/exception/CanNotLoginSysException.java<|end_filename|> package org.clever.security.exception; import org.springframework.security.core.AuthenticationException; /** * 无权登录系统 * <p> * 作者: lzw<br/> * 创建时间:2018-10-01 22:01 <br/> */ public class CanNotLoginSysException extends AuthenticationException { public CanNotLoginSysException(String msg) { super(msg); } } <|start_filename|>clever-security-server/src/main/java/org/clever/security/controller/UserController.java<|end_filename|> package org.clever.security.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.clever.common.server.controller.BaseController; import org.clever.security.dto.request.UserAuthenticationReq; import org.clever.security.dto.response.UserAuthenticationRes; import org.clever.security.entity.Permission; import org.clever.security.entity.User; import org.clever.security.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-09-17 9:21 <br/> */ @Api("用户信息") @RestController @RequestMapping("/api") public class UserController extends BaseController { @Autowired private UserService userService; @ApiOperation("获取用户(登录名、手机、邮箱)") @GetMapping("/user/{unique}") public User getUser(@PathVariable("unique") String unique) { return userService.getUser(unique); } @ApiOperation("获取某个用户在某个系统下的所有权限") @GetMapping("/user/{username}/{sysName}/permission") public List<Permission> findAllPermission(@PathVariable("username") String username, @PathVariable("sysName") String sysName) { return userService.findAllPermission(username, sysName); } @ApiOperation("用户是否有权登录某个系统") @GetMapping("/user/{username}/{sysName}") public Boolean canLogin(@PathVariable("username") String username, @PathVariable("sysName") String sysName) { return userService.canLogin(username, sysName); } @ApiOperation("用户登录认证") @PostMapping("/user/authentication") public UserAuthenticationRes authentication(@RequestBody @Validated UserAuthenticationReq req) { return userService.authenticationAndRes(req); } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/config/ApplicationSecurityBean.java<|end_filename|> package org.clever.security.config; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.clever.security.Constant; import org.clever.security.authentication.CollectLoginToken; import org.clever.security.authorization.RequestAccessDecisionVoter; import org.clever.security.config.model.LoginConfig; import org.clever.security.config.model.RememberMeConfig; import org.clever.security.jackson2.CleverSecurityJackson2Module; import org.clever.security.rememberme.RememberMeRepository; import org.clever.security.rememberme.RememberMeServices; import org.clever.security.rememberme.RememberMeUserDetailsChecker; import org.clever.security.service.GlobalUserDetailsService; import org.clever.security.strategy.SessionExpiredStrategy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import org.springframework.security.access.AccessDecisionManager; import org.springframework.security.access.AccessDecisionVoter; import org.springframework.security.access.vote.AffirmativeBased; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.core.session.SessionRegistry; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.jackson2.SecurityJackson2Modules; import org.springframework.security.web.authentication.NullRememberMeServices; import org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy; import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy; import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy; import org.springframework.security.web.session.HttpSessionEventPublisher; import org.springframework.security.web.session.SessionInformationExpiredStrategy; import org.springframework.session.data.redis.RedisOperationsSessionRepository; import org.springframework.session.security.SpringSessionBackedSessionRegistry; import java.security.SecureRandom; import java.util.Collections; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-09-17 9:49 <br/> */ @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) @Configuration @Slf4j public class ApplicationSecurityBean { @Autowired private SecurityConfig securityConfig; /** * 密码处理 */ @ConditionalOnMissingBean(BCryptPasswordEncoder.class) @Bean protected BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(10, new SecureRandom()); } /** * 使用 GenericJackson2JsonRedisSerializer 替换默认序列化 */ // @ConditionalOnMissingBean(RedisTemplate.class) @Bean("redisTemplate") public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { // 自定义 ObjectMapper ObjectMapper objectMapper = newObjectMapper(); // 创建 RedisTemplate RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); // 设置value的序列化规则和 key的序列化规则 template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new GenericJackson2JsonRedisSerializer(objectMapper)); template.afterPropertiesSet(); return template; } /** * 授权校验 <br/> * <pre> * {@code * AffirmativeBased (有一个允许访问就有权访问) * 1. 只要有AccessDecisionVoter的投票为ACCESS_GRANTED则同意用户进行访问 * 2. 如果全部弃权也表示通过 * 3. 如果没有一个人投赞成票,但是有人投反对票,则将抛出AccessDeniedException * ConsensusBased (大多数允许访问才有权访问) * 1. 如果赞成票多于反对票则表示通过 * 2. 反过来,如果反对票多于赞成票则将抛出AccessDeniedException * 3. 如果赞成票与反对票相同且不等于0,并且属性allowIfEqualGrantedDeniedDecisions的值为true,则表示通过,否则将抛出异常AccessDeniedException。参数allowIfEqualGrantedDeniedDecisions的值默认为true * 4. 如果所有的AccessDecisionVoter都弃权了,则将视参数allowIfAllAbstainDecisions的值而定,如果该值为true则表示通过,否则将抛出异常AccessDeniedException。参数allowIfAllAbstainDecisions的值默认为false * UnanimousBased * 逻辑与另外两种实现有点不一样, * 另外两种会一次性把受保护对象的配置属性全部传递给AccessDecisionVoter进行投票, * 而UnanimousBased会一次只传递一个ConfigAttribute给AccessDecisionVoter进行投票。 * 这也就意味着如果我们的AccessDecisionVoter的逻辑是只要传递进来的ConfigAttribute中有一个能够匹配则投赞成票, * 但是放到UnanimousBased中其投票结果就不一定是赞成了 * 1. 如果受保护对象配置的某一个ConfigAttribute被任意的AccessDecisionVoter反对了,则将抛出AccessDeniedException * 2. 如果没有反对票,但是有赞成票,则表示通过 * 3. 如果全部弃权了,则将视参数allowIfAllAbstainDecisions的值而定,true则通过,false则抛出AccessDeniedException * } * </pre> */ @Bean protected AccessDecisionManager accessDecisionManager(@Autowired RequestAccessDecisionVoter requestAccessDecisionVoter) { // WebExpressionVoter RoleVoter AuthenticatedVoter List<AccessDecisionVoter<?>> decisionVoters = Collections.singletonList(requestAccessDecisionVoter); // AffirmativeBased accessDecisionManager = new AffirmativeBased(decisionVoters); // accessDecisionManager. // TODO 支持注解权限校验 return new AffirmativeBased(decisionVoters); } /** * 登录并发处理(使用session登录时才需要) */ @ConditionalOnProperty(prefix = Constant.ConfigPrefix, name = "login-model", havingValue = "session") @Bean protected SessionAuthenticationStrategy sessionAuthenticationStrategy(@Autowired SessionRegistry sessionRegistry) { LoginConfig login = securityConfig.getLogin(); if (login.getConcurrentLoginCount() == null) { return new NullAuthenticatedSessionStrategy(); } int concurrentLoginCount = login.getConcurrentLoginCount() <= 0 ? -1 : login.getConcurrentLoginCount(); boolean notAllowAfterLogin = false; if (login.getNotAllowAfterLogin() != null) { notAllowAfterLogin = login.getNotAllowAfterLogin(); } ConcurrentSessionControlAuthenticationStrategy sessionAuthenticationStrategy = new ConcurrentSessionControlAuthenticationStrategy(sessionRegistry); sessionAuthenticationStrategy.setMaximumSessions(concurrentLoginCount); sessionAuthenticationStrategy.setExceptionIfMaximumExceeded(notAllowAfterLogin); // sessionAuthenticationStrategy.setMessageSource(); return sessionAuthenticationStrategy; } /** * Session过期处理(使用session登录时才需要) */ @ConditionalOnProperty(prefix = Constant.ConfigPrefix, name = "login-model", havingValue = "session") @Bean protected SessionInformationExpiredStrategy sessionInformationExpiredStrategy() { SessionExpiredStrategy sessionExpiredStrategy = new SessionExpiredStrategy(); sessionExpiredStrategy.setNeedRedirect(StringUtils.isNotBlank(securityConfig.getSessionExpiredRedirectUrl())); sessionExpiredStrategy.setDestinationUrl(securityConfig.getSessionExpiredRedirectUrl()); return sessionExpiredStrategy; } /** * 实现的记住我的功能,不使用SpringSession提供的SpringSessionRememberMeServices(使用session登录时才需要) */ @ConditionalOnProperty(prefix = Constant.ConfigPrefix, name = "login-model", havingValue = "session") @Bean protected org.springframework.security.web.authentication.RememberMeServices rememberMeServices( @Autowired RememberMeUserDetailsChecker rememberMeUserDetailsChecker, @Autowired GlobalUserDetailsService userDetailsService, @Autowired RememberMeRepository rememberMeRepository) { RememberMeConfig rememberMe = securityConfig.getRememberMe(); if (rememberMe == null || rememberMe.getEnable() == null || !rememberMe.getEnable()) { return new NullRememberMeServices(); } RememberMeServices rememberMeServices = new RememberMeServices( RememberMeServices.REMEMBER_ME_KEY, userDetailsService, rememberMeRepository, rememberMeUserDetailsChecker); rememberMeServices.setAlwaysRemember(rememberMe.getAlwaysRemember()); rememberMeServices.setParameter(CollectLoginToken.REMEMBER_ME_PARAM); rememberMeServices.setTokenValiditySeconds((int) rememberMe.getValidity().getSeconds()); rememberMeServices.setCookieName(RememberMeServices.REMEMBER_ME_COOKIE_NAME); // rememberMeServices.setTokenLength(); // rememberMeServices.setSeriesLength(); // rememberMeServices.setUserDetailsChecker(); // rememberMeServices.setUseSecureCookie(); // rememberMeServices.setCookieDomain(); return rememberMeServices; } /** * 替换Spring Session Redis默认的序列化方式 JdkSerializationRedisSerializer<br /> * * @see org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration#setDefaultRedisSerializer */ @ConditionalOnProperty(prefix = Constant.ConfigPrefix, name = "login-model", havingValue = "session") @Bean("springSessionDefaultRedisSerializer") protected RedisSerializer<Object> springSessionDefaultRedisSerializer() { //解决查询缓存转换异常的问题 ObjectMapper objectMapper = newObjectMapper(); return new GenericJackson2JsonRedisSerializer(objectMapper); } /** * 监听 HttpSession 事件 */ @ConditionalOnProperty(prefix = Constant.ConfigPrefix, name = "login-model", havingValue = "session") @Bean public HttpSessionEventPublisher httpSessionEventPublisher() { return new HttpSessionEventPublisher(); } /** * 集成Spring Session所需的Bean */ @ConditionalOnProperty(prefix = Constant.ConfigPrefix, name = "login-model", havingValue = "session") @Bean protected SpringSessionBackedSessionRegistry sessionRegistry(@Autowired RedisOperationsSessionRepository sessionRepository) { return new SpringSessionBackedSessionRegistry<>(sessionRepository); } private ObjectMapper newObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); // objectMapper.setDateFormat(); // objectMapper.setDefaultMergeable() // objectMapper.setDefaultPropertyInclusion() // objectMapper.setDefaultSetterInfo() // objectMapper.setDefaultVisibility() // 查看Spring的实现 SecurityJackson2Modules List<Module> modules = SecurityJackson2Modules.getModules(getClass().getClassLoader()); objectMapper.findAndRegisterModules(); objectMapper.registerModules(modules); objectMapper.registerModule(new CleverSecurityJackson2Module()); return objectMapper; } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/embed/controller/CaptchaController.java<|end_filename|> package org.clever.security.embed.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.clever.common.utils.codec.DigestUtils; import org.clever.common.utils.codec.EncodeDecodeUtils; import org.clever.common.utils.imgvalidate.ImageValidateCageUtils; import org.clever.common.utils.imgvalidate.ValidateCodeSourceUtils; import org.clever.common.utils.reflection.ReflectionsUtils; import org.clever.security.Constant; import org.clever.security.LoginModel; import org.clever.security.config.SecurityConfig; import org.clever.security.model.CaptchaInfo; import org.clever.security.repository.CaptchaInfoRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 作者: lzw<br/> * 创建时间:2018-09-19 21:21 <br/> */ @Api("验证码") @RestController @Slf4j public class CaptchaController { @Autowired private SecurityConfig securityConfig; @Autowired private CaptchaInfoRepository captchaInfoRepository; @ApiOperation("获取登录验证码(请求头包含文件SHA1签名)") @GetMapping("/login/captcha.png") public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException { String code = ValidateCodeSourceUtils.getRandString(4); byte[] image = ImageValidateCageUtils.createImage(code); // 3分钟有效 Long captchaEffectiveTime = 180000L; String imageDigestHeader = "ImageDigest"; if (securityConfig.getLogin() != null && securityConfig.getLogin().getCaptchaEffectiveTime() != null) { captchaEffectiveTime = securityConfig.getLogin().getCaptchaEffectiveTime().toMillis(); } CaptchaInfo captchaInfo; setContentTypeNoCharset(response, "image/png"); if (LoginModel.jwt.equals(securityConfig.getLoginModel())) { // JWT Token String imageDigest = EncodeDecodeUtils.encodeHex(DigestUtils.sha1(image)); captchaInfo = new CaptchaInfo(code, captchaEffectiveTime, imageDigest); // 验证码放在Redis captchaInfoRepository.saveCaptchaInfo(captchaInfo); // 写入图片数据 response.setHeader(imageDigestHeader, imageDigest); log.info("### 获取验证码[{}]", captchaInfo); } else { // Session captchaInfo = new CaptchaInfo(code, captchaEffectiveTime); request.getSession().setAttribute(Constant.Login_Captcha_Session_Key, captchaInfo); log.info("### 客户端[SessionID={}] 获取验证码[{}]", request.getSession().getId(), captchaInfo); } response.getOutputStream().write(image); } @SuppressWarnings("SameParameterValue") private static void setContentTypeNoCharset(HttpServletResponse response, String contentType) { boolean flag = false; Object object = response; while (true) { try { object = ReflectionsUtils.getFieldValue(object, "response"); } catch (Throwable e) { break; } if (object instanceof org.apache.catalina.connector.Response) { break; } } if (object instanceof org.apache.catalina.connector.Response) { org.apache.catalina.connector.Response connectorResponse = (org.apache.catalina.connector.Response) object; object = ReflectionsUtils.getFieldValue(connectorResponse, "coyoteResponse"); if (object instanceof org.apache.coyote.Response) { org.apache.coyote.Response coyoteResponse = (org.apache.coyote.Response) object; coyoteResponse.setContentTypeNoCharset(contentType); ReflectionsUtils.setFieldValue(coyoteResponse, "charset", null); flag = true; } } if (!flag) { response.setContentType(contentType); } } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/PermissionUpdateReq.java<|end_filename|> package org.clever.security.dto.request; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.request.BaseRequest; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.Range; /** * 作者: lzw<br/> * 创建时间:2018-10-03 19:05 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class PermissionUpdateReq extends BaseRequest { @ApiModelProperty("权限标题") @Length(max = 255) private String title; @ApiModelProperty("唯一权限标识字符串") @Length(min = 6, max = 255) private String permissionStr; @ApiModelProperty("权限类型,1:web资源权限, 2:菜单权限,3:ui权限,4:自定义") @Range(min = 1, max = 4) private Integer resourcesType; @ApiModelProperty("权限说明") @Length(max = 127) private String description; @ApiModelProperty("需要授权才允许访问(1:需要;2:不需要)") @Range(min = 1, max = 2) private Integer needAuthorization; } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/UserBindRoleReq.java<|end_filename|> package org.clever.security.dto.request; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.request.BaseRequest; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-10-03 21:53 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class UserBindRoleReq extends BaseRequest { @ApiModelProperty("用户名集合") @Size(min = 1, max = 100) @NotNull private List<String> usernameList; @ApiModelProperty("角色集合") @NotNull private List<String> roleNameList; } <|start_filename|>clever-security-server/src/main/java/org/clever/security/mapper/ServiceSysMapper.java<|end_filename|> package org.clever.security.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.clever.security.entity.ServiceSys; import org.springframework.stereotype.Repository; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-10-22 15:23 <br/> */ @Repository @Mapper public interface ServiceSysMapper extends BaseMapper<ServiceSys> { int existsSysName(@Param("sysName") String sysName); int existsRedisNameSpace(@Param("redisNameSpace") String redisNameSpace); ServiceSys getByUnique(@Param("sysName") String sysName, @Param("redisNameSpace") String redisNameSpace); ServiceSys getBySysName(@Param("sysName") String sysName); List<String> allSysName(); } <|start_filename|>Dockerfile<|end_filename|> FROM 172.18.1.1:15000/java:8u111-jre-alpine as dev ADD clever-security-server/target/clever-security-server-*-SNAPSHOT.jar app.jar ENTRYPOINT ["java", "-jar", "app.jar", "--server.port=9066", "--server.address=0.0.0.0"] EXPOSE 9066 FROM 172.18.1.1:15000/java:8u111-jre-alpine as prod ADD clever-security-server/target/clever-security-server-*-SNAPSHOT.jar app.jar ENTRYPOINT ["java", "-jar", "app.jar", "--server.port=9066", "--server.address=0.0.0.0"] EXPOSE 9066 <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/PermissionAddReq.java<|end_filename|> package org.clever.security.dto.request; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.request.BaseRequest; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.Range; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; /** * 作者: lzw<br/> * 创建时间:2018-10-03 16:29 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class PermissionAddReq extends BaseRequest { @ApiModelProperty("系统(或服务)名称") @NotBlank @Length(max = 127) private String sysName; @ApiModelProperty("权限标题") @NotBlank @Length(max = 255) private String title; @ApiModelProperty("唯一权限标识字符串") @Length(min = 6, max = 255) private String permissionStr; @ApiModelProperty("权限类型,1:web资源权限, 2:菜单权限,3:ui权限,4:自定义") @NotNull @Range(min = 2, max = 4) private Integer resourcesType; @ApiModelProperty("权限说明") @Length(max = 127) private String description; } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/rememberme/RememberMeServices.java<|end_filename|> package org.clever.security.rememberme; import lombok.extern.slf4j.Slf4j; import org.clever.security.Constant; import org.clever.security.model.LoginUserDetails; import org.clever.security.token.SecurityContextToken; import org.clever.security.token.login.RememberMeToken; import org.json.JSONObject; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.authentication.RememberMeAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsChecker; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices; import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository; import javax.servlet.http.HttpServletRequest; /** * "记住我"功能实现 * 作者: lzw<br/> * 创建时间:2018-09-20 20:23 <br/> */ @Slf4j public class RememberMeServices extends PersistentTokenBasedRememberMeServices { public static final String REMEMBER_ME_KEY = "remember-me-key"; public static final String REMEMBER_ME_COOKIE_NAME = "remember-me"; public RememberMeServices( String key, UserDetailsService userDetailsService, PersistentTokenRepository tokenRepository, UserDetailsChecker userDetailsChecker) { super(key, userDetailsService, tokenRepository); this.setUserDetailsChecker(userDetailsChecker); } /** * 判断是否需要"记住我"的功能 */ @Override protected boolean rememberMeRequested(HttpServletRequest request, String parameter) { String rememberMe = request.getParameter(parameter); if (rememberMe == null) { Object json = request.getAttribute(Constant.Login_Data_Body_Request_Key); if (json != null) { JSONObject object = new JSONObject(json.toString()); rememberMe = object.optString(parameter); } } if (rememberMe != null) { if (rememberMe.equalsIgnoreCase("true") || rememberMe.equalsIgnoreCase("on") || rememberMe.equalsIgnoreCase("yes") || rememberMe.equals("1")) { return true; } } if (log.isDebugEnabled()) { log.debug("Did not send remember-me cookie (principal did not set " + "parameter '" + parameter + "')"); } return false; } /** * 通过RememberMe登录创建LoginToken而非RememberMeAuthenticationToken,以免遇到403时跳转到登录页面<br/> * 不合理应该修改UserLoginEntryPoint.java */ @Override protected Authentication createSuccessfulAuthentication(HttpServletRequest request, UserDetails user) { AbstractAuthenticationToken authentication; if (user instanceof LoginUserDetails) { LoginUserDetails loginUserDetails = (LoginUserDetails) user; RememberMeToken rememberMeToken = new RememberMeToken(); rememberMeToken.setUsername(loginUserDetails.getUsername()); authentication = new SecurityContextToken(rememberMeToken, loginUserDetails); } else { authentication = new RememberMeAuthenticationToken( this.getKey(), user, user.getAuthorities()); } // 设置用户 "details" 属性(设置请求IP和SessionID) -- 需要提前创建Session request.getSession(); authentication.setDetails(this.getAuthenticationDetailsSource().buildDetails(request)); return authentication; } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/ForcedOfflineRes.java<|end_filename|> package org.clever.security.dto.response; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.response.BaseResponse; /** * 作者: lzw<br/> * 创建时间:2018-11-12 16:21 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class ForcedOfflineRes extends BaseResponse { @ApiModelProperty("删除Session数") private int count = 0; @ApiModelProperty("用户名") private String sysName; @ApiModelProperty("系统名") private String username; } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/strategy/SessionExpiredStrategy.java<|end_filename|> package org.clever.security.strategy; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.clever.common.model.response.ErrorResponse; import org.clever.common.utils.mapper.JacksonMapper; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.RedirectStrategy; import org.springframework.security.web.session.SessionInformationExpiredEvent; import org.springframework.security.web.session.SessionInformationExpiredStrategy; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Date; /** * Session 过期时的处理 * 作者: lzw<br/> * 创建时间:2018-09-20 15:00 <br/> */ @Data @Slf4j public class SessionExpiredStrategy implements SessionInformationExpiredStrategy { private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); /** * 需要跳转 */ private Boolean needRedirect = false; /** * 跳转Url */ private String destinationUrl = "/login.html"; @Override public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException { HttpServletRequest request = event.getRequest(); HttpServletResponse response = event.getResponse(); if (needRedirect) { redirectStrategy.sendRedirect(request, response, destinationUrl); return; } if (!response.isCommitted()) { ErrorResponse errorResponse = new ErrorResponse(); errorResponse.setPath(request.getPathInfo()); errorResponse.setTimestamp(new Date()); errorResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); errorResponse.setError("当前登录已过期(可能是因为同一用户尝试多次并发登录)"); errorResponse.setMessage("当前登录已过期(可能是因为同一用户尝试多次并发登录)"); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json;charset=utf-8"); response.getWriter().print(JacksonMapper.nonEmptyMapper().toJson(errorResponse)); } } } <|start_filename|>clever-security-server/src/main/java/org/clever/security/mapper/RememberMeTokenMapper.java<|end_filename|> package org.clever.security.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.clever.security.entity.RememberMeToken; import org.springframework.stereotype.Repository; import java.util.Date; /** * “记住我”功能的token(RememberMeToken)表数据库访问层 * * @author lizw * @since 2018-09-21 20:10:31 */ @Repository @Mapper public interface RememberMeTokenMapper extends BaseMapper<RememberMeToken> { int updateBySeries(@Param("series") String series, @Param("tokenValue") String tokenValue, @Param("lastUsed") Date lastUsed); RememberMeToken getBySeries(@Param("series") String series); int deleteByUsername(@Param("username") String username); int deleteBySysNameAndUsername(@Param("sysName") String sysName, @Param("username") String username); } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/service/JwtTokenService.java<|end_filename|> package org.clever.security.service; import io.jsonwebtoken.*; import io.jsonwebtoken.impl.DefaultClaims; import io.jsonwebtoken.security.Keys; import io.jsonwebtoken.security.SignatureException; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.clever.common.exception.BusinessException; import org.clever.common.utils.DateTimeUtils; import org.clever.common.utils.IDCreateUtils; import org.clever.common.utils.SnowFlake; import org.clever.common.utils.codec.EncodeDecodeUtils; import org.clever.common.utils.mapper.JacksonMapper; import org.clever.security.config.SecurityConfig; import org.clever.security.config.model.TokenConfig; import org.clever.security.token.JwtAccessToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.stereotype.Component; import java.security.Key; import java.util.Date; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; /** * 作者: lzw<br/> * 创建时间:2018-11-16 16:45 <br/> */ @Component @Slf4j public class JwtTokenService { private static final String PermissionKey = "permissions"; private static final String RoleKey = "roles"; private static final String SecretKeySuffix = "0123456789012345678901234567890123456789012345678901234567890123"; /** * 签名密钥 */ private final String secretKey; /** * Token有效时间(默认) */ private final long tokenValidityInMilliseconds; /** * Token记住我有效时间(记住我) */ private final long tokenValidityInMillisecondsForRememberMe; /** * 设置密钥过期时间 (格式 HH:mm:ss) */ private final String hoursInDay; /** * JWT Token配置 */ private final TokenConfig tokenConfig; protected JwtTokenService(SecurityConfig securityConfig) { tokenConfig = securityConfig.getTokenConfig(); if (tokenConfig == null) { throw new BusinessException("未配置TokenConfig"); } this.secretKey = tokenConfig.getSecretKey() + SecretKeySuffix; this.tokenValidityInMilliseconds = tokenConfig.getTokenValidity().toMillis(); this.tokenValidityInMillisecondsForRememberMe = tokenConfig.getTokenValidityForRememberMe().toMillis(); this.hoursInDay = tokenConfig.getHoursInDay(); } /** * 创建Token,并将Token写入Redis * * @param authentication 授权信息 * @param rememberMe 使用记住我 */ public JwtAccessToken createToken(Authentication authentication, boolean rememberMe) { // 用户权限信息 Set<String> authorities = authentication.getAuthorities().stream() .map(GrantedAuthority::getAuthority) .collect(Collectors.toSet()); //获取当前时间戳 long now = System.currentTimeMillis(); //存放过期时间 Date expiration; if (rememberMe) { expiration = new Date(now + this.tokenValidityInMillisecondsForRememberMe); } else { expiration = new Date(now + this.tokenValidityInMilliseconds); } // 优化过期时间 if (StringUtils.isNotBlank(hoursInDay)) { String tmp = DateTimeUtils.formatToString(expiration, DateTimeUtils.yyyy_MM_dd); try { expiration = DateTimeUtils.parseDate(tmp.trim() + " " + hoursInDay.trim(), DateTimeUtils.yyyy_MM_dd_HH_mm_ss); } catch (Throwable e) { log.warn("### TokenConfig.hoursInDay配置错误", e); } if (expiration.getTime() <= now) { expiration = DateTimeUtils.addDays(expiration, 1); } } //创建Token令牌 - iss(签发者), aud(接收方), sub(面向的用户),exp(过期时间戳), iat(签发时间), jti(JWT ID) DefaultClaims claims = new DefaultClaims(); claims.setIssuer(tokenConfig.getIssuer()); claims.setAudience(tokenConfig.getAudience()); claims.setSubject(authentication.getName()); claims.setExpiration(expiration); claims.setIssuedAt(new Date()); claims.setId(String.valueOf(SnowFlake.SNOW_FLAKE.nextId())); // 设置角色和权限 claims.put(PermissionKey, authorities); // TODO 设置角色 claims.put(RoleKey, new HashSet<String>(0)); // 签名私钥 Key key = Keys.hmacShaKeyFor((authentication.getName() + secretKey).getBytes()); String token = Jwts.builder() .setClaims(claims) .signWith(key, SignatureAlgorithm.HS512) .compact(); // 构建返回数据 Jws<Claims> claimsJws = Jwts.parser().setSigningKey(key).parseClaimsJws(token); JwtAccessToken jwtAccessToken = new JwtAccessToken(); jwtAccessToken.setToken(token); jwtAccessToken.setHeader(claimsJws.getHeader()); jwtAccessToken.setClaims(claimsJws.getBody()); jwtAccessToken.setRefreshToken(createRefreshToken(authentication.getName())); return jwtAccessToken; } /** * 校验Token,校验失败抛出异常 */ public Jws<Claims> getClaimsJws(String token) { String[] strArray = token.split("\\."); if (strArray.length != 3) { throw new MalformedJwtException("Token格式不正确"); } // 解析获得签名私钥 String payload = strArray[1]; payload = new String(EncodeDecodeUtils.decodeBase64(payload)); DefaultClaims claims = JacksonMapper.nonEmptyMapper().fromJson(payload, DefaultClaims.class); Key key = Keys.hmacShaKeyFor((claims.getSubject() + secretKey).getBytes()); try { //通过密钥验证Token return Jwts.parser().setSigningKey(key).parseClaimsJws(token); } catch (SignatureException e) { // 签名异常 throw new BusinessException("Token签名异常", e); } catch (MalformedJwtException e) { // JWT格式错误 throw new BusinessException("Token格式错误", e); } catch (ExpiredJwtException e) { // JWT过期 throw new BusinessException("TokenJWT过期", e); } catch (UnsupportedJwtException e) { // 不支持该JWT throw new BusinessException("不支持该Token", e); } catch (IllegalArgumentException e) { // 参数错误异常 throw new BusinessException("Token参数错误异常", e); } } /** * 生成刷新令牌 */ private String createRefreshToken(String username) { return username + ":" + IDCreateUtils.shortUuid(); } // /** // * 通过刷新令牌得到用户名 // */ // public String getUsernameByRefreshToken(String refreshToken) { // return refreshToken.substring(0, refreshToken.lastIndexOf(':')); // } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/config/SessionWebSecurityConfig.java<|end_filename|> package org.clever.security.config; import lombok.extern.slf4j.Slf4j; import org.clever.security.Constant; import org.clever.security.authentication.CollectLoginToken; import org.clever.security.authentication.UserLoginEntryPoint; import org.clever.security.authentication.filter.UserLoginFilter; import org.clever.security.config.model.LoginConfig; import org.clever.security.config.model.RememberMeConfig; import org.clever.security.handler.UserAccessDeniedHandler; import org.clever.security.handler.UserLogoutSuccessHandler; import org.clever.security.rememberme.RememberMeServices; import org.clever.security.repository.SecurityContextRepositoryProxy; import org.clever.security.service.GlobalUserDetailsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.access.AccessDecisionManager; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.config.BeanIds; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.context.SecurityContextRepository; import org.springframework.security.web.session.SessionInformationExpiredStrategy; import org.springframework.session.security.SpringSessionBackedSessionRegistry; import java.util.List; /** * Session 登录配置 * 作者: lzw<br/> * 创建时间:2018-03-14 14:45 <br/> */ @Configuration @ConditionalOnProperty(prefix = Constant.ConfigPrefix, name = "login-model", havingValue = "session") @Slf4j public class SessionWebSecurityConfig extends BaseWebSecurityConfig { @Autowired private SecurityConfig securityConfig; @Autowired private UserLoginFilter userLoginFilter; @Autowired private GlobalUserDetailsService globalUserDetailsService; @Autowired private List<AuthenticationProvider> authenticationProviderList; @Autowired private UserLoginEntryPoint userLoginEntryPoint; @Autowired private UserLogoutSuccessHandler userLogoutSuccessHandler; @Autowired private UserAccessDeniedHandler userAccessDeniedHandler; @Autowired private AccessDecisionManager accessDecisionManager; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; @Autowired private SecurityContextRepositoryProxy securityContextRepositoryProxy; @Autowired private SpringSessionBackedSessionRegistry sessionRegistry; @Autowired private SessionInformationExpiredStrategy sessionInformationExpiredStrategy; @Autowired private org.springframework.security.web.authentication.RememberMeServices rememberMeServices; @Override PasswordEncoder getPasswordEncoder() { return bCryptPasswordEncoder; } @Override UserDetailsService getUserDetailsService() { return globalUserDetailsService; } @Override List<AuthenticationProvider> getAuthenticationProviderList() { return authenticationProviderList; } @Override SecurityConfig getSecurityConfig() { return securityConfig; } /** * 在Spring容器中注册 AuthenticationManager */ @Bean(name = BeanIds.AUTHENTICATION_MANAGER) @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } /** * 具体的权限控制规则配置 */ @Override protected void configure(HttpSecurity http) throws Exception { http.setSharedObject(SecurityContextRepository.class, securityContextRepositoryProxy); // 自定义登录 Filter --> UserLoginFilter http.addFilterAt(userLoginFilter, UsernamePasswordAuthenticationFilter.class); // http // .csrf().and() // .addFilter(new WebAsyncManagerIntegrationFilter()) // .exceptionHandling().and() // .headers().and() // .sessionManagement().and() // .securityContext().and() // .requestCache().and() // .anonymous().and() // .servletApi().and() // .apply(new DefaultLoginPageConfigurer<>()).and() // .logout(); // ClassLoader classLoader = this.getApplicationContext().getClassLoader(); // List<AbstractHttpConfigurer> defaultHttpConfigurers = SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, classLoader); // for(AbstractHttpConfigurer configurer : defaultHttpConfigurers) { // http.apply(configurer); // } // 过滤器配置 http .csrf().disable() .exceptionHandling().authenticationEntryPoint(userLoginEntryPoint).accessDeniedHandler(userAccessDeniedHandler) .and() .authorizeRequests().anyRequest().authenticated().accessDecisionManager(accessDecisionManager) .and() .formLogin().disable() .logout().logoutUrl(securityConfig.getLogout().getLogoutUrl()).logoutSuccessHandler(userLogoutSuccessHandler).permitAll() ; // 设置"记住我功能配置" RememberMeConfig rememberMe = securityConfig.getRememberMe(); if (rememberMe != null && rememberMe.getEnable()) { http.rememberMe() .rememberMeServices(rememberMeServices) .alwaysRemember(rememberMe.getAlwaysRemember()) .tokenValiditySeconds((int) rememberMe.getValidity().getSeconds()) .rememberMeParameter(CollectLoginToken.REMEMBER_ME_PARAM) .rememberMeCookieName(RememberMeServices.REMEMBER_ME_COOKIE_NAME) .key(RememberMeServices.REMEMBER_ME_KEY) ; } // 登录并发控制 LoginConfig login = securityConfig.getLogin(); if (login.getConcurrentLoginCount() != null) { int concurrentLoginCount = login.getConcurrentLoginCount() <= 0 ? -1 : login.getConcurrentLoginCount(); boolean notAllowAfterLogin = false; if (login.getNotAllowAfterLogin() != null) { notAllowAfterLogin = login.getNotAllowAfterLogin(); } http.sessionManagement() .maximumSessions(concurrentLoginCount) .maxSessionsPreventsLogin(notAllowAfterLogin) .sessionRegistry(sessionRegistry) .expiredSessionStrategy(sessionInformationExpiredStrategy) ; } log.info("### HttpSecurity 配置完成!"); } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/UserBindRoleRes.java<|end_filename|> package org.clever.security.dto.response; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.response.BaseResponse; import org.clever.security.entity.Role; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-10-03 21:54 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class UserBindRoleRes extends BaseResponse { @ApiModelProperty("用户名") private String username; @ApiModelProperty("角色集合") private List<Role> roleList; } <|start_filename|>clever-security-model/src/main/java/org/clever/security/jackson2/UserAuthorityMixin.java<|end_filename|> package org.clever.security.jackson2; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; /** * 作者: lzw<br/> * 创建时间:2018-09-22 22:02 <br/> */ //@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_ARRAY) @JsonAutoDetect @JsonIgnoreProperties(ignoreUnknown = true) class UserAuthorityMixin { @JsonCreator public UserAuthorityMixin(@JsonProperty("authority") String authority, @JsonProperty("title") String title) { } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/annotation/UrlAuthorization.java<|end_filename|> package org.clever.security.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 定义Url授权信息 * 作者: lzw<br/> * 创建时间:2018-09-20 17:49 <br/> */ @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface UrlAuthorization { /** * 权限标题 */ String title() default ""; /** * 权限说明 */ String description() default ""; /** * 唯一权限标识字符串 */ String permissionStr() default ""; } <|start_filename|>clever-security-server/src/main/java/org/clever/security/service/RememberMeTokenService.java<|end_filename|> package org.clever.security.service; import lombok.extern.slf4j.Slf4j; import org.clever.common.exception.BusinessException; import org.clever.common.server.service.BaseService; import org.clever.security.entity.RememberMeToken; import org.clever.security.mapper.RememberMeTokenMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Date; /** * 作者: lzw<br/> * 创建时间:2018-09-24 16:35 <br/> */ @Transactional(readOnly = true) @Service @Slf4j public class RememberMeTokenService extends BaseService { @Autowired private RememberMeTokenMapper rememberMeTokenMapper; /** * 新增RememberMeToken */ @Transactional public RememberMeToken addRememberMeToken(RememberMeToken req) { // 校验token序列号是否唯一 RememberMeToken exists = rememberMeTokenMapper.getBySeries(req.getSeries()); if (exists != null) { throw new BusinessException("token序列号已经存在"); } rememberMeTokenMapper.insert(req); return rememberMeTokenMapper.selectById(req.getId()); } public RememberMeToken getRememberMeToken(String series) { return rememberMeTokenMapper.getBySeries(series); } @Transactional public Integer delRememberMeToken(String username) { return rememberMeTokenMapper.deleteByUsername(username); } /** * @param series token序列号 * @param tokenValue token值 * @param lastUsed 最后使用时间 */ @Transactional public RememberMeToken updateRememberMeToken(String series, String tokenValue, Date lastUsed) { rememberMeTokenMapper.updateBySeries(series, tokenValue, lastUsed); return rememberMeTokenMapper.getBySeries(series); } } <|start_filename|>clever-security-server/src/main/java/org/clever/security/mapper/QueryMapper.java<|end_filename|> package org.clever.security.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.metadata.IPage; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.clever.security.dto.request.RememberMeTokenQueryReq; import org.clever.security.dto.request.ServiceSysQueryReq; import org.clever.security.dto.request.UserLoginLogQueryReq; import org.clever.security.entity.ServiceSys; import org.clever.security.entity.User; import org.clever.security.entity.model.UserLoginLogModel; import org.clever.security.entity.model.UserRememberMeToken; import org.springframework.stereotype.Repository; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-10-07 21:02 <br/> */ @Repository @Mapper public interface QueryMapper extends BaseMapper<User> { List<String> allSysName(); List<String> allRoleName(); List<String> findRoleNameByUser(@Param("username") String username); List<String> findPermissionStrByRole(@Param("roleName") String roleName); List<UserRememberMeToken> findRememberMeToken(@Param("query") RememberMeTokenQueryReq query, IPage page); List<UserLoginLogModel> findUserLoginLog(@Param("query") UserLoginLogQueryReq query, IPage page); List<ServiceSys> findServiceSys(@Param("query") ServiceSysQueryReq query, IPage page); } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/authorization/RequestAccessDecisionVoter.java<|end_filename|> package org.clever.security.authorization; import lombok.extern.slf4j.Slf4j; import org.clever.security.client.WebPermissionClient; import org.clever.security.config.SecurityConfig; import org.clever.security.dto.request.WebPermissionModelGetReq; import org.clever.security.entity.EnumConstant; import org.clever.security.entity.model.WebPermissionModel; import org.clever.security.model.LoginUserDetails; import org.clever.security.model.UserAuthority; import org.clever.security.token.SecurityContextToken; import org.clever.security.token.ServerApiAccessContextToken; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.AccessDecisionVoter; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.core.Authentication; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.stereotype.Component; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerExecutionChain; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; /** * 基于HttpRequest授权校验 * <p> * 作者: lzw<br/> * 创建时间:2018-03-15 17:51 <br/> * * @see org.springframework.security.access.SecurityMetadataSource */ @Component @Slf4j public class RequestAccessDecisionVoter implements AccessDecisionVoter<FilterInvocation> { @Autowired private SecurityConfig securityConfig; @Autowired private WebPermissionClient webPermissionClient; @Autowired private RequestMappingHandlerMapping requestMappingHandlerMapping; // 不去需要授权就能访问的Url private List<AntPathRequestMatcher> antPathRequestMatcherList = new ArrayList<>(); @PostConstruct public void init() { if (securityConfig.getIgnoreAuthorizationUrls() != null) { for (String url : securityConfig.getIgnoreAuthorizationUrls()) { antPathRequestMatcherList.add(new AntPathRequestMatcher(url)); } // 打印相应的日志 if (log.isInfoEnabled()) { StringBuilder strTmp = new StringBuilder(); strTmp.append("\r\n"); strTmp.append("#=======================================================================================================================#\r\n"); strTmp.append("不需要授权检查的资源:\r\n"); for (String url : securityConfig.getIgnoreAuthorizationUrls()) { strTmp.append("\t").append(url).append("\r\n"); } strTmp.append("#=======================================================================================================================#"); log.info(strTmp.toString()); } } } @Override public boolean supports(ConfigAttribute attribute) { return true; } @Override public boolean supports(Class<?> clazz) { return FilterInvocation.class.isAssignableFrom(clazz); } /** * 授权实现 */ @Override public int vote(Authentication authentication, FilterInvocation filterInvocation, Collection<ConfigAttribute> attributes) { if (authentication instanceof ServerApiAccessContextToken) { log.info("[ServerApiAccessContextToken]允许访问 -> {}", authentication); return ACCESS_GRANTED; } if (!(authentication instanceof SecurityContextToken)) { log.info("### 放弃授权(authentication类型不匹配SecurityContextToken) -> [{}] [{}]", authentication.getClass().getSimpleName(), filterInvocation.getRequestUrl()); return ACCESS_ABSTAIN; } SecurityContextToken securityContextToken = (SecurityContextToken) authentication; LoginUserDetails loginUserDetails = securityContextToken.getUserDetails(); if (loginUserDetails == null) { log.info("### 放弃授权(loginUserDetails为空) -> [{}]", filterInvocation.getRequestUrl()); return ACCESS_ABSTAIN; } log.info("### 开始授权 [username={}] -> [{}]", loginUserDetails.getUsername(), filterInvocation.getRequestUrl()); HandlerExecutionChain handlerExecutionChain; try { handlerExecutionChain = requestMappingHandlerMapping.getHandler(filterInvocation.getHttpRequest()); } catch (Throwable e) { log.warn("### 授权时出现异常", e); return ACCESS_DENIED; } if (handlerExecutionChain == null) { log.info("### 授权通过(未知的资源404) -> [{}]", filterInvocation.getRequestUrl()); return ACCESS_GRANTED; } // 匹配是否是不需要授权就能访问的Url for (AntPathRequestMatcher antPathRequestMatcher : antPathRequestMatcherList) { if (antPathRequestMatcher.matches(filterInvocation.getRequest())) { log.info("### 授权通过(不需要授权的URL) [{}] -> [{}]", antPathRequestMatcher.getPattern(), filterInvocation.getRequestUrl()); return ACCESS_GRANTED; } } HandlerMethod handlerMethod = (HandlerMethod) handlerExecutionChain.getHandler(); String targetClass = handlerMethod.getBeanType().getName(); String targetMethod = handlerMethod.getMethod().getName(); // 获取放签名 StringBuilder methodParams = new StringBuilder(); Class<?>[] paramTypes = handlerMethod.getMethod().getParameterTypes(); for (Class<?> clzz : paramTypes) { if (methodParams.length() > 0) { methodParams.append(", "); } methodParams.append(clzz.getName()); } WebPermissionModelGetReq req = new WebPermissionModelGetReq(); req.setSysName(securityConfig.getSysName()); req.setTargetClass(targetClass); req.setTargetMethod(targetMethod); req.setTargetMethodParams(methodParams.toString()); WebPermissionModel webPermissionModel = webPermissionClient.getWebPermissionModel(req); if (webPermissionModel == null) { log.info("### 授权通过(当前资源未配置权限) [{}#{}] -> [{}]", targetClass, targetMethod, filterInvocation.getRequestUrl()); return ACCESS_GRANTED; } log.info("### 权限字符串 [{}] -> [{}]", webPermissionModel.getPermissionStr(), filterInvocation.getRequestUrl()); if (Objects.equals(webPermissionModel.getNeedAuthorization(), EnumConstant.Permission_NeedAuthorization_2)) { log.info("### 授权通过(当前资源不需要访问权限) [{}#{}] [{}] -> [{}]", targetClass, targetMethod, webPermissionModel.getResourcesUrl(), filterInvocation.getRequestUrl()); return ACCESS_GRANTED; } // 对比权限字符串 permission.getPermission() if (checkPermission(webPermissionModel.getPermissionStr(), loginUserDetails.getAuthorities())) { log.info("### 授权通过(已授权) [{}#{}] [{}] -> [{}]", targetClass, targetMethod, webPermissionModel.getResourcesUrl(), filterInvocation.getRequestUrl()); return ACCESS_GRANTED; } log.info("### 授权失败(未授权) [{}#{}] [{}] -> [{}]", targetClass, targetMethod, webPermissionModel.getResourcesUrl(), filterInvocation.getRequestUrl()); return ACCESS_DENIED; } /** * 校验权限字符串 */ private boolean checkPermission(String permissionStr, Collection<UserAuthority> authorities) { if (authorities == null) { return false; } for (UserAuthority userAuthority : authorities) { if (Objects.equals(permissionStr, userAuthority.getAuthority())) { log.info("### 权限字符串匹配成功 [{}] [{}]", userAuthority.getAuthority(), userAuthority.getTitle()); return true; } } return false; } } <|start_filename|>clever-security-server/src/main/java/org/clever/security/controller/ServiceSysController.java<|end_filename|> package org.clever.security.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.clever.common.utils.mapper.BeanMapper; import org.clever.security.dto.request.ServiceSysAddReq; import org.clever.security.entity.ServiceSys; import org.clever.security.service.ServiceSysService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-10-22 20:34 <br/> */ @Api("服务系统") @RestController @RequestMapping("/api") public class ServiceSysController { @Autowired private ServiceSysService serviceSysService; @ApiOperation("查询所有系统信息") @GetMapping("/service_sys") public List<ServiceSys> allSysName() { return serviceSysService.selectAll(); } @ApiOperation("注册系统") @PostMapping("/service_sys") public ServiceSys registerSys(@RequestBody @Validated ServiceSysAddReq serviceSysAddReq) { ServiceSys serviceSys = BeanMapper.mapper(serviceSysAddReq, ServiceSys.class); return serviceSysService.registerSys(serviceSys); } @ApiOperation("删除系统") @DeleteMapping("/service_sys/{sysName}") public ServiceSys delServiceSys(@PathVariable("sysName") String sysName) { return serviceSysService.delServiceSys(sysName); } } <|start_filename|>clever-security-server/src/main/java/org/clever/security/service/ManageByPermissionService.java<|end_filename|> package org.clever.security.service; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.clever.common.exception.BusinessException; import org.clever.common.utils.IDCreateUtils; import org.clever.common.utils.mapper.BeanMapper; import org.clever.security.dto.request.PermissionQueryReq; import org.clever.security.dto.request.PermissionUpdateReq; import org.clever.security.entity.EnumConstant; import org.clever.security.entity.Permission; import org.clever.security.entity.WebPermission; import org.clever.security.entity.model.WebPermissionModel; import org.clever.security.mapper.PermissionMapper; import org.clever.security.mapper.RoleMapper; import org.clever.security.mapper.WebPermissionMapper; import org.clever.security.service.internal.ReLoadSessionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Set; /** * 作者: lzw<br/> * 创建时间:2018-10-03 12:51 <br/> */ @Transactional(readOnly = true) @Service @Slf4j public class ManageByPermissionService { @Autowired private PermissionMapper permissionMapper; @Autowired private WebPermissionMapper webPermissionMapper; @Autowired private RoleMapper roleMapper; @Autowired private ReLoadSessionService reLoadSessionService; public IPage<WebPermissionModel> findByPage(PermissionQueryReq queryReq) { Page<WebPermissionModel> page = new Page<>(queryReq.getPageNo(), queryReq.getPageSize()); page.setRecords(permissionMapper.findByPage(queryReq, page)); return page; } @Transactional public WebPermissionModel addPermission(Permission permission) { if (StringUtils.isBlank(permission.getPermissionStr())) { permission.setPermissionStr(IDCreateUtils.shortUuid()); } int count = permissionMapper.existsPermission(permission.getPermissionStr()); if (count > 0) { throw new BusinessException("权限已存在"); } permissionMapper.insert(permission); return permissionMapper.getByPermissionStr(permission.getPermissionStr()); } @Transactional public WebPermissionModel updatePermission(String permissionStr, PermissionUpdateReq permissionUpdateReq) { WebPermissionModel webPermissionModel = permissionMapper.getByPermissionStr(permissionStr); if (webPermissionModel == null) { throw new BusinessException("权限[" + permissionStr + "]不存在"); } if (StringUtils.isBlank(permissionUpdateReq.getPermissionStr())) { permissionUpdateReq.setPermissionStr(null); } if (StringUtils.isNotBlank(permissionUpdateReq.getPermissionStr()) && permissionUpdateReq.getPermissionStr().startsWith("[auto]") && !webPermissionModel.getPermissionStr().equals(permissionUpdateReq.getPermissionStr())) { throw new BusinessException("权限标识不能以“[auto]”开始"); } // 更新权限 if (Objects.equals(webPermissionModel.getResourcesType(), EnumConstant.Permission_ResourcesType_1) && permissionUpdateReq.getNeedAuthorization() != null && !Objects.equals(webPermissionModel.getNeedAuthorization(), permissionUpdateReq.getNeedAuthorization())) { // 更新WEB权限 WebPermission webPermission = new WebPermission(); webPermission.setId(webPermissionModel.getWebPermissionId()); webPermission.setPermissionStr(permissionUpdateReq.getPermissionStr()); webPermission.setNeedAuthorization(permissionUpdateReq.getNeedAuthorization()); webPermissionMapper.updateById(webPermission); } Permission permission = BeanMapper.mapper(permissionUpdateReq, Permission.class); permission.setId(webPermissionModel.getPermissionId()); if (permission.getTitle() != null || permission.getPermissionStr() != null || permission.getResourcesType() != null || permission.getDescription() != null) { permissionMapper.updateById(permission); } if (permissionUpdateReq.getPermissionStr() != null && !Objects.equals(permissionStr, permissionUpdateReq.getPermissionStr())) { // 更新 role_permission 表 - 先查询受影响的角色 List<String> roleNameList = roleMapper.findRoleNameByPermissionStr(permissionStr); roleMapper.updateRolePermissionByPermissionStr(permissionStr, permissionUpdateReq.getPermissionStr()); // 计算影响的用户 更新Session reLoadSessionService.onChangeRole(roleNameList); } String newPermissionStr = StringUtils.isBlank(permissionUpdateReq.getPermissionStr()) ? permissionStr : permissionUpdateReq.getPermissionStr(); return permissionMapper.getByPermissionStr(newPermissionStr); } public WebPermissionModel getPermissionModel(String permissionStr) { return permissionMapper.getByPermissionStr(permissionStr); } @Transactional public WebPermissionModel delPermissionModel(String permissionStr) { WebPermissionModel webPermissionModel = permissionMapper.getByPermissionStr(permissionStr); if (webPermissionModel == null) { throw new BusinessException("权限[" + permissionStr + "]不存在"); } permissionMapper.deleteById(webPermissionModel.getPermissionId()); webPermissionMapper.deleteById(webPermissionModel.getWebPermissionId()); // 删除 role_permission 表 - 先查询受影响的角色 List<String> roleNameList = roleMapper.findRoleNameByPermissionStr(permissionStr); permissionMapper.delRolePermission(permissionStr); // 计算影响的用户 更新Session reLoadSessionService.onChangeRole(roleNameList); return webPermissionModel; } @Transactional public List<WebPermissionModel> delPermissionModels(Set<String> permissionSet) { List<WebPermissionModel> list = new ArrayList<>(); for (String permission : permissionSet) { WebPermissionModel webPermissionModel = permissionMapper.getByPermissionStr(permission); if (webPermissionModel == null) { throw new BusinessException("权限[" + permission + "]不存在"); } list.add(webPermissionModel); } // 删除 - 先查询受影响的角色 List<String> roleNameList = roleMapper.findRoleNameByPermissionStrList(permissionSet); for (WebPermissionModel webPermissionModel : list) { permissionMapper.deleteById(webPermissionModel.getPermissionId()); webPermissionMapper.deleteById(webPermissionModel.getWebPermissionId()); permissionMapper.delRolePermission(webPermissionModel.getPermissionStr()); } // 计算影响的用户 更新Session reLoadSessionService.onChangeRole(roleNameList); return list; } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/entity/EnumConstant.java<|end_filename|> package org.clever.security.entity; /** * 作者: lzw<br/> * 创建时间:2018-09-17 14:15 <br/> */ public class EnumConstant { /** * 帐号是否锁定,0:未锁定 */ public static final Integer User_Locked_0 = 0; /** * 帐号是否锁定,1:锁定 */ public static final Integer User_Locked_1 = 1; /** * 是否启用,0:禁用 */ public static final Integer User_Enabled_0 = 0; /** * 是否启用,1:启用 */ public static final Integer User_Enabled_1 = 1; /** * 需要授权才允许访问(1:需要) */ public static final Integer Permission_NeedAuthorization_1 = 1; /** * 需要授权才允许访问(2:不需要) */ public static final Integer Permission_NeedAuthorization_2 = 2; /** * 权限类型,1:web资源权限 */ public static final Integer Permission_ResourcesType_1 = 1; /** * 权限类型,2:菜单权限 */ public static final Integer Permission_ResourcesType_2 = 2; /** * 权限类型,3:ui权限 */ public static final Integer Permission_ResourcesType_3 = 3; /** * controller路由资源是否存在,0:不存在 */ public static final Integer WebPermission_targetExist_0 = 0; /** * controller路由资源是否存在,1:存在 */ public static final Integer WebPermission_targetExist_1 = 1; /** * 登录状态,0:未知 */ public static final Integer UserLoginLog_LoginState_0 = 0; /** * 登录状态,1:已登录 */ public static final Integer UserLoginLog_LoginState_1 = 1; /** * 登录状态,2:登录已过期 */ public static final Integer UserLoginLog_LoginState_2 = 2; /** * 登录类型,0:session-cookie */ public static final Integer ServiceSys_LoginModel_0 = 0; /** * 登录类型,1:jwt-token */ public static final Integer ServiceSys_LoginModel_1 = 1; } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/UserQueryPageReq.java<|end_filename|> package org.clever.security.dto.request; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.request.QueryByPage; import java.util.Date; /** * 作者: lzw<br/> * 创建时间:2018-10-02 21:22 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class UserQueryPageReq extends QueryByPage { @ApiModelProperty("登录名(一条记录的手机号不能当另一条记录的用户名用)") private String username; @ApiModelProperty("用户类型,0:系统内建,1:外部系统用户") private Integer userType; @ApiModelProperty("手机号") private String telephone; @ApiModelProperty("邮箱") private String email; @ApiModelProperty("帐号过期时间-开始") private Date expiredTimeStart; @ApiModelProperty("帐号过期时间-结束") private Date expiredTimeEnd; @ApiModelProperty("帐号是否锁定,0:未锁定;1:锁定") private Integer locked; @ApiModelProperty("是否启用,0:禁用;1:启用") private Integer enabled; @ApiModelProperty("登录名、手机号、邮箱(模糊匹配)") private String search; } <|start_filename|>clever-security-model/src/main/java/org/clever/security/entity/UserRole.java<|end_filename|> package org.clever.security.entity; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * 用户-角色(UserRole)实体类 * * @author lizw * @since 2018-09-16 21:24:44 */ @Data public class UserRole implements Serializable { private static final long serialVersionUID = -79782786523606049L; /** 登录名 */ private String username; /** 角色名称 */ private String roleName; /** 创建时间 */ private Date createAt; /** 更新时间 */ private Date updateAt; } <|start_filename|>clever-security-model/src/main/java/org/clever/security/token/JwtAccessToken.java<|end_filename|> package org.clever.security.token; import io.jsonwebtoken.Claims; import io.jsonwebtoken.JwsHeader; import lombok.Data; import java.io.Serializable; /** * 作者: lzw<br/> * 创建时间:2018-11-18 22:27 <br/> */ @Data public class JwtAccessToken implements Serializable { /** * JWT Token 字符串 */ private String token; /** * JWT 刷新 Token 字符串 */ private String refreshToken; /** * JWT Token Header */ private JwsHeader header; /** * JWT Token Body */ private Claims claims; } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/service/GenerateKeyService.java<|end_filename|> package org.clever.security.service; import io.jsonwebtoken.Claims; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.clever.common.exception.BusinessException; import org.clever.security.config.SecurityConfig; import org.clever.security.config.model.TokenConfig; import org.springframework.stereotype.Component; /** * 作者: lzw<br/> * 创建时间:2018-11-19 11:22 <br/> */ @Component @Slf4j public class GenerateKeyService { /** * SecurityContext Key */ private static final String SecurityContextKey = "security-context"; /** * JWT Token 令牌Key */ private static final String JwtTokenKey = "jwt-token"; /** * JWT Token 刷新令牌Key */ private static final String JwtTokenRefreshKey = "refresh-token"; /** * 验证码 Key */ private static final String CaptchaInfoKey = "captcha-info"; /** * 登录失败次数 Key */ private static final String LoginFailCountKey = "login-fail-count"; /** * Token Redis前缀 */ private final String redisNamespace; protected GenerateKeyService(SecurityConfig securityConfig) { TokenConfig tokenConfig = securityConfig.getTokenConfig(); if (tokenConfig == null || StringUtils.isBlank(tokenConfig.getRedisNamespace())) { throw new BusinessException("TokenConfig 的 RedisNamespace 属性未配置"); } String tmp = tokenConfig.getRedisNamespace(); if (tmp.endsWith(":")) { tmp = tmp.substring(0, tmp.length() - 1); } redisNamespace = tmp; } /** * 生成 Redis 存储 SecurityContextKey */ public String getSecurityContextKey(String username) { // {redisNamespace}:{SecurityContextKey}:{username} return String.format("%s:%s:%s", redisNamespace, SecurityContextKey, username); } /** * 生成 Redis 存储 JwtTokenKey */ public String getJwtTokenKey(Claims claims) { return getJwtTokenKey(claims.getSubject(), claims.getId()); } /** * 生成 Redis 存储 JwtTokenKey */ public String getJwtTokenKey(String username, String tokenId) { // {redisNamespace}:{JwtTokenKey}:{username}:{JWT ID} return String.format("%s:%s:%s:%s", redisNamespace, JwtTokenKey, username, tokenId); } /** * 生成 Redis 存储 JwtTokenKey Pattern */ public String getJwtTokenPatternKey(String username) { // {redisNamespace}:{JwtTokenKey}:{username}:{*} return String.format("%s:%s:%s:%s", redisNamespace, JwtTokenKey, username, "*"); } /** * 生成 Redis 存储 JwtTokenRefreshKey */ public String getJwtRefreshTokenKey(String refreshToken) { // {redisNamespace}:{JwtTokenRefreshKey}:{refreshToken} return String.format("%s:%s:%s", redisNamespace, JwtTokenRefreshKey, refreshToken); } /** * 生成 Redis 存储 CaptchaInfoKey */ public String getCaptchaInfoKey(String code, String imageDigest) { // {redisNamespace}:{CaptchaInfoKey}:{code}:{imageDigest} return String.format("%s:%s:%s:%s", redisNamespace, CaptchaInfoKey, code, imageDigest); } /** * 生成 Redis 存储 LoginFailCountKey */ public String getLoginFailCountKey(String username) { // {redisNamespace}:{LoginFailCountKey}:{username} return String.format("%s:%s:%s", redisNamespace, LoginFailCountKey, username); } // /** // * 生成 Redis 存储 JwtTokenRefreshKey Pattern // */ // public String getJwtRefreshTokenPatternKey(String username) { // // {redisNamespace}:{JwtTokenRefreshKey}:{username}:{*} // return String.format("%s:%s:%s:%s", redisNamespace, JwtTokenRefreshKey, username, "*"); // } } <|start_filename|>clever-security-client/src/main/java/org/clever/security/client/WebPermissionClient.java<|end_filename|> package org.clever.security.client; import org.clever.security.config.CleverSecurityFeignConfiguration; import org.clever.security.dto.request.WebPermissionInitReq; import org.clever.security.dto.request.WebPermissionModelGetReq; import org.clever.security.dto.response.WebPermissionInitRes; import org.clever.security.entity.model.WebPermissionModel; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.cloud.openfeign.SpringQueryMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-09-24 19:14 <br/> */ @FeignClient( contextId = "org.clever.security.client.WebPermissionClient", name = "clever-security-server", path = "/api", configuration = CleverSecurityFeignConfiguration.class ) public interface WebPermissionClient { /** * 根据系统和Controller信息查询Web权限 */ @GetMapping("/web_permission") WebPermissionModel getWebPermissionModel(@SpringQueryMap WebPermissionModelGetReq req); /** * 查询某个系统的所有Web权限 */ @GetMapping("/web_permission/{sysName}") List<WebPermissionModel> findAllWebPermissionModel(@PathVariable("sysName") String sysName); /** * 初始化某个系统的所有Web权限 */ @PostMapping("/web_permission/{sysName}") WebPermissionInitRes initWebPermission(@PathVariable("sysName") String sysName, @RequestBody WebPermissionInitReq req); } <|start_filename|>clever-security-server/src/main/java/org/clever/security/service/UserLoginLogService.java<|end_filename|> package org.clever.security.service; import lombok.extern.slf4j.Slf4j; import org.clever.common.exception.BusinessException; import org.clever.security.entity.UserLoginLog; import org.clever.security.mapper.UserLoginLogMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * 作者: lzw<br/> * 创建时间:2018-09-23 16:03 <br/> */ @Transactional(readOnly = true) @Service @Slf4j public class UserLoginLogService { @Autowired private UserLoginLogMapper userLoginLogMapper; @Transactional public UserLoginLog addUserLoginLog(UserLoginLog userLoginLog) { userLoginLogMapper.insert(userLoginLog); return userLoginLogMapper.selectById(userLoginLog.getId()); } public UserLoginLog getUserLoginLog(String sessionId) { return userLoginLogMapper.getBySessionId(sessionId); } @Transactional public UserLoginLog updateUserLoginLog(String sessionId, UserLoginLog update) { UserLoginLog old = userLoginLogMapper.getBySessionId(sessionId); if (old == null) { throw new BusinessException("登录记录不存在,SessionId=" + sessionId); } update.setId(old.getId()); userLoginLogMapper.updateById(update); return userLoginLogMapper.selectById(old.getId()); } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/repository/SecurityContextRepositoryProxy.java<|end_filename|> package org.clever.security.repository; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.clever.security.LoginModel; import org.clever.security.config.SecurityConfig; import org.clever.security.config.model.ServerApiAccessToken; import org.clever.security.token.ServerApiAccessContextToken; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.InternalAuthenticationServiceException; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.security.web.context.HttpRequestResponseHolder; import org.springframework.security.web.context.HttpSessionSecurityContextRepository; import org.springframework.security.web.context.SecurityContextRepository; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Objects; /** * 作者: lzw<br/> * 创建时间:2019-05-16 14:28 <br/> */ @Component @Slf4j public class SecurityContextRepositoryProxy implements SecurityContextRepository { private SecurityConfig securityConfig; @Autowired(required = false) private JwtRedisSecurityContextRepository jwtRedisSecurityContextRepository; @Autowired(required = false) private HttpSessionSecurityContextRepository httpSessionSecurityContextRepository; public SecurityContextRepositoryProxy(@Autowired SecurityConfig securityConfig) { this.securityConfig = securityConfig; if (LoginModel.session.equals(securityConfig.getLoginModel())) { httpSessionSecurityContextRepository = new HttpSessionSecurityContextRepository(); } } @Override public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) { if (userServerApiAccessToken(requestResponseHolder.getRequest())) { ServerApiAccessToken serverApiAccessToken = securityConfig.getServerApiAccessToken(); if (validationServerApiAccessToken(requestResponseHolder.getRequest())) { ServerApiAccessContextToken serverApiAccessContextToken = new ServerApiAccessContextToken(serverApiAccessToken.getTokenName(), serverApiAccessToken.getTokenValue()); // log.info("[ServerApiAccessContextToken]创建成功 -> {}", serverApiAccessContextToken); return new SecurityContextImpl(serverApiAccessContextToken); } } return getSecurityContextRepository().loadContext(requestResponseHolder); } @Override public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) { if (context.getAuthentication() instanceof ServerApiAccessContextToken) { // log.info("[ServerApiAccessContextToken]不需要持久化保存 -> {}", context.getAuthentication()); return; } getSecurityContextRepository().saveContext(context, request, response); } @Override public boolean containsContext(HttpServletRequest request) { if (userServerApiAccessToken(request)) { if (validationServerApiAccessToken(request)) { return true; } } return getSecurityContextRepository().containsContext(request); } private SecurityContextRepository getSecurityContextRepository() { if (LoginModel.jwt.equals(securityConfig.getLoginModel())) { return jwtRedisSecurityContextRepository; } else if (LoginModel.session.equals(securityConfig.getLoginModel())) { return httpSessionSecurityContextRepository; } throw new InternalAuthenticationServiceException("未知的登入模式"); } /** * 验证请求使用的 ServerApiAccessToken */ private boolean validationServerApiAccessToken(HttpServletRequest request) { ServerApiAccessToken serverApiAccessToken = securityConfig.getServerApiAccessToken(); String token = request.getHeader(serverApiAccessToken.getTokenName()); boolean result = Objects.equals(token, serverApiAccessToken.getTokenValue()); if (!result) { log.warn("[ServerApiAccessContextToken]ServerApiAccessToken验证失败 -> {}", token); } return result; } /** * 是否使用了 ServerApiAccessToken */ private boolean userServerApiAccessToken(HttpServletRequest request) { return securityConfig != null && securityConfig.getServerApiAccessToken() != null && StringUtils.isNotBlank(securityConfig.getServerApiAccessToken().getTokenName()) && StringUtils.isNotBlank(securityConfig.getServerApiAccessToken().getTokenValue()) && StringUtils.isNotBlank(request.getHeader(securityConfig.getServerApiAccessToken().getTokenName())); } } <|start_filename|>clever-security-server/src/main/java/org/clever/security/service/impl/JwtTokenSecurityContextService.java<|end_filename|> package org.clever.security.service.impl; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.clever.security.entity.*; import org.clever.security.mapper.ServiceSysMapper; import org.clever.security.mapper.UserLoginLogMapper; import org.clever.security.mapper.UserMapper; import org.clever.security.model.LoginUserDetails; import org.clever.security.model.UserAuthority; import org.clever.security.service.ISecurityContextService; import org.clever.security.token.SecurityContextToken; import org.clever.security.token.login.BaseLoginToken; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.*; /** * 作者: lzw<br/> * 创建时间:2018-11-22 19:51 <br/> */ @SuppressWarnings("Duplicates") @Transactional(readOnly = true) @Service("JwtTokenSecurityContextService") @Slf4j public class JwtTokenSecurityContextService implements ISecurityContextService { /** * SecurityContext Key */ private static final String SecurityContextKey = "security-context"; /** * JWT Token 令牌Key */ private static final String JwtTokenKey = "jwt-token"; /** * JWT Token 刷新令牌Key */ private static final String JwtTokenRefreshKey = "refresh-token"; @Autowired private ServiceSysMapper serviceSysMapper; @Autowired private UserMapper userMapper; @Autowired private UserLoginLogMapper userLoginLogMapper; @Autowired private RedisTemplate<String, Object> redisTemplate; /** * 生成 Redis 存储 SecurityContextKey */ private String getSecurityContextKey(String redisNamespace, String username) { // {redisNamespace}:{SecurityContextKey}:{username} return String.format("%s:%s:%s", redisNamespace, SecurityContextKey, username); } /** * 生成 Redis 存储 JwtTokenKey Pattern */ private String getJwtTokenPatternKey(String redisNamespace, String username) { // {redisNamespace}:{JwtTokenKey}:{username}:{*} return String.format("%s:%s:%s:%s", redisNamespace, JwtTokenKey, username, "*"); } /** * 生成 Redis 存储 JwtTokenRefreshKey */ private String getJwtRefreshTokenKey(String redisNamespace, String refreshToken) { // {redisNamespace}:{JwtTokenRefreshKey}:{refreshToken} return String.format("%s:%s:%s", redisNamespace, JwtTokenRefreshKey, refreshToken); } /** * 加载用户安全信息 * * @param loginToken 当前的loginToken * @param sysName 系统名 * @param userName 用户名 * @return 不存在返回null */ private SecurityContextToken loadUserLoginToken(BaseLoginToken loginToken, String sysName, String userName) { // 获取用所有权限 User user = userMapper.getByUnique(userName); if (user == null) { return null; } List<Permission> permissionList = userMapper.findByUsername(userName, sysName); LoginUserDetails userDetails = new LoginUserDetails(user); for (Permission permission : permissionList) { userDetails.getAuthorities().add(new UserAuthority(permission.getPermissionStr(), permission.getTitle())); } // TODO 加载角色 // userDetails.getRoles().add(); // 组装 UserLoginToken return new SecurityContextToken(loginToken, userDetails); } /** * 加载用户安全信息 * * @param newUserLoginToken 新的Token * @param oldUserLoginToken 旧的Token */ private SecurityContext loadSecurityContext(SecurityContextToken newUserLoginToken, SecurityContextToken oldUserLoginToken) { newUserLoginToken.setDetails(oldUserLoginToken.getDetails()); newUserLoginToken.eraseCredentials(); // 组装 SecurityContext return new SecurityContextImpl(newUserLoginToken); } @Override public Map<String, SecurityContext> getSecurityContext(String sysName, String userName) { ServiceSys serviceSys = serviceSysMapper.getBySysName(sysName); if (serviceSys == null || StringUtils.isBlank(serviceSys.getRedisNameSpace()) || !Objects.equals(EnumConstant.ServiceSys_LoginModel_1, serviceSys.getLoginModel())) { return null; } String securityContextKey = getSecurityContextKey(serviceSys.getRedisNameSpace(), userName); Object securityObject = redisTemplate.opsForValue().get(securityContextKey); if (securityObject == null) { return null; } Map<String, SecurityContext> map = new HashMap<>(); SecurityContext securityContext = null; if (securityObject instanceof SecurityContext) { securityContext = (SecurityContext) securityObject; } map.put(sysName, securityContext); return map; } @Override public SecurityContext getSecurityContext(String tokenId) { UserLoginLog userLoginLog = userLoginLogMapper.getBySessionId(tokenId); ServiceSys serviceSys = serviceSysMapper.getBySysName(userLoginLog.getSysName()); if (serviceSys == null || StringUtils.isBlank(serviceSys.getRedisNameSpace()) || !Objects.equals(EnumConstant.ServiceSys_LoginModel_1, serviceSys.getLoginModel())) { return null; } String securityContextKey = getSecurityContextKey(serviceSys.getRedisNameSpace(), userLoginLog.getUsername()); Object securityObject = redisTemplate.opsForValue().get(securityContextKey); if (securityObject == null) { return null; } if (securityObject instanceof SecurityContext) { return (SecurityContext) securityObject; } return null; } @Override public List<SecurityContext> reloadSecurityContext(String sysName, String userName) { List<SecurityContext> newSecurityContextList = new ArrayList<>(); ServiceSys serviceSys = serviceSysMapper.getBySysName(sysName); if (serviceSys == null || StringUtils.isBlank(serviceSys.getRedisNameSpace()) || !Objects.equals(EnumConstant.ServiceSys_LoginModel_1, serviceSys.getLoginModel())) { return null; } String securityContextKey = getSecurityContextKey(serviceSys.getRedisNameSpace(), userName); Object oldSecurityObject = redisTemplate.opsForValue().get(securityContextKey); if (!(oldSecurityObject instanceof SecurityContext)) { return null; } SecurityContext oldSecurityContext = (SecurityContext) oldSecurityObject; if (!(oldSecurityContext.getAuthentication() instanceof SecurityContextToken)) { return null; } SecurityContextToken oldUserLoginToken = (SecurityContextToken) oldSecurityContext.getAuthentication(); SecurityContextToken newUserLoginToken = loadUserLoginToken(oldUserLoginToken.getLoginToken(), sysName, userName); if (newUserLoginToken == null) { return null; } SecurityContext newSecurityContext = loadSecurityContext(newUserLoginToken, oldUserLoginToken); newSecurityContextList.add(newSecurityContext); redisTemplate.opsForValue().set(securityContextKey, newSecurityContext); // 删除 JwtToken String JwtTokenKeyPattern = getJwtTokenPatternKey(serviceSys.getRedisNameSpace(), userName); Set<String> JwtTokenKeySet = redisTemplate.keys(JwtTokenKeyPattern); if (JwtTokenKeySet != null && JwtTokenKeySet.size() > 0) { redisTemplate.delete(JwtTokenKeySet); } return newSecurityContextList; } @Override public Map<String, List<SecurityContext>> reloadSecurityContext(String userName) { Map<String, List<SecurityContext>> result = new HashMap<>(); List<ServiceSys> sysList = userMapper.findSysByUsername(userName); if (sysList == null || sysList.size() <= 0) { return result; } for (ServiceSys serviceSys : sysList) { if (serviceSys == null || StringUtils.isBlank(serviceSys.getRedisNameSpace()) || !Objects.equals(EnumConstant.ServiceSys_LoginModel_1, serviceSys.getLoginModel())) { continue; } List<SecurityContext> securityContextList = reloadSecurityContext(serviceSys.getSysName(), userName); result.put(serviceSys.getSysName(), securityContextList); } return result; } @Override public int forcedOffline(String sysName, String userName) { int count = 0; ServiceSys serviceSys = serviceSysMapper.getBySysName(sysName); if (serviceSys == null || StringUtils.isBlank(serviceSys.getRedisNameSpace()) || !Objects.equals(EnumConstant.ServiceSys_LoginModel_1, serviceSys.getLoginModel())) { return 0; } // 删除 JwtToken String JwtTokenKeyPattern = getJwtTokenPatternKey(serviceSys.getRedisNameSpace(), userName); Set<String> JwtTokenKeySet = redisTemplate.keys(JwtTokenKeyPattern); if (JwtTokenKeySet != null && JwtTokenKeySet.size() > 0) { redisTemplate.delete(JwtTokenKeySet); count = JwtTokenKeySet.size(); } // 删除 RefreshToken String jwtRefreshTokenKeyPattern = getJwtRefreshTokenKey(serviceSys.getRedisNameSpace(), userName + ":*"); Set<String> jwtRefreshTokenKeySet = redisTemplate.keys(jwtRefreshTokenKeyPattern); if (jwtRefreshTokenKeySet != null && jwtRefreshTokenKeySet.size() > 0) { redisTemplate.delete(jwtRefreshTokenKeySet); count = jwtRefreshTokenKeySet.size(); } return count; } @Override public void delSession(String userName) { List<ServiceSys> sysList = userMapper.findSysByUsername(userName); if (sysList == null || sysList.size() <= 0) { return; } for (ServiceSys serviceSys : sysList) { if (serviceSys == null || StringUtils.isBlank(serviceSys.getRedisNameSpace()) || !Objects.equals(EnumConstant.ServiceSys_LoginModel_1, serviceSys.getLoginModel())) { continue; } delSession(serviceSys.getSysName(), userName); } } @Override public void delSession(String sysName, String userName) { ServiceSys serviceSys = serviceSysMapper.getBySysName(sysName); if (serviceSys == null || StringUtils.isBlank(serviceSys.getRedisNameSpace()) || !Objects.equals(EnumConstant.ServiceSys_LoginModel_1, serviceSys.getLoginModel())) { return; } // 删除 JwtToken String JwtTokenKeyPattern = getJwtTokenPatternKey(serviceSys.getRedisNameSpace(), userName); Set<String> JwtTokenKeySet = redisTemplate.keys(JwtTokenKeyPattern); if (JwtTokenKeySet != null && JwtTokenKeySet.size() > 0) { redisTemplate.delete(JwtTokenKeySet); } // 删除 RefreshToken String jwtRefreshTokenKeyPattern = getJwtRefreshTokenKey(serviceSys.getRedisNameSpace(), userName + ":*"); Set<String> jwtRefreshTokenKeySet = redisTemplate.keys(jwtRefreshTokenKeyPattern); if (jwtRefreshTokenKeySet != null && jwtRefreshTokenKeySet.size() > 0) { redisTemplate.delete(jwtRefreshTokenKeySet); } } } <|start_filename|>clever-security-client/src/main/java/org/clever/security/client/ManageByUserClient.java<|end_filename|> package org.clever.security.client; import org.clever.security.config.CleverSecurityFeignConfiguration; import org.clever.security.dto.request.UserAddReq; import org.clever.security.dto.response.UserAddRes; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; @FeignClient( contextId = "org.clever.security.client.ManageByUserClient", name = "clever-security-server", path = "/api/manage", configuration = CleverSecurityFeignConfiguration.class ) public interface ManageByUserClient { /** * 新增用户 */ @PostMapping("/user") UserAddRes addUser(@RequestBody UserAddReq userAddReq); } <|start_filename|>clever-security-server/src/main/java/org/clever/security/controller/UserLoginLogController.java<|end_filename|> package org.clever.security.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.clever.common.server.controller.BaseController; import org.clever.common.utils.mapper.BeanMapper; import org.clever.security.dto.request.UserLoginLogAddReq; import org.clever.security.dto.request.UserLoginLogUpdateReq; import org.clever.security.entity.UserLoginLog; import org.clever.security.service.UserLoginLogService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; /** * 作者: lzw<br/> * 创建时间:2018-09-24 19:21 <br/> */ @Api("用户登录日志") @RestController @RequestMapping("/api") public class UserLoginLogController extends BaseController { @Autowired private UserLoginLogService userLoginLogService; @ApiOperation("新增登录日志") @PostMapping("/user_login_log") public UserLoginLog addUserLoginLog(@RequestBody @Validated UserLoginLogAddReq req) { UserLoginLog userLoginLog = BeanMapper.mapper(req, UserLoginLog.class); return userLoginLogService.addUserLoginLog(userLoginLog); } @ApiOperation("根据SessionID查询用户登录日志") @GetMapping("/user_login_log/{sessionId}") public UserLoginLog getUserLoginLog(@PathVariable("sessionId") String sessionId) { return userLoginLogService.getUserLoginLog(sessionId); } @ApiOperation("更新登录日志信息") @PutMapping("/user_login_log/{sessionId}") public UserLoginLog updateUserLoginLog(@PathVariable("sessionId") String sessionId, @RequestBody @Validated UserLoginLogUpdateReq req) { UserLoginLog update = BeanMapper.mapper(req, UserLoginLog.class); return userLoginLogService.updateUserLoginLog(sessionId, update); } } <|start_filename|>clever-security-client/src/main/java/org/clever/security/client/UserLoginLogClient.java<|end_filename|> package org.clever.security.client; import org.clever.security.config.CleverSecurityFeignConfiguration; import org.clever.security.dto.request.UserLoginLogAddReq; import org.clever.security.dto.request.UserLoginLogUpdateReq; import org.clever.security.entity.UserLoginLog; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; /** * 作者: lzw<br/> * 创建时间:2018-09-24 19:25 <br/> */ @FeignClient( contextId = "org.clever.security.client.UserLoginLogClient", name = "clever-security-server", path = "/api", configuration = CleverSecurityFeignConfiguration.class ) public interface UserLoginLogClient { /** * 新增登录日志 */ @PostMapping("/user_login_log") UserLoginLog addUserLoginLog(@RequestBody @Validated UserLoginLogAddReq req); /** * 根据SessionID查询用户登录日志 */ @GetMapping("/user_login_log/{sessionId}") UserLoginLog getUserLoginLog(@PathVariable("sessionId") String sessionId); /** * 更新登录日志信息 */ @PutMapping("/user_login_log/{sessionId}") UserLoginLog updateUserLoginLog(@PathVariable("sessionId") String sessionId, @RequestBody UserLoginLogUpdateReq req); } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/init/InitSystemUrlPermission.java<|end_filename|> package org.clever.security.init; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.clever.security.config.SecurityConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; import java.util.concurrent.atomic.AtomicInteger; /** * 初始化系统的所有Url权限 * <p> * 作者: lzw<br/> * 创建时间:2018-03-17 11:24 <br/> */ @Component @Slf4j public class InitSystemUrlPermission implements ApplicationListener<ContextRefreshedEvent> { /** * 是否初始化完成 */ private boolean initFinish = false; private AtomicInteger count = new AtomicInteger(0); @Autowired private SecurityConfig securityConfig; @Autowired private InitSystemUrlPermissionJob job; @Override public void onApplicationEvent(ContextRefreshedEvent event) { int countTmp = count.addAndGet(1); if (countTmp < securityConfig.getWaitSpringContextInitCount()) { log.info("### [系统权限初始化] 等待Spring容器初始化次数 {} ", countTmp); return; } log.info("### [系统权限初始化] 当前Spring容器初始化次数 {} ", countTmp); if (job == null) { log.info("### [系统权限初始化] 等待InitSystemUrlPermissionJob注入..."); return; } if (initFinish) { log.info("### [系统权限初始化] 已经初始化完成,跳过。"); return; } if (StringUtils.isBlank(securityConfig.getSysName())) { throw new RuntimeException("系统名称未配置"); } initFinish = job.execute(); if (initFinish) { log.info("### [系统权限初始化] 初始化完成!Spring容器初始化次数 {}", countTmp); } } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/token/ServerApiAccessContextToken.java<|end_filename|> package org.clever.security.token; import org.springframework.security.authentication.AbstractAuthenticationToken; import java.util.ArrayList; /** * 作者: lzw<br/> * 创建时间:2019-05-16 13:55 <br/> */ public class ServerApiAccessContextToken extends AbstractAuthenticationToken { /** * 请求头Token名称 */ private String tokenName; /** * 请求头Token值 */ private String tokenValue; /** * @param tokenName 请求头Token名称 * @param tokenValue 请求头Token值 */ public ServerApiAccessContextToken(String tokenName, String tokenValue) { super(new ArrayList<>()); this.tokenName = tokenName; this.tokenValue = tokenValue; super.setAuthenticated(true); } @Override public Object getCredentials() { return tokenValue; } @Override public Object getPrincipal() { return tokenName; } @Override public String toString() { return "ServerApiAccessContextToken{" + "tokenName='" + tokenName + '\'' + ", tokenValue='" + tokenValue + '\'' + '}'; } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/entity/ServiceSys.java<|end_filename|> package org.clever.security.entity; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * 服务系统(ServiceSys)实体类 * * @author lizw * @since 2018-10-22 15:22:30 */ @Data public class ServiceSys implements Serializable { private static final long serialVersionUID = 178234483743559404L; /** * 主键id */ private Long id; /** * 系统(或服务)名称 */ private String sysName; /** * 全局的Session Redis前缀 */ private String redisNameSpace; /** * 登录类型,0:sesion-cookie,1:jwt-token */ private Integer loginModel; /** * 说明 */ private String description; /** * 创建时间 */ private Date createAt; /** * 更新时间 */ private Date updateAt; } <|start_filename|>clever-security-server/src/main/java/org/clever/security/controller/RememberMeTokenController.java<|end_filename|> package org.clever.security.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.clever.common.server.controller.BaseController; import org.clever.common.utils.mapper.BeanMapper; import org.clever.security.dto.request.RememberMeTokenAddReq; import org.clever.security.dto.request.RememberMeTokenUpdateReq; import org.clever.security.entity.RememberMeToken; import org.clever.security.service.RememberMeTokenService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.Map; /** * 作者: lzw<br/> * 创建时间:2018-09-24 16:36 <br/> */ @Api("RememberMeToken") @RestController @RequestMapping("/api") public class RememberMeTokenController extends BaseController { @Autowired private RememberMeTokenService rememberMeTokenService; @ApiOperation("新增RememberMeToken") @PostMapping("/remember_me_token") public RememberMeToken addRememberMeToken(@RequestBody @Validated RememberMeTokenAddReq req) { RememberMeToken rememberMeToken = BeanMapper.mapper(req, RememberMeToken.class); return rememberMeTokenService.addRememberMeToken(rememberMeToken); } @ApiOperation("读取RememberMeToken") @GetMapping("/remember_me_token/series") public RememberMeToken getRememberMeToken(@RequestParam("series") String series) { return rememberMeTokenService.getRememberMeToken(series); } @ApiOperation("删除RememberMeToken") @DeleteMapping("/remember_me_token/{username}") public Map<String, Object> delRememberMeToken(@PathVariable("username") String username) { Map<String, Object> map = new HashMap<>(); Integer delCount = rememberMeTokenService.delRememberMeToken(username); map.put("delCount", delCount); return map; } @ApiOperation("修改RememberMeToken") @PutMapping("/remember_me_token/series") public RememberMeToken updateRememberMeToken(@RequestParam("series") String series, @RequestBody @Validated RememberMeTokenUpdateReq req) { return rememberMeTokenService.updateRememberMeToken(series, req.getToken(), req.getLastUsed()); } } <|start_filename|>clever-security-server/src/main/java/org/clever/security/service/local/ManageByUserServiceProxy.java<|end_filename|> package org.clever.security.service.local; import lombok.extern.slf4j.Slf4j; import org.clever.common.utils.mapper.BeanMapper; import org.clever.security.client.ManageByUserClient; import org.clever.security.dto.request.UserAddReq; import org.clever.security.dto.response.UserAddRes; import org.clever.security.entity.User; import org.clever.security.service.ManageByUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * 作者: lzw<br/> * 创建时间:2019-04-29 19:08 <br/> */ @Component @Slf4j public class ManageByUserServiceProxy implements ManageByUserClient { @Autowired private ManageByUserService manageByUserService; @Override public UserAddRes addUser(UserAddReq userAddReq) { User user = manageByUserService.addUser(userAddReq); return BeanMapper.mapper(user, UserAddRes.class); } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/entity/WebPermission.java<|end_filename|> package org.clever.security.entity; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * web权限表(permission子表)(WebPermission)实体类 * * @author lizw * @since 2018-09-16 21:24:44 */ @Data public class WebPermission implements Serializable { private static final long serialVersionUID = 197256500272108557L; /** 主键id */ private Long id; /** 权限标识字符串 */ private String permissionStr; /** controller类名称 */ private String targetClass; /** controller类的方法名称 */ private String targetMethod; /** controller类的方法参数签名 */ private String targetMethodParams; /** 资源url地址(只用作显示使用) */ private String resourcesUrl; /** 需要授权才允许访问,1:需要;2:不需要 */ private Integer needAuthorization; /** controller路由资源是否存在,0:不存在;1:存在 */ private Integer targetExist; /** 创建时间 */ private Date createAt; /** 更新时间 */ private Date updateAt; } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/UserInfoRes.java<|end_filename|> package org.clever.security.dto.response; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.response.BaseResponse; import org.clever.security.entity.Permission; import org.clever.security.entity.Role; import java.util.Date; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-10-02 22:46 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class UserInfoRes extends BaseResponse { @ApiModelProperty("主键id") private Long id; @ApiModelProperty("登录名(一条记录的手机号不能当另一条记录的用户名用)") private String username; @ApiModelProperty("用户类型,0:系统内建,1:外部系统用户") private Integer userType; @ApiModelProperty("手机号") private String telephone; @ApiModelProperty("邮箱") private String email; @ApiModelProperty("帐号过期时间") private Date expiredTime; @ApiModelProperty("帐号是否锁定,0:未锁定;1:锁定") private Integer locked; @ApiModelProperty("是否启用,0:禁用;1:启用") private Integer enabled; @ApiModelProperty("说明") private String description; @ApiModelProperty("创建时间") private Date createAt; @ApiModelProperty("更新时间") private Date updateAt; @ApiModelProperty("角色信息") private List<Role> roleList; @ApiModelProperty("权限信息") private List<Permission> permissionList; @ApiModelProperty("授权系统信息") private List<String> sysNameList; } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/config/model/AesKeyConfig.java<|end_filename|> package org.clever.security.config.model; import lombok.Data; /** * AES对称加密key配置 * 作者: lzw<br/> * 创建时间:2019-04-25 19:03 <br/> */ @Data public class AesKeyConfig { /** * 密码AES加密 key(Hex编码) -- 请求数据,与前端一致 */ private String reqPasswordAesKey; /** * 密码AES加密 iv(Hex编码) -- 请求数据,与前端一致 */ private String reqPasswordAesIv; } <|start_filename|>clever-security-server/src/main/java/org/clever/security/service/impl/DelegateSecurityContextService.java<|end_filename|> package org.clever.security.service.impl; import lombok.extern.slf4j.Slf4j; import org.clever.security.service.ISecurityContextService; import org.springframework.context.annotation.Primary; import org.springframework.security.core.context.SecurityContext; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 作者: lzw<br/> * 创建时间:2018-11-22 20:08 <br/> */ @Primary @Transactional(readOnly = true) @Service @Slf4j public class DelegateSecurityContextService implements ISecurityContextService { private final List<ISecurityContextService> sessionServiceList = new ArrayList<>(); public DelegateSecurityContextService(SessionSecurityContextService cookieSessionService, JwtTokenSecurityContextService JwtTokenSessionService) { sessionServiceList.add(cookieSessionService); sessionServiceList.add(JwtTokenSessionService); } @Override public Map<String, SecurityContext> getSecurityContext(String sysName, String userName) { Map<String, SecurityContext> map = new HashMap<>(); for (ISecurityContextService sessionService : sessionServiceList) { Map<String, SecurityContext> tmp = sessionService.getSecurityContext(sysName, userName); if (tmp != null) { map.putAll(tmp); } } return map; } @Override public SecurityContext getSecurityContext(String sessionId) { SecurityContext securityContext = null; for (ISecurityContextService sessionService : sessionServiceList) { SecurityContext tmp = sessionService.getSecurityContext(sessionId); if (tmp != null) { securityContext = tmp; break; } } return securityContext; } @Override public List<SecurityContext> reloadSecurityContext(String sysName, String userName) { List<SecurityContext> securityContextList = new ArrayList<>(); for (ISecurityContextService sessionService : sessionServiceList) { List<SecurityContext> tmp = sessionService.reloadSecurityContext(sysName, userName); if (tmp != null) { securityContextList.addAll(tmp); } } return securityContextList; } @Override public Map<String, List<SecurityContext>> reloadSecurityContext(String userName) { Map<String, List<SecurityContext>> map = new HashMap<>(); for (ISecurityContextService sessionService : sessionServiceList) { Map<String, List<SecurityContext>> tmp = sessionService.reloadSecurityContext(userName); if (tmp != null) { map.putAll(tmp); } } return map; } @Override public int forcedOffline(String sysName, String userName) { int count = 0; for (ISecurityContextService sessionService : sessionServiceList) { int tmp = sessionService.forcedOffline(sysName, userName); count += tmp; } return count; } @Override public void delSession(String userName) { for (ISecurityContextService sessionService : sessionServiceList) { sessionService.delSession(userName); } } @Override public void delSession(String sysName, String userName) { for (ISecurityContextService sessionService : sessionServiceList) { sessionService.delSession(sysName, userName); } } } <|start_filename|>clever-security-client/src/main/java/org/clever/security/client/RememberMeTokenClient.java<|end_filename|> package org.clever.security.client; import org.clever.security.config.CleverSecurityFeignConfiguration; import org.clever.security.dto.request.RememberMeTokenAddReq; import org.clever.security.dto.request.RememberMeTokenUpdateReq; import org.clever.security.entity.RememberMeToken; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.*; import java.util.Map; /** * 作者: lzw<br/> * 创建时间:2018-09-24 18:45 <br/> */ @FeignClient( contextId = "org.clever.security.client.RememberMeTokenClient", name = "clever-security-server", path = "/api", configuration = CleverSecurityFeignConfiguration.class ) public interface RememberMeTokenClient { /** * 新增RememberMeToken */ @PostMapping("/remember_me_token") RememberMeToken addRememberMeToken(@RequestBody RememberMeTokenAddReq req); /** * 读取RememberMeToken */ @GetMapping("/remember_me_token/series") RememberMeToken getRememberMeToken(@RequestParam("series") String series); /** * 删除RememberMeToken */ @DeleteMapping("/remember_me_token/{username}") Map<String, Object> delRememberMeToken(@PathVariable("username") String username); /** * 修改RememberMeToken */ @PutMapping("/remember_me_token/series") RememberMeToken updateRememberMeToken(@RequestParam("series") String series, @RequestBody RememberMeTokenUpdateReq req); } <|start_filename|>clever-security-model/src/main/java/org/clever/security/token/login/BaseLoginToken.java<|end_filename|> package org.clever.security.token.login; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; import lombok.Setter; import org.springframework.security.core.AuthenticatedPrincipal; import org.springframework.security.core.Authentication; import org.springframework.security.core.CredentialsContainer; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import java.io.Serializable; import java.security.Principal; import java.util.Collection; /** * 用户登录请求参数基础Token * <p> * 作者: lzw<br/> * 创建时间:2019-04-27 20:46 <br/> */ @JsonIgnoreProperties(value = {"isRememberMe", "credentials", "authorities", "name"}) public abstract class BaseLoginToken implements Authentication, CredentialsContainer, Serializable { /** * 是否使用记住我功能 */ @Setter @Getter private boolean isRememberMe = false; /** * 当前登录类型(用户名密码、手机号验证码、其他三方登录方式) */ @JsonProperty(access = JsonProperty.Access.READ_ONLY) @Setter @Getter private String loginType; /** * 登录请求其他信息(请求IP地址和SessionID,如: WebAuthenticationDetails) */ @Setter private Object details; /** * 登录验证码 */ @Setter @Getter private String captcha; /** * 登录验证码签名 */ @Setter @Getter private String captchaDigest; public BaseLoginToken(String loginType) { this.loginType = loginType; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return null; } /** * 没有认证成功只能返回false */ @Override public boolean isAuthenticated() { return false; } /** * 设置当前Token是否认证成功(只能设置false) */ @Override public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { if (isAuthenticated == this.isAuthenticated()) { return; } if (isAuthenticated) { throw new IllegalArgumentException("Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead"); } } /** * 返回登录请求其他信息 */ @Override public Object getDetails() { return details; } /** * 返回认证用户的唯一ID */ @Override public String getName() { if (this.getPrincipal() instanceof UserDetails) { return ((UserDetails) this.getPrincipal()).getUsername(); } if (this.getPrincipal() instanceof AuthenticatedPrincipal) { return ((AuthenticatedPrincipal) this.getPrincipal()).getName(); } if (this.getPrincipal() instanceof Principal) { return ((Principal) this.getPrincipal()).getName(); } return (this.getPrincipal() == null) ? "" : this.getPrincipal().toString(); } /** * 擦除密码 */ @Override public void eraseCredentials() { eraseSecret(getCredentials()); eraseSecret(getPrincipal()); eraseSecret(details); } private void eraseSecret(Object secret) { if (secret instanceof CredentialsContainer) { ((CredentialsContainer) secret).eraseCredentials(); } } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/ServiceSysAddReq.java<|end_filename|> package org.clever.security.dto.request; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.request.BaseRequest; import org.clever.common.validation.ValidIntegerStatus; import org.hibernate.validator.constraints.Length; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; /** * 作者: lzw<br/> * 创建时间:2018-10-22 20:41 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class ServiceSysAddReq extends BaseRequest { @ApiModelProperty("系统(或服务)名称") @NotBlank @Length(max = 127) private String sysName; @ApiModelProperty("全局的Session Redis前缀") @NotBlank @Length(max = 127) private String redisNameSpace; @ApiModelProperty("登录类型,0:sesion-cookie,1:jwt-token") @NotNull @ValidIntegerStatus({0, 1}) private Integer loginModel; @ApiModelProperty("说明") @Length(max = 511) private String description; } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/embed/controller/CurrentLoginUserController.java<|end_filename|> package org.clever.security.embed.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.clever.security.dto.response.UserRes; import org.clever.security.utils.AuthenticationUtils; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * 作者: lzw<br/> * 创建时间:2018-11-12 17:03 <br/> */ @Api("当前登录用户信息") @RestController @Slf4j public class CurrentLoginUserController { @ApiOperation("获取当前登录用户信息") @GetMapping("/login/user_info.json") public UserRes currentLoginUser() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); return AuthenticationUtils.getUserRes(authentication); } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/service/RequestCryptoService.java<|end_filename|> package org.clever.security.service; import lombok.extern.slf4j.Slf4j; import org.clever.common.exception.BusinessException; import org.clever.common.utils.codec.CryptoUtils; import org.clever.common.utils.codec.EncodeDecodeUtils; import org.clever.security.config.SecurityConfig; import org.clever.security.config.model.AesKeyConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.stereotype.Component; /** * 请求参数加密/解密 * <p> * 作者: lzw<br/> * 创建时间:2018-11-01 10:42 <br/> */ @Component @Slf4j public class RequestCryptoService { @Autowired private SecurityConfig securityConfig; /** * 登录密码 AES 加密 * * @return Base64编码密码 */ @SuppressWarnings("Duplicates") public String reqAesEncrypt(String input) { try { AesKeyConfig aesKey = securityConfig.getLoginReqAesKey(); if (aesKey == null) { throw new BusinessException("请先配置登录密码AesKey"); } byte[] passwordData = input.getBytes(); byte[] key = EncodeDecodeUtils.decodeHex(aesKey.getReqPasswordAesKey()); byte[] iv = EncodeDecodeUtils.decodeHex(aesKey.getReqPasswordAesIv()); return EncodeDecodeUtils.encodeBase64(CryptoUtils.aesEncrypt(passwordData, key, iv)); } catch (Exception e) { throw new BadCredentialsException("请求密码加密失败"); } } /** * 登录密码 AES 解密 * * @param input Base64编码密码 */ @SuppressWarnings("Duplicates") public String reqAesDecrypt(String input) { try { AesKeyConfig aesKey = securityConfig.getLoginReqAesKey(); if (aesKey == null) { throw new BusinessException("请先配置登录密码AesKey"); } byte[] passwordData = EncodeDecodeUtils.decodeBase64(input); byte[] key = EncodeDecodeUtils.decodeHex(aesKey.getReqPasswordAesKey()); byte[] iv = EncodeDecodeUtils.decodeHex(aesKey.getReqPasswordAesIv()); return CryptoUtils.aesDecrypt(passwordData, key, iv); } catch (Exception e) { throw new BadCredentialsException("请求密码解密失败"); } } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/UserRoleReq.java<|end_filename|> package org.clever.security.dto.request; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.request.BaseRequest; import javax.validation.constraints.NotBlank; /** * 作者: lzw<br/> * 创建时间:2018-10-04 13:26 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class UserRoleReq extends BaseRequest { @ApiModelProperty("用户名") @NotBlank private String username; @ApiModelProperty("角色名") @NotBlank private String roleName; } <|start_filename|>clever-security-server/src/main/java/org/clever/security/service/ManageBySecurityService.java<|end_filename|> package org.clever.security.service; import lombok.extern.slf4j.Slf4j; import org.clever.common.exception.BusinessException; import org.clever.security.dto.request.*; import org.clever.security.dto.response.RoleBindPermissionRes; import org.clever.security.dto.response.UserBindRoleRes; import org.clever.security.dto.response.UserBindSysRes; import org.clever.security.entity.Permission; import org.clever.security.entity.Role; import org.clever.security.entity.User; import org.clever.security.mapper.RoleMapper; import org.clever.security.mapper.UserMapper; import org.clever.security.service.internal.ReLoadSessionService; import org.clever.security.service.internal.RoleBindPermissionService; import org.clever.security.service.internal.UserBindRoleService; import org.clever.security.service.internal.UserBindSysNameService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-10-03 21:24 <br/> */ @Transactional(readOnly = true) @Service @Slf4j public class ManageBySecurityService { @Autowired private UserMapper userMapper; @Autowired private RoleMapper roleMapper; @Autowired private UserBindSysNameService userBindSysNameService; @Autowired private UserBindRoleService userBindRoleService; @Autowired private RoleBindPermissionService resetRoleBindPermission; @Autowired private ManageByQueryService manageByQueryService; @Autowired private ISecurityContextService sessionService; @Autowired private ReLoadSessionService reLoadSessionService; @Transactional public List<UserBindSysRes> userBindSys(UserBindSysReq userBindSysReq) { // 校验用户全部存在 for (String username : userBindSysReq.getUsernameList()) { int count = userMapper.existsByUserName(username); if (count <= 0) { throw new BusinessException("用户[" + username + "]不存在"); } } // 校验系统全部存在 List<String> allSysName = manageByQueryService.allSysName(); for (String sysName : userBindSysReq.getSysNameList()) { if (!allSysName.contains(sysName)) { throw new BusinessException("系统[" + sysName + "]不存在"); } } List<UserBindSysRes> result = new ArrayList<>(); // 设置用户绑定的系统 for (String username : userBindSysReq.getUsernameList()) { userBindSysNameService.resetUserBindSys(username, userBindSysReq.getSysNameList()); List<String> sysNameList = userMapper.findSysNameByUsername(username); UserBindSysRes userBindSysRes = new UserBindSysRes(); userBindSysRes.setUsername(username); userBindSysRes.setSysNameList(sysNameList); result.add(userBindSysRes); } return result; } @Transactional public List<UserBindRoleRes> userBindRole(UserBindRoleReq userBindSysReq) { // 校验用户全部存在 for (String username : userBindSysReq.getUsernameList()) { int count = userMapper.existsByUserName(username); if (count <= 0) { throw new BusinessException("用户[" + username + "]不存在"); } } List<UserBindRoleRes> result = new ArrayList<>(); // 设置用户绑定的系统 for (String username : userBindSysReq.getUsernameList()) { userBindRoleService.resetUserBindRole(username, userBindSysReq.getRoleNameList()); List<Role> roleList = userMapper.findRoleByUsername(username); UserBindRoleRes userBindRoleRes = new UserBindRoleRes(); userBindRoleRes.setUsername(username); userBindRoleRes.setRoleList(roleList); result.add(userBindRoleRes); } return result; } @Transactional public List<RoleBindPermissionRes> roleBindPermission(RoleBindPermissionReq roleBindPermissionReq) { // 校验角色全部存在 for (String roleName : roleBindPermissionReq.getRoleNameList()) { int count = roleMapper.existsByRole(roleName); if (count <= 0) { throw new BusinessException("角色[" + roleName + "]不存在"); } } List<RoleBindPermissionRes> result = new ArrayList<>(); // 设置用户绑定的系统 for (String roleName : roleBindPermissionReq.getRoleNameList()) { resetRoleBindPermission.resetRoleBindPermission(roleName, roleBindPermissionReq.getPermissionStrList()); List<Permission> permissionList = roleMapper.findPermissionByRoleName(roleName); RoleBindPermissionRes roleBindPermissionRes = new RoleBindPermissionRes(); roleBindPermissionRes.setRoleName(roleName); roleBindPermissionRes.setPermissionList(permissionList); result.add(roleBindPermissionRes); } return result; } @SuppressWarnings("Duplicates") @Transactional public UserBindSysRes userBindSys(UserSysReq userSysReq) { // 校验用户存在 User user = userMapper.getByUsername(userSysReq.getUsername()); if (user == null) { throw new BusinessException("用户[" + userSysReq.getUsername() + "]不存在"); } // 校验系统存在 List<String> allSysName = manageByQueryService.allSysName(); if (!allSysName.contains(userSysReq.getSysName())) { throw new BusinessException("系统[" + userSysReq.getSysName() + "]不存在"); } userMapper.addUserSys(userSysReq.getUsername(), userSysReq.getSysName()); UserBindSysRes userBindSysRes = new UserBindSysRes(); userBindSysRes.setUsername(user.getUsername()); userBindSysRes.setSysNameList(userMapper.findSysNameByUsername(user.getUsername())); return userBindSysRes; } @SuppressWarnings("Duplicates") @Transactional public UserBindSysRes userUnBindSys(UserSysReq userSysReq) { // 校验用户存在 User user = userMapper.getByUsername(userSysReq.getUsername()); if (user == null) { throw new BusinessException("用户[" + userSysReq.getUsername() + "]不存在"); } // 校验系统存在 List<String> allSysName = manageByQueryService.allSysName(); if (!allSysName.contains(userSysReq.getSysName())) { throw new BusinessException("系统[" + userSysReq.getSysName() + "]不存在"); } userMapper.delUserSys(userSysReq.getUsername(), userSysReq.getSysName()); // 删除 Session sessionService.delSession(userSysReq.getSysName(), userSysReq.getUsername()); // 构造返回数据 UserBindSysRes userBindSysRes = new UserBindSysRes(); userBindSysRes.setUsername(user.getUsername()); userBindSysRes.setSysNameList(userMapper.findSysNameByUsername(user.getUsername())); return userBindSysRes; } @Transactional public UserBindRoleRes userBindRole(UserRoleReq userRoleReq) { int count = userMapper.existsUserRole(userRoleReq.getUsername(), userRoleReq.getRoleName()); if (count >= 1) { throw new BusinessException("用户[" + userRoleReq.getUsername() + "]已经拥有角色[" + userRoleReq.getRoleName() + "]"); } userMapper.addRole(userRoleReq.getUsername(), userRoleReq.getRoleName()); // 更新Session sessionService.reloadSecurityContext(userRoleReq.getUsername()); // 构造返回数据 UserBindRoleRes res = new UserBindRoleRes(); res.setUsername(userRoleReq.getUsername()); res.setRoleList(userMapper.findRoleByUsername(userRoleReq.getUsername())); return res; } @Transactional public UserBindRoleRes userUnBindRole(UserRoleReq userRoleReq) { int count = userMapper.existsUserRole(userRoleReq.getUsername(), userRoleReq.getRoleName()); if (count <= 0) { throw new BusinessException("用户[" + userRoleReq.getUsername() + "]未拥有角色[" + userRoleReq.getRoleName() + "]"); } userMapper.delRole(userRoleReq.getUsername(), userRoleReq.getRoleName()); // 更新Session sessionService.reloadSecurityContext(userRoleReq.getUsername()); // 构造返回数据 UserBindRoleRes res = new UserBindRoleRes(); res.setUsername(userRoleReq.getUsername()); res.setRoleList(userMapper.findRoleByUsername(userRoleReq.getUsername())); return res; } @Transactional public RoleBindPermissionRes roleBindPermission(RolePermissionReq rolePermissionReq) { int count = roleMapper.existsRolePermission(rolePermissionReq.getRoleName(), rolePermissionReq.getPermissionStr()); if (count >= 1) { throw new BusinessException("角色[" + rolePermissionReq.getRoleName() + "]已经拥有权限[" + rolePermissionReq.getPermissionStr() + "]"); } roleMapper.addPermission(rolePermissionReq.getRoleName(), rolePermissionReq.getPermissionStr()); // 计算受影响的用户 更新Session reLoadSessionService.onChangeRole(rolePermissionReq.getRoleName()); // 构造返回数据 RoleBindPermissionRes res = new RoleBindPermissionRes(); res.setRoleName(rolePermissionReq.getRoleName()); res.setPermissionList(roleMapper.findPermissionByRoleName(rolePermissionReq.getRoleName())); return res; } @Transactional public RoleBindPermissionRes roleUnBindPermission(RolePermissionReq rolePermissionReq) { int count = roleMapper.existsRolePermission(rolePermissionReq.getRoleName(), rolePermissionReq.getPermissionStr()); if (count <= 0) { throw new BusinessException("角色[" + rolePermissionReq.getRoleName() + "]未拥有权限[" + rolePermissionReq.getPermissionStr() + "]"); } roleMapper.delPermission(rolePermissionReq.getRoleName(), rolePermissionReq.getPermissionStr()); // 计算受影响的用户 更新Session reLoadSessionService.onChangeRole(rolePermissionReq.getRoleName()); // 构造返回数据 RoleBindPermissionRes res = new RoleBindPermissionRes(); res.setRoleName(rolePermissionReq.getRoleName()); res.setPermissionList(roleMapper.findPermissionByRoleName(rolePermissionReq.getRoleName())); return res; } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/exception/ConcurrentLoginException.java<|end_filename|> package org.clever.security.exception; import org.springframework.security.core.AuthenticationException; /** * 并发登录异常 * <p> * 作者: lzw<br/> * 创建时间:2018-11-19 20:41 <br/> */ public class ConcurrentLoginException extends AuthenticationException { public ConcurrentLoginException(String msg) { super(msg); } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/entity/User.java<|end_filename|> package org.clever.security.entity; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * 用户表(User)实体类 * * @author lizw * @since 2018-09-16 21:24:44 */ @Data public class User implements Serializable { private static final long serialVersionUID = -73828129880873228L; /** * 主键id */ private Long id; /** * 登录名(一条记录的手机号不能当另一条记录的用户名用) */ private String username; /** * 密码 */ private String password; /** * 用户类型,0:系统内建,1:外部系统用户 */ private Integer userType; /** * 手机号 */ private String telephone; /** * 邮箱 */ private String email; /** * 帐号过期时间 */ private Date expiredTime; /** * 帐号是否锁定,0:未锁定;1:锁定 */ private Integer locked; /** * 是否启用,0:禁用;1:启用 */ private Integer enabled; /** * 说明 */ private String description; /** * 创建时间 */ private Date createAt; /** * 更新时间 */ private Date updateAt; } <|start_filename|>clever-security-server/src/main/java/org/clever/security/service/impl/SessionSecurityContextService.java<|end_filename|> package org.clever.security.service.impl; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.clever.security.entity.*; import org.clever.security.mapper.RememberMeTokenMapper; import org.clever.security.mapper.ServiceSysMapper; import org.clever.security.mapper.UserLoginLogMapper; import org.clever.security.mapper.UserMapper; import org.clever.security.model.LoginUserDetails; import org.clever.security.model.UserAuthority; import org.clever.security.service.ISecurityContextService; import org.clever.security.token.SecurityContextToken; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.session.FindByIndexNameSessionRepository; import org.springframework.session.data.redis.RedisOperationsSessionRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.*; /** * 作者: lzw<br/> * 创建时间:2018-11-22 19:33 <br/> */ @SuppressWarnings("Duplicates") @Transactional(readOnly = true) @Service("sessionSecurityContextService") @Slf4j public class SessionSecurityContextService implements ISecurityContextService { private static final String SPRING_SECURITY_CONTEXT = "sessionAttr:SPRING_SECURITY_CONTEXT"; @Autowired private ServiceSysMapper serviceSysMapper; @Autowired private UserMapper userMapper; @Autowired private UserLoginLogMapper userLoginLogMapper; @Autowired private RememberMeTokenMapper rememberMeTokenMapper; @Autowired private RedisOperationsSessionRepository sessionRepository; /** * 参考 RedisOperationsSessionRepository#getPrincipalKey */ private String getPrincipalKey(String redisNameSpace, String userName) { // {redisNameSpace}:{index}:{PRINCIPAL_NAME_INDEX_NAME}:{userName} // spring:session:clever-security:index:org.springframework.session.FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME:lizw return redisNameSpace + ":index:" + FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME + ":" + userName; } /** * 获取SessionKey */ private String getSessionKey(String redisNameSpace, String sessionId) { // {redisNameSpace}:{sessions}:{sessionId} // spring:session:clever-security:sessions:962e63c3-4e2e-4089-94f1-02a9137661b4 return redisNameSpace + ":sessions:" + sessionId; } private LoginUserDetails loadUserLoginToken(String sysName, String userName) { // 获取用所有权限 User user = userMapper.getByUnique(userName); if (user == null) { return null; } List<Permission> permissionList = userMapper.findByUsername(userName, sysName); LoginUserDetails userDetails = new LoginUserDetails(user); for (Permission permission : permissionList) { userDetails.getAuthorities().add(new UserAuthority(permission.getPermissionStr(), permission.getTitle())); } // TODO 加载角色 // userDetails.getRoles().add(); return userDetails; } // /** // * 加载用户安全信息 // * // * @param sysName 系统名 // * @param userName 用户名 // * @return 不存在返回null // */ // private SecurityContextToken loadUserLoginToken(BaseLoginToken loginToken, String sysName, String userName) { // // 获取用所有权限 // User user = userMapper.getByUnique(userName); // if (user == null) { // return null; // } // List<Permission> permissionList = userMapper.findByUsername(userName, sysName); // LoginUserDetails userDetails = new LoginUserDetails(user); // for (Permission permission : permissionList) { // userDetails.getAuthorities().add(new UserAuthority(permission.getPermissionStr(), permission.getTitle())); // } // // TODO 加载角色 // // userDetails.getRoles().add(); // // 组装 UserLoginToken // return new SecurityContextToken(loginToken, userDetails); // } /** * 加载用户安全信息 * * @param newUserLoginToken 新的Token * @param oldUserLoginToken 旧的Token */ private SecurityContext loadSecurityContext(SecurityContextToken newUserLoginToken, SecurityContextToken oldUserLoginToken) { newUserLoginToken.setDetails(oldUserLoginToken.getDetails()); newUserLoginToken.eraseCredentials(); // 组装 SecurityContext return new SecurityContextImpl(newUserLoginToken); } @Override public Map<String, SecurityContext> getSecurityContext(String sysName, String userName) { ServiceSys serviceSys = serviceSysMapper.getBySysName(sysName); if (serviceSys == null || StringUtils.isBlank(serviceSys.getRedisNameSpace()) || !Objects.equals(EnumConstant.ServiceSys_LoginModel_0, serviceSys.getLoginModel())) { return null; } String principalKey = getPrincipalKey(serviceSys.getRedisNameSpace(), userName); Set<Object> sessionIds = sessionRepository.getSessionRedisOperations().boundSetOps(principalKey).members(); if (sessionIds == null) { return null; } Map<String, SecurityContext> map = new HashMap<>(); for (Object sessionId : sessionIds) { if (sessionId == null || StringUtils.isBlank(sessionId.toString())) { continue; } String sessionKey = getSessionKey(serviceSys.getRedisNameSpace(), sessionId.toString()); Object securityObject = sessionRepository.getSessionRedisOperations().boundHashOps(sessionKey).get(SPRING_SECURITY_CONTEXT); SecurityContext securityContext = null; if (securityObject instanceof SecurityContext) { securityContext = (SecurityContext) securityObject; } map.put(sessionId.toString(), securityContext); } return map; } @Override public SecurityContext getSecurityContext(String sessionId) { if (sessionId == null || StringUtils.isBlank(sessionId)) { return null; } UserLoginLog userLoginLog = userLoginLogMapper.getBySessionId(sessionId); if (userLoginLog == null || StringUtils.isBlank(userLoginLog.getSysName())) { return null; } ServiceSys serviceSys = serviceSysMapper.getBySysName(userLoginLog.getSysName()); if (serviceSys == null || StringUtils.isBlank(serviceSys.getRedisNameSpace())) { return null; } String sessionKey = getSessionKey(serviceSys.getRedisNameSpace(), sessionId); Object securityObject = sessionRepository.getSessionRedisOperations().boundHashOps(sessionKey).get(SPRING_SECURITY_CONTEXT); if (securityObject instanceof SecurityContext) { return (SecurityContext) securityObject; } return null; } @Override public List<SecurityContext> reloadSecurityContext(String sysName, String userName) { List<SecurityContext> newSecurityContextList = new ArrayList<>(); ServiceSys serviceSys = serviceSysMapper.getBySysName(sysName); if (serviceSys == null || StringUtils.isBlank(serviceSys.getRedisNameSpace()) || !Objects.equals(EnumConstant.ServiceSys_LoginModel_0, serviceSys.getLoginModel())) { return null; } String principalKey = getPrincipalKey(serviceSys.getRedisNameSpace(), userName); Set<Object> sessionIds = sessionRepository.getSessionRedisOperations().boundSetOps(principalKey).members(); if (sessionIds == null) { return null; } LoginUserDetails loginUserDetails = null; for (Object sessionId : sessionIds) { if (sessionId == null || StringUtils.isBlank(sessionId.toString())) { continue; } String sessionKey = getSessionKey(serviceSys.getRedisNameSpace(), sessionId.toString()); Object securityObject = sessionRepository.getSessionRedisOperations().boundHashOps(sessionKey).get(SPRING_SECURITY_CONTEXT); if (!(securityObject instanceof SecurityContext)) { log.error("重新加载SecurityContext失败, SecurityContext类型错误,{}", securityObject == null ? "null" : securityObject.getClass()); continue; } SecurityContext oldSecurityContext = (SecurityContext) securityObject; if (!(oldSecurityContext.getAuthentication() instanceof SecurityContextToken)) { log.error("重新加载SecurityContext失败, Authentication类型错误,{}", oldSecurityContext.getAuthentication().getClass()); continue; } SecurityContextToken oldUserLoginToken = (SecurityContextToken) oldSecurityContext.getAuthentication(); if (loginUserDetails == null) { loginUserDetails = loadUserLoginToken(sysName, userName); if (loginUserDetails == null) { return null; } } SecurityContextToken newUserLoginToken = new SecurityContextToken(oldUserLoginToken.getLoginToken(), loginUserDetails); SecurityContext newSecurityContext = loadSecurityContext(newUserLoginToken, oldUserLoginToken); sessionRepository.getSessionRedisOperations().boundHashOps(sessionKey).put(SPRING_SECURITY_CONTEXT, newSecurityContext); newSecurityContextList.add(newSecurityContext); } return newSecurityContextList; } @Override public Map<String, List<SecurityContext>> reloadSecurityContext(String userName) { Map<String, List<SecurityContext>> result = new HashMap<>(); List<ServiceSys> sysList = userMapper.findSysByUsername(userName); if (sysList == null || sysList.size() <= 0) { return result; } for (ServiceSys serviceSys : sysList) { if (serviceSys == null || StringUtils.isBlank(serviceSys.getRedisNameSpace()) || !Objects.equals(EnumConstant.ServiceSys_LoginModel_0, serviceSys.getLoginModel())) { return null; } List<SecurityContext> securityContextList = reloadSecurityContext(serviceSys.getSysName(), userName); result.put(serviceSys.getSysName(), securityContextList); } return result; } @Transactional @Override public int forcedOffline(String sysName, String userName) { int count = 0; ServiceSys serviceSys = serviceSysMapper.getBySysName(sysName); if (serviceSys == null || StringUtils.isBlank(serviceSys.getRedisNameSpace()) || !Objects.equals(EnumConstant.ServiceSys_LoginModel_0, serviceSys.getLoginModel())) { return 0; } String principalKey = getPrincipalKey(serviceSys.getRedisNameSpace(), userName); Set<Object> sessionIds = sessionRepository.getSessionRedisOperations().boundSetOps(principalKey).members(); if (sessionIds == null) { return 0; } // 删除 RememberMe Token rememberMeTokenMapper.deleteBySysNameAndUsername(sysName, userName); // 删除Session for (Object sessionId : sessionIds) { if (sessionId == null || StringUtils.isBlank(sessionId.toString())) { continue; } count++; sessionRepository.deleteById(sessionId.toString()); } return count; } @Override public void delSession(String userName) { List<ServiceSys> sysList = userMapper.findSysByUsername(userName); if (sysList == null || sysList.size() <= 0) { return; } for (ServiceSys serviceSys : sysList) { if (serviceSys == null || StringUtils.isBlank(serviceSys.getRedisNameSpace()) || !Objects.equals(EnumConstant.ServiceSys_LoginModel_0, serviceSys.getLoginModel())) { continue; } delSession(serviceSys.getSysName(), userName); } } @Override public void delSession(String sysName, String userName) { ServiceSys serviceSys = serviceSysMapper.getBySysName(sysName); if (serviceSys == null || StringUtils.isBlank(serviceSys.getRedisNameSpace()) || !Objects.equals(EnumConstant.ServiceSys_LoginModel_0, serviceSys.getLoginModel())) { return; } String principalKey = getPrincipalKey(serviceSys.getRedisNameSpace(), userName); Set<Object> sessionIds = sessionRepository.getSessionRedisOperations().boundSetOps(principalKey).members(); if (sessionIds == null) { return; } for (Object sessionId : sessionIds) { if (sessionId == null || StringUtils.isBlank(sessionId.toString())) { continue; } sessionRepository.deleteById(sessionId.toString()); } } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/init/InitSystemUrlPermissionJob.java<|end_filename|> package org.clever.security.init; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.clever.common.utils.GlobalJob; import org.clever.common.utils.IDCreateUtils; import org.clever.common.utils.reflection.ReflectionsUtils; import org.clever.security.LoginModel; import org.clever.security.annotation.UrlAuthorization; import org.clever.security.client.ServiceSysClient; import org.clever.security.client.WebPermissionClient; import org.clever.security.config.SecurityConfig; import org.clever.security.dto.request.ServiceSysAddReq; import org.clever.security.dto.request.WebPermissionInitReq; import org.clever.security.dto.response.WebPermissionInitRes; import org.clever.security.entity.EnumConstant; import org.clever.security.entity.ServiceSys; import org.clever.security.entity.model.WebPermissionModel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration; import org.springframework.stereotype.Component; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.mvc.method.RequestMappingInfo; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; import java.lang.reflect.Method; import java.util.*; /** * 作者: lzw<br/> * 创建时间:2018-11-11 14:42 <br/> */ @Component @Slf4j public class InitSystemUrlPermissionJob extends GlobalJob { @Autowired private SecurityConfig securityConfig; @Autowired private RequestMappingHandlerMapping handlerMapping; @Autowired(required = false) private RedisHttpSessionConfiguration redisHttpSessionConfiguration; @Autowired private ServiceSysClient serviceSysClient; @Autowired private WebPermissionClient webPermissionClient; @Override protected void exceptionHandle(Throwable e) { log.info("### [系统权限初始化] 初始化系统的所有Url权限异常", e); // throw ExceptionUtils.unchecked(e); } @Override protected void internalExecute() { log.info("### [系统权限初始化] 开始初始化..."); // 注册系统信息 ServiceSysAddReq serviceSysAddReq = new ServiceSysAddReq(); serviceSysAddReq.setSysName(securityConfig.getSysName()); if (LoginModel.jwt.equals(securityConfig.getLoginModel())) { // JwtToken serviceSysAddReq.setRedisNameSpace(securityConfig.getTokenConfig().getRedisNamespace()); serviceSysAddReq.setLoginModel(EnumConstant.ServiceSys_LoginModel_1); } else if (LoginModel.session.equals(securityConfig.getLoginModel())) { // Session serviceSysAddReq.setRedisNameSpace(ReflectionsUtils.getFieldValue(redisHttpSessionConfiguration, "redisNamespace").toString()); serviceSysAddReq.setLoginModel(EnumConstant.ServiceSys_LoginModel_0); } else { throw new IllegalArgumentException("配置项[loginModel - 登入模式]必须指定"); } ServiceSys serviceSys = serviceSysClient.registerSys(serviceSysAddReq); log.info("### 注册系统成功: {}", serviceSys); // 获取系统中所有的资源,并排序 - allPermission List<WebPermissionModel> allPermission = new ArrayList<>(); Map<RequestMappingInfo, HandlerMethod> handlerMap = handlerMapping.getHandlerMethods(); for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMap.entrySet()) { RequestMappingInfo requestMappingInfo = entry.getKey(); HandlerMethod handlerMethod = entry.getValue(); // 获取URL路由信息 allPermission.add(newPermissions(requestMappingInfo, handlerMethod)); } Collections.sort(allPermission); // 初始化某个系统的所有Web权限 WebPermissionInitReq req = new WebPermissionInitReq(); req.setAllPermission(allPermission); WebPermissionInitRes res = webPermissionClient.initWebPermission(securityConfig.getSysName(), req); // 打印相应的日志 if (log.isInfoEnabled()) { StringBuilder strTmp = new StringBuilder(); strTmp.append("\r\n"); strTmp.append("#=======================================================================================================================#\r\n"); strTmp .append("# 系统注册信息:").append(serviceSys.toString()).append("\n") .append("# 新增的权限配置如下(") .append(res.getAddPermission().size()) .append("条):") .append("\t\t---> ") .append(securityConfig.getDefaultNeedAuthorization() ? "需要授权" : "不需要授权") .append("\r\n"); for (WebPermissionModel permission : res.getAddPermission()) { strTmp.append("#\t ").append(getPermissionStr(permission)).append("\r\n"); } strTmp.append("# 数据库里无效的权限配置(").append(res.getNotExistPermission().size()).append("条):\r\n"); for (WebPermissionModel permission : res.getNotExistPermission()) { strTmp.append("#\t ").append(getPermissionStr(permission)).append("\r\n"); } strTmp.append("#=======================================================================================================================#"); log.info(strTmp.toString()); } } /** * 打印权限配置信息字符串 */ private String getPermissionStr(WebPermissionModel permission) { return String.format("| %1$s | [%2$s] [%3$s#%4$s] -> [%5$s]", permission.getSysName(), permission.getTitle(), permission.getTargetClass(), permission.getTargetMethod(), permission.getResourcesUrl()); } /** * 创建一个 Permission */ @SuppressWarnings("deprecation") private WebPermissionModel newPermissions(RequestMappingInfo requestMappingInfo, HandlerMethod handlerMethod) { // 提取MVC路由信息 Class<?> beanType = handlerMethod.getBeanType(); Method method = handlerMethod.getMethod(); // 获取标题 String titlePrefix = beanType.getSimpleName(); String titleSuffix = method.getName(); UrlAuthorization urlAuthorizationForClass = beanType.getAnnotation(UrlAuthorization.class); Api api = beanType.getAnnotation(Api.class); if (urlAuthorizationForClass != null && StringUtils.isNotBlank(urlAuthorizationForClass.title())) { titlePrefix = urlAuthorizationForClass.title(); } else if (api != null && (StringUtils.isNotBlank(api.value()) || StringUtils.isNotBlank(api.description()))) { titlePrefix = StringUtils.isNotBlank(api.value()) ? api.value() : api.description(); } UrlAuthorization urlAuthorizationForMethod = handlerMethod.getMethodAnnotation(UrlAuthorization.class); ApiOperation apiOperation = handlerMethod.getMethodAnnotation(ApiOperation.class); if (urlAuthorizationForMethod != null && StringUtils.isNotBlank(urlAuthorizationForMethod.title())) { titleSuffix = urlAuthorizationForMethod.title(); } else if (apiOperation != null && StringUtils.isNotBlank(apiOperation.value())) { titleSuffix = apiOperation.value(); } String title = String.format("[%1$s]-%2$s", titlePrefix, titleSuffix); // 获取资源说明 String description = "系统自动生成的权限配置"; if (urlAuthorizationForMethod != null && StringUtils.isNotBlank(urlAuthorizationForMethod.description())) { description = urlAuthorizationForMethod.description(); } else if (apiOperation != null && StringUtils.isNotBlank(apiOperation.notes())) { description = apiOperation.notes(); } // 获取资源字符串 String permissionStr = "[auto]:" + IDCreateUtils.shortUuid(); String permissionStrPrefix = ""; if (urlAuthorizationForClass != null && StringUtils.isNotBlank(urlAuthorizationForClass.permissionStr())) { permissionStrPrefix = urlAuthorizationForClass.permissionStr(); } if (urlAuthorizationForMethod != null && StringUtils.isNotBlank(urlAuthorizationForMethod.permissionStr())) { if (StringUtils.isBlank(permissionStrPrefix)) { permissionStr = urlAuthorizationForMethod.permissionStr(); } else { permissionStr = String.format("[%1$s]%2$s", permissionStrPrefix, urlAuthorizationForMethod.permissionStr()); } } // 获取方法参数签名 StringBuilder methodParams = new StringBuilder(); Class<?>[] paramTypes = method.getParameterTypes(); for (Class<?> clzz : paramTypes) { if (methodParams.length() > 0) { methodParams.append(", "); } methodParams.append(clzz.getName()); } // 请求Url StringBuilder resourcesUrl = new StringBuilder(); Set<String> urlArray = requestMappingInfo.getPatternsCondition().getPatterns(); for (String url : urlArray) { if (resourcesUrl.length() > 0) { resourcesUrl.append(" | "); } resourcesUrl.append(url); } // 构建权限信息 WebPermissionModel permission = new WebPermissionModel(); permission.setSysName(securityConfig.getSysName()); permission.setPermissionStr(permissionStr); if (securityConfig.getDefaultNeedAuthorization() != null && securityConfig.getDefaultNeedAuthorization()) { permission.setNeedAuthorization(EnumConstant.Permission_NeedAuthorization_1); } else { permission.setNeedAuthorization(EnumConstant.Permission_NeedAuthorization_2); } permission.setResourcesType(EnumConstant.Permission_ResourcesType_1); permission.setTitle(title); permission.setTargetClass(beanType.getName()); permission.setTargetMethod(method.getName()); permission.setTargetMethodParams(methodParams.toString()); permission.setResourcesUrl(resourcesUrl.toString()); permission.setTargetExist(EnumConstant.WebPermission_targetExist_1); permission.setDescription(description); permission.setCreateAt(new Date()); return permission; } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/config/SecurityConfig.java<|end_filename|> package org.clever.security.config; import lombok.Data; import org.clever.security.Constant; import org.clever.security.LoginModel; import org.clever.security.config.model.*; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-03-15 14:31 <br/> */ @ConfigurationProperties(prefix = Constant.ConfigPrefix) @Component @Data public class SecurityConfig { /** * 登入模式 */ private LoginModel loginModel = LoginModel.jwt; /** * 启用Spring Security调试功能 */ private Boolean enableDebug = false; /** * 系统名称 */ private String sysName; /** * 等待spring容器初始化次数(用于系统启动之后初始化系统权限) */ private Integer waitSpringContextInitCount = 0; /** * 是否需要控制Web资源权限,默认true(true 需要;false 不要) */ private Boolean defaultNeedAuthorization = true; /** * 不需要认证的URL */ private List<String> ignoreUrls = new ArrayList<>(); /** * 不需要授权的URL */ private List<String> ignoreAuthorizationUrls = new ArrayList<>(); /** * 隐藏登录用户找不到的异常 */ private Boolean hideUserNotFoundExceptions = true; /** * 未登录时是否需要跳转 */ private Boolean notLoginNeedForward = false; /** * 无权访问时是否需要跳转 */ private Boolean forbiddenNeedForward = false; /** * 无权访问时跳转页面(请求转发) */ private String forbiddenForwardPage = "/403.html"; /** * Session 过期需要跳转的地址,值为空就不跳转 */ private String sessionExpiredRedirectUrl = "/index.html"; // ---------------------------------------------------------------------------------------- /** * 用户登录相关配置 */ @NestedConfigurationProperty private final LoginConfig login = new LoginConfig(); /** * 用户登出相关配置 */ @NestedConfigurationProperty private final LogoutConfig logout = new LogoutConfig(); /** * 用户登录请求参数加密配置 Aes Key */ @NestedConfigurationProperty private final AesKeyConfig loginReqAesKey = new AesKeyConfig(); /** * "记住我"相关配置 */ @NestedConfigurationProperty private final RememberMeConfig rememberMe = new RememberMeConfig(); /** * token配置(只有JWT Token有效) */ @NestedConfigurationProperty private final TokenConfig tokenConfig = new TokenConfig(); /** * 服务间免登陆Token访问配置 */ @NestedConfigurationProperty private ServerApiAccessToken serverApiAccessToken = new ServerApiAccessToken(); } <|start_filename|>clever-security-model/src/main/java/org/clever/security/entity/model/UserRememberMeToken.java<|end_filename|> package org.clever.security.entity.model; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * 作者: lzw<br/> * 创建时间:2018-10-21 21:59 <br/> */ @Data public class UserRememberMeToken implements Serializable { /** * 主键id */ private Long id; /** * 系统(或服务)名称 */ private String sysName; /** * token序列号 */ private String series; /** * 用户登录名 */ private String username; /** * token数据 */ private String token; /** * 最后使用时间 */ private Date lastUsed; /** * 创建时间 */ private Date createAt; /** * 更新时间 */ private Date updateAt; // ----------------------------------------------------------------------------- User /** * 主键id */ private Long userId; /** * 用户类型,0:系统内建,1:外部系统用户 */ private Integer userType; /** * 手机号 */ private String telephone; /** * 邮箱 */ private String email; /** * 帐号过期时间 */ private Date expiredTime; /** * 帐号是否锁定,0:未锁定;1:锁定 */ private Integer locked; /** * 是否启用,0:禁用;1:启用 */ private Integer enabled; /** * 说明 */ private String description; } <|start_filename|>clever-security-model/src/main/java/org/clever/security/entity/RememberMeToken.java<|end_filename|> package org.clever.security.entity; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * “记住我”功能的token(RememberMeToken)实体类 * * @author lizw * @since 2018-09-21 20:10:31 */ @Data public class RememberMeToken implements Serializable { private static final long serialVersionUID = -57228137236940071L; /** 主键id */ private Long id; /** 系统(或服务)名称 */ private String sysName; /** token序列号 */ private String series; /** 用户登录名 */ private String username; /** token数据 */ private String token; /** 最后使用时间 */ private Date lastUsed; /** 创建时间 */ private Date createAt; /** 更新时间 */ private Date updateAt; } <|start_filename|>clever-security-server/src/main/java/org/clever/security/mapper/WebPermissionMapper.java<|end_filename|> package org.clever.security.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.clever.security.entity.WebPermission; import org.clever.security.entity.model.WebPermissionModel; import org.springframework.stereotype.Repository; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-09-17 9:13 <br/> */ @Repository @Mapper public interface WebPermissionMapper extends BaseMapper<WebPermission> { WebPermissionModel getBySysNameAndTarget( @Param("sysName") String sysName, @Param("targetClass") String targetClass, @Param("targetMethod") String targetMethod, @Param("targetMethodParams") String targetMethodParams ); List<WebPermissionModel> findBySysName(@Param("sysName") String sysName); } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/LoginRes.java<|end_filename|> package org.clever.security.dto.response; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.response.BaseResponse; /** * 作者: lzw<br/> * 创建时间:2018-09-17 13:57 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class LoginRes extends BaseResponse { /** * 是否登录成功 */ private Boolean success; /** * 错误消息 */ private String message; /** * 时间戳 */ private Long timestamp = System.currentTimeMillis(); /** * 登录是否需要验证码 */ private Boolean needCaptcha = false; /** * 当前登录用户信息 */ private UserRes user; public LoginRes(Boolean success, String message) { this.success = success; this.message = message; } public LoginRes(Boolean success, String message, UserRes user) { this.success = success; this.message = message; this.user = user; } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/token/SecurityContextToken.java<|end_filename|> package org.clever.security.token; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.ToString; import org.clever.security.model.LoginUserDetails; import org.clever.security.token.login.BaseLoginToken; import org.springframework.security.authentication.AbstractAuthenticationToken; /** * 登录成功的Token * <p> * 作者: lzw<br/> * 创建时间:2019-04-27 20:50 <br/> */ //@JsonIgnoreProperties(value = {"details"}) @ToString(exclude = {"userDetails"}) public class SecurityContextToken extends AbstractAuthenticationToken { /** * 用户登录请求参数Token */ private BaseLoginToken loginToken; /** * 数据库中用户信息 */ private LoginUserDetails userDetails; /** * 用于创建登录成功的用户信息 */ public SecurityContextToken(BaseLoginToken loginToken, LoginUserDetails userDetails) { super(userDetails.getAuthorities()); this.loginToken = loginToken; this.userDetails = userDetails; super.setAuthenticated(true); } /** * 获取登录凭证(password 密码) */ @Override public Object getCredentials() { return loginToken; } /** * 获取登录的用户信息 */ @Override public Object getPrincipal() { return userDetails; } @Override public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { if (isAuthenticated == this.isAuthenticated()) { return; } if (isAuthenticated) { throw new IllegalArgumentException("Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead"); } super.setAuthenticated(false); } @Override public void eraseCredentials() { super.eraseCredentials(); loginToken.eraseCredentials(); userDetails.eraseCredentials(); } @JsonIgnore public BaseLoginToken getLoginToken() { return loginToken; } @JsonIgnore public LoginUserDetails getUserDetails() { return userDetails; } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/config/model/ServerApiAccessToken.java<|end_filename|> package org.clever.security.config.model; import lombok.Data; /** * 服务间免登陆Token访问配置 * 作者: lzw<br/> * 创建时间:2019-05-16 11:07 <br/> */ @Data public class ServerApiAccessToken { /** * 请求头Token名称 */ private String tokenName = "ServerApiToken"; /** * 请求头Token值 */ private String tokenValue; } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/WebPermissionInitReq.java<|end_filename|> package org.clever.security.dto.request; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.request.BaseRequest; import org.clever.security.entity.model.WebPermissionModel; import javax.validation.constraints.NotNull; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-09-24 20:36 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class WebPermissionInitReq extends BaseRequest { @NotNull @ApiModelProperty("当前系统所有权限") private List<WebPermissionModel> allPermission; } <|start_filename|>clever-security-server/src/main/java/org/clever/security/service/WebPermissionService.java<|end_filename|> package org.clever.security.service; import lombok.extern.slf4j.Slf4j; import org.clever.common.server.service.BaseService; import org.clever.common.utils.mapper.BeanMapper; import org.clever.security.dto.request.WebPermissionInitReq; import org.clever.security.dto.request.WebPermissionModelGetReq; import org.clever.security.dto.response.WebPermissionInitRes; import org.clever.security.entity.EnumConstant; import org.clever.security.entity.Permission; import org.clever.security.entity.WebPermission; import org.clever.security.entity.model.WebPermissionModel; import org.clever.security.mapper.PermissionMapper; import org.clever.security.mapper.WebPermissionMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.*; /** * 作者: lzw<br/> * 创建时间:2018-09-20 15:53 <br/> */ @Transactional(readOnly = true) @Service @Slf4j public class WebPermissionService extends BaseService { @Autowired private PermissionMapper permissionMapper; @Autowired private WebPermissionMapper webPermissionMapper; /** * 保存Web权限 */ @Transactional public void saveWebPermission(WebPermissionModel webPermissionModel) { Permission permission = BeanMapper.mapper(webPermissionModel, Permission.class); WebPermission webPermission = BeanMapper.mapper(webPermissionModel, WebPermission.class); permissionMapper.insert(permission); webPermissionMapper.insert(webPermission); } public WebPermissionModel getWebPermissionModel(WebPermissionModelGetReq req) { return webPermissionMapper.getBySysNameAndTarget( req.getSysName(), req.getTargetClass(), req.getTargetMethod(), req.getTargetMethodParams() ); } public List<WebPermissionModel> findAllWebPermissionModel(String sysName) { return webPermissionMapper.findBySysName(sysName); } /** * 初始化某个系统的所有Web权限 */ @Transactional public WebPermissionInitRes initWebPermission(String sysName, WebPermissionInitReq req) { List<WebPermissionModel> allPermission = req.getAllPermission(); // 校验数据正确 for (WebPermissionModel webPermissionModel : allPermission) { webPermissionModel.check(); } // 排序 Collections.sort(allPermission); // 加载当前模块所有的权限信息 - moduleAllPermission List<WebPermissionModel> moduleAllPermission = webPermissionMapper.findBySysName(sysName); // 保存系统中有而数据库里没有的资源 - addPermission List<WebPermissionModel> addPermission = this.addPermission(allPermission, moduleAllPermission); // 统计数据库中有而系统中没有的资源数据 - notExistPermission moduleAllPermission = webPermissionMapper.findBySysName(sysName); List<WebPermissionModel> notExistPermission = this.getNotExistPermission(allPermission, moduleAllPermission); // 构造返回信息 WebPermissionInitRes res = new WebPermissionInitRes(); res.setAddPermission(addPermission); res.setNotExistPermission(notExistPermission); return res; } /** * 保存所有新增的权限 (module targetClass targetMethod resourcesUrl) * * @param allPermission 当前模块所有权限 * @param moduleAllPermission 数据库中当前模块所有的权限信息 * @return 新增的权限 */ @Transactional protected List<WebPermissionModel> addPermission(List<WebPermissionModel> allPermission, List<WebPermissionModel> moduleAllPermission) { List<WebPermissionModel> addPermission = new ArrayList<>(); Set<String> setPermission = new HashSet<>(); // module targetClass targetMethod targetMethodParams String format = "%1$-128s|%2$-255s|%3$-255s|%4$-255s"; for (WebPermissionModel permission : moduleAllPermission) { setPermission.add(String.format(format, permission.getSysName(), permission.getTargetClass(), permission.getTargetMethod(), permission.getTargetMethodParams())); } for (WebPermissionModel permission : allPermission) { String key = String.format(format, permission.getSysName(), permission.getTargetClass(), permission.getTargetMethod(), permission.getTargetMethodParams()); if (!setPermission.contains(key)) { // 新增不存在的权限配置 this.saveWebPermission(permission); addPermission.add(permission); } } return addPermission; } /** * 统计数据库中有而系统中没有的资源数据 * * @param allPermission 当前模块所有权限 * @param moduleAllPermission 数据库中当前模块所有的权限信息 * @return 数据库中有而系统中没有的资源数据 */ @Transactional protected List<WebPermissionModel> getNotExistPermission(List<WebPermissionModel> allPermission, List<WebPermissionModel> moduleAllPermission) { List<WebPermissionModel> notExistPermission = new ArrayList<>(); Map<String, WebPermissionModel> mapPermission = new HashMap<>(); // module targetClass targetMethod targetMethodParams String format = "%1$-128s|%2$-255s|%3$-255s|%4$-255s"; for (WebPermissionModel permission : allPermission) { mapPermission.put(String.format(format, permission.getSysName(), permission.getTargetClass(), permission.getTargetMethod(), permission.getTargetMethodParams()), permission); } for (WebPermissionModel dbPermission : moduleAllPermission) { String key = String.format(format, dbPermission.getSysName(), dbPermission.getTargetClass(), dbPermission.getTargetMethod(), dbPermission.getTargetMethodParams()); WebPermissionModel permission = mapPermission.get(key); if (permission == null) { // 数据库里有 系统中没有 - 更新 targetExist if (!Objects.equals(dbPermission.getTargetExist(), EnumConstant.WebPermission_targetExist_0)) { WebPermission update = new WebPermission(); update.setId(dbPermission.getWebPermissionId()); update.setTargetExist(EnumConstant.WebPermission_targetExist_0); update.setUpdateAt(new Date()); webPermissionMapper.updateById(update); } notExistPermission.add(dbPermission); } else { // 数据库里有 系统中也有 - 更新 resourcesUrl boolean permissionStrChange = !Objects.equals(permission.getPermissionStr(), dbPermission.getPermissionStr()) && !(dbPermission.getPermissionStr().startsWith("[auto]:") && permission.getPermissionStr().startsWith("[auto]:")); if (!Objects.equals(permission.getResourcesUrl(), dbPermission.getResourcesUrl()) || permissionStrChange) { WebPermission update = new WebPermission(); update.setId(dbPermission.getPermissionId()); update.setResourcesUrl(permission.getResourcesUrl()); update.setPermissionStr(permission.getPermissionStr()); webPermissionMapper.updateById(update); } if (!Objects.equals(permission.getTitle(), dbPermission.getTitle()) || !Objects.equals(permission.getDescription(), dbPermission.getDescription()) || permissionStrChange) { Permission update = new Permission(); update.setId(dbPermission.getPermissionId()); update.setTitle(permission.getTitle()); update.setDescription(permission.getDescription()); update.setPermissionStr(permission.getPermissionStr()); permissionMapper.updateById(update); } } } return notExistPermission; } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/ServiceSysQueryReq.java<|end_filename|> package org.clever.security.dto.request; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.request.QueryByPage; /** * 作者: lzw<br/> * 创建时间:2018-11-25 20:09 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class ServiceSysQueryReq extends QueryByPage { @ApiModelProperty("系统(或服务)名称") private String sysName; @ApiModelProperty("登录类型,0:sesion-cookie,1:jwt-token") private Integer loginModel; } <|start_filename|>clever-security-model/src/main/java/org/clever/security/LoginTypeConstant.java<|end_filename|> package org.clever.security; /** * 登录类型字符串常量 * <p> * 作者: lzw<br/> * 创建时间:2019-04-27 21:50 <br/> */ public class LoginTypeConstant { /** * 使用"记住我"功能自动登录登录 */ public static final String RememberMe = "RememberMe"; /** * 使用用户名密码登录 */ public static final String UsernamePassword = "<PASSWORD>"; /** * 使用手机号验证码登录 */ public static final String TelephoneCode = "TelephoneCode"; } <|start_filename|>clever-security-model/src/main/java/org/clever/security/LoginModel.java<|end_filename|> package org.clever.security; /** * 作者: lzw<br/> * 创建时间:2019-04-25 19:51 <br/> */ public enum LoginModel { /** * session-cookie */ session, /** * jwt-token */ jwt, } <|start_filename|>clever-security-server/src/main/java/org/clever/security/service/internal/ManageCryptoService.java<|end_filename|> package org.clever.security.service.internal; import lombok.extern.slf4j.Slf4j; import org.clever.common.utils.codec.CryptoUtils; import org.clever.common.utils.codec.EncodeDecodeUtils; import org.clever.security.config.GlobalConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Component; /** * 管理系统敏感数据加密-解密 * 作者: lzw<br/> * 创建时间:2018-11-12 9:29 <br/> */ @Component @Slf4j public class ManageCryptoService { @Autowired private GlobalConfig globalConfig; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; /** * 请求数据 AES 加密 * * @return Base64编码密码 */ public String reqAesEncrypt(String input) { try { byte[] passwordData = input.getBytes(); byte[] key = EncodeDecodeUtils.decodeHex(globalConfig.getReqAesKey()); byte[] iv = EncodeDecodeUtils.decodeHex(globalConfig.getReqAesIv()); return EncodeDecodeUtils.encodeBase64(CryptoUtils.aesEncrypt(passwordData, key, iv)); } catch (Exception e) { throw new BadCredentialsException("请求密码加密失败"); } } /** * 请求数据 AES 解密 * * @param input Base64编码密码 */ public String reqAesDecrypt(String input) { try { byte[] passwordData = EncodeDecodeUtils.decodeBase64(input); byte[] key = EncodeDecodeUtils.decodeHex(globalConfig.getReqAesKey()); byte[] iv = EncodeDecodeUtils.decodeHex(globalConfig.getReqAesIv()); return CryptoUtils.aesDecrypt(passwordData, key, iv); } catch (Exception e) { throw new BadCredentialsException("请求密码解密失败"); } } /** * 存储数据 加密 */ public String dbEncode(String input) { try { return bCryptPasswordEncoder.encode(input); } catch (Exception e) { throw new BadCredentialsException("存储密码加密失败"); } } /** * 数据库加密数据匹配 */ public boolean dbMatches(String str1, String str2) { try { return bCryptPasswordEncoder.matches(str1, str2); } catch (Exception e) { throw new BadCredentialsException("存储密码解密失败"); } } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/model/CaptchaInfo.java<|end_filename|> package org.clever.security.model; import lombok.Data; import java.io.Serializable; /** * 验证码信息 * 作者: lzw<br/> * 创建时间:2018-09-19 21:34 <br/> */ @Data public class CaptchaInfo implements Serializable { /** * 验证码 */ private String code; /** * 创建时间戳(毫秒) */ private Long createTime; /** * 有效时间(毫秒) */ private Long effectiveTime; /** * 验证码文件图片签名 */ private String imageDigest; /** * 默认构造 */ public CaptchaInfo() { createTime = System.currentTimeMillis(); } /** * Session 登录模式使用 * * @param code 验证码 * @param effectiveTime 有效时间(毫秒) */ public CaptchaInfo(String code, Long effectiveTime) { this.code = code; this.createTime = System.currentTimeMillis(); this.effectiveTime = effectiveTime; } /** * JWT Token 登录模式使用 * * @param code 验证码 * @param effectiveTime 有效时间(毫秒) * @param imageDigest 验证码文件图片签名 */ public CaptchaInfo(String code, Long effectiveTime, String imageDigest) { this.code = code; this.createTime = System.currentTimeMillis(); this.effectiveTime = effectiveTime; this.imageDigest = imageDigest; } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/RoleInfoRes.java<|end_filename|> package org.clever.security.dto.response; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.response.BaseResponse; import org.clever.security.entity.Permission; import java.util.Date; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-10-03 9:35 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class RoleInfoRes extends BaseResponse { @ApiModelProperty("主键id") private Long id; @ApiModelProperty("角色名称") private String name; @ApiModelProperty("角色说明") private String description; @ApiModelProperty("创建时间") private Date createAt; @ApiModelProperty("更新时间") private Date updateAt; @ApiModelProperty("拥有权限") private List<Permission> permissionList; } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/AccessDeniedRes.java<|end_filename|> package org.clever.security.dto.response; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.response.BaseResponse; /** * 作者: lzw<br/> * 创建时间:2018-03-18 15:19 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class AccessDeniedRes extends BaseResponse { /** * 错误消息 */ private String message = "没有访问权限"; /** * 时间戳 */ private Long timestamp = System.currentTimeMillis(); public AccessDeniedRes() { } public AccessDeniedRes(String message) { this.message = message; } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/response/WebPermissionInitRes.java<|end_filename|> package org.clever.security.dto.response; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.response.BaseResponse; import org.clever.security.entity.model.WebPermissionModel; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-09-24 20:45 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class WebPermissionInitRes extends BaseResponse { @ApiModelProperty("新增的权限") private List<WebPermissionModel> addPermission; @ApiModelProperty("数据库里存在,系统中不存在的权限") private List<WebPermissionModel> notExistPermission; } <|start_filename|>clever-security-server/src/main/java/org/clever/security/controller/WebPermissionController.java<|end_filename|> package org.clever.security.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.clever.common.server.controller.BaseController; import org.clever.security.dto.request.WebPermissionInitReq; import org.clever.security.dto.request.WebPermissionModelGetReq; import org.clever.security.dto.response.WebPermissionInitRes; import org.clever.security.entity.model.WebPermissionModel; import org.clever.security.service.WebPermissionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-09-24 18:59 <br/> */ @Api("Web权限") @RestController @RequestMapping("/api") public class WebPermissionController extends BaseController { @Autowired private WebPermissionService webPermissionService; @ApiOperation("根据系统和Controller信息查询Web权限") @GetMapping("/web_permission") public WebPermissionModel getWebPermissionModel(@Validated WebPermissionModelGetReq req) { return webPermissionService.getWebPermissionModel(req); } @ApiOperation("查询某个系统的所有Web权限") @GetMapping("/web_permission/{sysName}") public List<WebPermissionModel> findAllWebPermissionModel(@PathVariable("sysName") String sysName) { return webPermissionService.findAllWebPermissionModel(sysName); } @ApiOperation("初始化某个系统的所有Web权限") @PostMapping("/web_permission/{sysName}") public WebPermissionInitRes initWebPermission(@PathVariable("sysName") String sysName, @RequestBody @Validated WebPermissionInitReq req) { return webPermissionService.initWebPermission(sysName, req); } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/entity/model/UserLoginLogModel.java<|end_filename|> package org.clever.security.entity.model; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * 作者: lzw<br/> * 创建时间:2018-10-21 22:11 <br/> */ @Data public class UserLoginLogModel implements Serializable { /** * 主键id */ private Long id; /** * 系统(或服务)名称 */ private String sysName; /** * 用户登录名 */ private String username; /** * 登录时间 */ private Date loginTime; /** * 登录IP */ private String loginIp; /** * 登录的用户信息 */ private String authenticationInfo; /** * 登录类型,0:sesion-cookie,1:jwt-token */ private Integer loginModel; /** * 登录SessionID */ private String sessionId; /** * 登录状态,0:未知;1:已登录;2:登录已过期 */ private Integer loginState; /** * 创建时间 */ private Date createAt; /** * 更新时间 */ private Date updateAt; // ----------------------------------------------------------------------------- User /** * 主键id */ private Long userId; /** * 用户类型,0:系统内建,1:外部系统用户 */ private Integer userType; /** * 手机号 */ private String telephone; /** * 邮箱 */ private String email; /** * 帐号过期时间 */ private Date expiredTime; /** * 帐号是否锁定,0:未锁定;1:锁定 */ private Integer locked; /** * 是否启用,0:禁用;1:启用 */ private Integer enabled; /** * 说明 */ private String description; } <|start_filename|>clever-security-model/src/main/java/org/clever/security/dto/request/UserAuthenticationReq.java<|end_filename|> package org.clever.security.dto.request; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import org.clever.common.model.request.BaseRequest; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Pattern; /** * 作者: lzw<br/> * 创建时间:2018-10-24 10:28 <br/> */ @EqualsAndHashCode(callSuper = true) @Data public class UserAuthenticationReq extends BaseRequest { public static final String LoginType_Username = "username"; public static final String LoginType_Telephone = "telephone"; @ApiModelProperty("用户登录名(登录名、手机、邮箱)") @NotBlank private String loginName; @ApiModelProperty("登录方式(username、telephone)") @Pattern(regexp = "username|telephone") private String loginType = "username"; @ApiModelProperty("验证密码(使用AES对称加密)") @NotBlank private String password; @ApiModelProperty("系统名称(选填)") private String sysName; } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/authentication/UserLoginEntryPoint.java<|end_filename|> package org.clever.security.authentication; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.clever.common.model.response.ErrorResponse; import org.clever.security.config.SecurityConfig; import org.clever.security.utils.HttpRequestUtils; import org.clever.security.utils.HttpResponseUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * 未登录访问时的处理 * <p> * 作者: lzw<br/> * 创建时间:2018-03-16 11:20 <br/> */ @Component @Slf4j public class UserLoginEntryPoint implements AuthenticationEntryPoint { @Autowired private SecurityConfig securityConfig; @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { log.info("### 未登录访问拦截,访问地址[{}] {}", request.getMethod(), request.getRequestURL().toString()); if (!securityConfig.getNotLoginNeedForward() || HttpRequestUtils.isJsonResponse(request)) { // 返回401错误 ErrorResponse errorResponse = new ErrorResponse("您还未登录,请先登录", authException, HttpServletResponse.SC_UNAUTHORIZED, request.getRequestURI()); HttpResponseUtils.sendJsonBy401(response, errorResponse); return; } // 跳转到登录页面 String redirectUrl = securityConfig.getLogin().getLoginPage(); if (StringUtils.isBlank(redirectUrl)) { redirectUrl = "/index.html"; } HttpResponseUtils.sendRedirect(response, redirectUrl); } } <|start_filename|>clever-security-model/src/main/java/org/clever/security/entity/model/WebPermissionModel.java<|end_filename|> package org.clever.security.entity.model; import lombok.Data; import org.apache.commons.lang3.StringUtils; import org.clever.common.exception.BusinessException; import org.clever.security.entity.EnumConstant; import java.io.Serializable; import java.util.Date; import java.util.Objects; /** * 作者: lzw<br/> * 创建时间:2018-09-17 16:56 <br/> */ @Data public class WebPermissionModel implements Serializable, Comparable<WebPermissionModel> { private Long permissionId; /** * 系统(或服务)名称 */ private String sysName; /** * 资源标题 */ private String title; /** * 资源访问所需要的权限标识字符串 */ private String permissionStr; /** * 资源类型(1:请求URL地址, 2:其他资源) */ private Integer resourcesType; /** * 资源说明 */ private String description; /** * 创建时间 */ private Date createAt; /** * 更新时间 */ private Date updateAt; // ---------------------------------------------------------------- private Long webPermissionId; /** * 需要授权才允许访问(1:需要;2:不需要) */ private Integer needAuthorization; /** * Spring Controller类名称 */ private String targetClass; /** * Spring Controller类的方法名称 */ private String targetMethod; /** * Spring Controller类的方法参数签名 */ private String targetMethodParams; /** * 资源URL地址 */ private String resourcesUrl; /** * Spring Controller路由资源是否存在,0:不存在;1:存在 */ private Integer targetExist; /** * 定义排序规则 */ @SuppressWarnings("NullableProblems") @Override public int compareTo(WebPermissionModel permission) { // module resourcesType targetClass targetMethod targetMethodParams title String format = "%1$-128s|%2$-20s|%3$-255s|%4$-255s|%5$-255s|%6$-255s"; String strA = String.format(format, this.getSysName(), this.getResourcesType(), this.getTargetClass(), this.getTargetMethod(), this.getTargetMethodParams(), this.getTitle()); String strB = String.format(format, permission.getSysName(), permission.getResourcesType(), permission.getTargetClass(), permission.getTargetMethod(), permission.getTargetMethodParams(), permission.getTitle()); return strA.compareTo(strB); } /** * 校验数据是否正确 */ public void check() { if (StringUtils.isBlank(sysName)) { throw new BusinessException("系统(或服务)名称不能为空"); } if (StringUtils.isBlank(title)) { throw new BusinessException("资源标题不能为空"); } if (StringUtils.isBlank(permissionStr)) { throw new BusinessException("权限标识不能为空"); } if (resourcesType == null) { throw new BusinessException("系统(或服务)名称不能为空"); } if (needAuthorization == null) { throw new BusinessException("需要授权才允许访问不能为空"); } if (Objects.equals(resourcesType, EnumConstant.Permission_ResourcesType_1)) { if (StringUtils.isBlank(targetClass)) { throw new BusinessException("目标类名不能为空"); } if (StringUtils.isBlank(targetMethod)) { throw new BusinessException("目标方法名不能为空"); } if (StringUtils.isBlank(resourcesUrl)) { throw new BusinessException("目标Url不能为空"); } } if (targetExist == null) { throw new BusinessException("资源是否存在不能为空"); } } } <|start_filename|>clever-security-client/src/main/java/org/clever/security/client/UserClient.java<|end_filename|> package org.clever.security.client; import org.clever.security.config.CleverSecurityFeignConfiguration; import org.clever.security.dto.request.UserAuthenticationReq; import org.clever.security.dto.response.UserAuthenticationRes; import org.clever.security.entity.Permission; import org.clever.security.entity.User; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import java.util.List; /** * 作者: lzw<br/> * 创建时间:2018-09-24 20:17 <br/> */ @FeignClient( contextId = "org.clever.security.client.UserClient", name = "clever-security-server", path = "/api", configuration = CleverSecurityFeignConfiguration.class ) public interface UserClient { /** * 获取用户 */ @GetMapping("/user/{unique}") User getUser(@PathVariable("unique") String unique); /** * 获取某个用户在某个系统下的所有权限 */ @GetMapping("/user/{username}/{sysName}/permission") List<Permission> findAllPermission(@PathVariable("username") String username, @PathVariable("sysName") String sysName); /** * 用户是否有权登录某个系统 */ @GetMapping("/user/{username}/{sysName}") Boolean canLogin(@PathVariable("username") String username, @PathVariable("sysName") String sysName); /** * 用户登录认证 */ @PostMapping("/user/authentication") UserAuthenticationRes authentication(@RequestBody UserAuthenticationReq req); } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/embed/controller/RefreshTokenController.java<|end_filename|> package org.clever.security.embed.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.clever.common.utils.CookieUtils; import org.clever.security.Constant; import org.clever.security.config.SecurityConfig; import org.clever.security.dto.request.RefreshTokenReq; import org.clever.security.dto.response.JwtLoginRes; import org.clever.security.repository.RedisJwtRepository; import org.clever.security.token.JwtAccessToken; import org.clever.security.token.JwtRefreshToken; import org.clever.security.utils.AuthenticationUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.security.core.context.SecurityContext; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; /** * 作者: lzw<br/> * 创建时间:2019-04-29 10:29 <br/> */ @Api("JwtToken刷新登录令牌") @ConditionalOnProperty(prefix = Constant.ConfigPrefix, name = "login-model", havingValue = "jwt") @RestController @Slf4j public class RefreshTokenController { @Autowired private SecurityConfig securityConfig; @Autowired private RedisJwtRepository redisJwtRepository; @ApiOperation("使用刷新令牌延长登录JwtToken过期时间") @PutMapping("/login/refresh_token.json") public JwtLoginRes refreshToken(HttpServletResponse response, @RequestBody @Validated RefreshTokenReq refreshTokenReq) { JwtRefreshToken jwtRefreshToken = redisJwtRepository.getRefreshToken(refreshTokenReq.getRefreshToken()); SecurityContext securityContext = redisJwtRepository.getSecurityContext(jwtRefreshToken.getUsername()); // 生成新的 JwtAccessToken 和 JwtRefreshToken JwtAccessToken newJwtAccessToken = redisJwtRepository.saveJwtToken(AuthenticationUtils.getSecurityContextToken(securityContext.getAuthentication())); // 删除之前的令牌 JwtAccessToken oldJwtAccessToken = null; try { oldJwtAccessToken = redisJwtRepository.getJwtToken(jwtRefreshToken.getUsername(), jwtRefreshToken.getTokenId()); } catch (Throwable ignored) { } if (oldJwtAccessToken != null) { redisJwtRepository.deleteJwtToken(oldJwtAccessToken); } if (securityConfig.getTokenConfig().isUseCookie()) { CookieUtils.setRooPathCookie(response, securityConfig.getTokenConfig().getJwtTokenKey(), newJwtAccessToken.getToken()); } return new JwtLoginRes( true, "刷新登录令牌成功", AuthenticationUtils.getUserRes(securityContext.getAuthentication()), newJwtAccessToken.getToken(), newJwtAccessToken.getRefreshToken() ); } } <|start_filename|>clever-security-server/src/main/java/org/clever/security/controller/ManageByUserController.java<|end_filename|> package org.clever.security.controller; import com.baomidou.mybatisplus.core.metadata.IPage; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.clever.common.server.controller.BaseController; import org.clever.common.utils.mapper.BeanMapper; import org.clever.security.dto.request.UserAddReq; import org.clever.security.dto.request.UserQueryPageReq; import org.clever.security.dto.request.UserUpdateReq; import org.clever.security.dto.response.UserAddRes; import org.clever.security.dto.response.UserInfoRes; import org.clever.security.entity.User; import org.clever.security.service.ManageByUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; /** * 作者: lzw<br/> * 创建时间:2018-10-02 20:45 <br/> */ @Api("用户管理") @RestController @RequestMapping("/api/manage") public class ManageByUserController extends BaseController { @Autowired private ManageByUserService manageByUserService; @ApiOperation("查询用户列表") @GetMapping("/user") public IPage<User> findByPage(UserQueryPageReq userQueryPageReq) { return manageByUserService.findByPage(userQueryPageReq); } @ApiOperation("获取用户详情(全部角色、权限、系统)") @GetMapping("/user/{username}") public UserInfoRes getUserInfo(@PathVariable("username") String username) { return manageByUserService.getUserInfo(username); } @ApiOperation("新增用户") @PostMapping("/user") public UserAddRes addUser(@RequestBody @Validated UserAddReq userAddReq) { User user = manageByUserService.addUser(userAddReq); return BeanMapper.mapper(user, UserAddRes.class); } @ApiOperation("更新用户") @PutMapping("/user/{username}") public UserAddRes updateUser(@PathVariable("username") String username, @RequestBody @Validated UserUpdateReq req) { return BeanMapper.mapper(manageByUserService.updateUser(username, req), UserAddRes.class); } @ApiOperation("删除用户") @DeleteMapping("/user/{username}") public UserAddRes deleteUser(@PathVariable("username") String username) { return BeanMapper.mapper(manageByUserService.deleteUser(username), UserAddRes.class); } } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/config/model/LoginConfig.java<|end_filename|> package org.clever.security.config.model; import lombok.Data; import java.time.Duration; /** * 用户登录配置 * 作者: lzw<br/> * 创建时间:2019-04-25 19:01 <br/> */ @Data public class LoginConfig { /** * 登录页面 */ private String loginPage = "/index.html"; /** * 登录请求URL */ private String loginUrl = "/login"; /** * 登录只支持POST请求 */ private Boolean postOnly = true; /** * Json 数据提交方式 */ private Boolean jsonDataSubmit = true; /** * 登录成功 - 是否需要跳转(重定向) */ private Boolean loginSuccessNeedRedirect = false; /** * 登录成功默认跳转的页面 */ private String loginSuccessRedirectPage = "/home.html"; /** * 登录失败 - 是否需要跳转(重定向) */ private Boolean loginFailureNeedRedirect = false; /** * 登录失败 - 是否需要跳转(请求转发) 优先级低于loginFailureNeedRedirect */ private Boolean loginFailureNeedForward = false; /** * 登录失败默认跳转的页面 */ private String loginFailureRedirectPage = "/index.html"; /** * 登录是否需要验证码 */ private Boolean needCaptcha = true; /** * 登录失败多少次才需要验证码(小于等于0,总是需要验证码) */ private Integer needCaptchaByLoginFailCount = 3; /** * 验证码有效时间 */ private Duration captchaEffectiveTime = Duration.ofSeconds(120); /** * 同一个用户并发登录次数限制(-1表示不限制) */ private Integer concurrentLoginCount = 1; /** * 同一个用户并发登录次数达到最大值之后,是否不允许之后的登录(false 之后登录的把之前登录的挤下来) */ private Boolean notAllowAfterLogin = false; } <|start_filename|>clever-security-embed/src/main/java/org/clever/security/handler/UserLogoutHandler.java<|end_filename|> package org.clever.security.handler; import lombok.extern.slf4j.Slf4j; import org.clever.security.Constant; import org.clever.security.LoginModel; import org.clever.security.config.SecurityConfig; import org.clever.security.repository.RedisJwtRepository; import org.clever.security.token.JwtAccessToken; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.logout.LogoutHandler; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Set; /** * 用户登出处理 * 作者: lzw<br/> * 创建时间:2018-11-19 15:13 <br/> */ @ConditionalOnProperty(prefix = Constant.ConfigPrefix, name = "login-model", havingValue = "jwt") @Component @Slf4j public class UserLogoutHandler implements LogoutHandler { @Autowired private SecurityConfig securityConfig; @Autowired private RedisJwtRepository redisJwtRepository; @Override public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { if (!LoginModel.jwt.equals(securityConfig.getLoginModel())) { return; } JwtAccessToken jwtAccessToken = null; try { jwtAccessToken = redisJwtRepository.getJwtToken(request); } catch (Throwable ignored) { } if (jwtAccessToken != null) { redisJwtRepository.deleteJwtToken(jwtAccessToken); log.info("### 删除 JWT Token成功"); Set<String> ketSet = redisJwtRepository.getJwtTokenPatternKey(jwtAccessToken.getClaims().getSubject()); if (ketSet != null && ketSet.size() <= 0) { redisJwtRepository.deleteSecurityContext(jwtAccessToken.getClaims().getSubject()); log.info("### 删除 SecurityContext 成功"); } } } } <|start_filename|>clever-security-client/src/main/java/org/clever/security/config/CleverSecurityAccessTokenConfig.java<|end_filename|> package org.clever.security.config; import lombok.Data; import org.clever.security.Constant; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import java.util.Map; /** * 作者: lzw<br/> * 创建时间:2018-03-15 14:31 <br/> */ @SuppressWarnings("ConfigurationProperties") @ConfigurationProperties(prefix = Constant.ConfigPrefix) @Component @Data public class CleverSecurityAccessTokenConfig { /** * 访问 clever-security-server 服务API的授权Token请求头 */ private Map<String, String> accessTokenHeads; } <|start_filename|>clever-security-server/src/main/java/org/clever/security/controller/ManageByPermissionController.java<|end_filename|> package org.clever.security.controller; import com.baomidou.mybatisplus.core.metadata.IPage; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.clever.common.server.controller.BaseController; import org.clever.common.utils.mapper.BeanMapper; import org.clever.security.dto.request.PermissionAddReq; import org.clever.security.dto.request.PermissionQueryReq; import org.clever.security.dto.request.PermissionUpdateReq; import org.clever.security.entity.Permission; import org.clever.security.entity.model.WebPermissionModel; import org.clever.security.service.ManageByPermissionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Set; /** * 作者: lzw<br/> * 创建时间:2018-10-02 20:48 <br/> */ @Api("权限管理") @RestController @RequestMapping("/api/manage") public class ManageByPermissionController extends BaseController { @Autowired private ManageByPermissionService manageByPermissionService; @ApiOperation("查询权限列表") @GetMapping("/permission") public IPage<WebPermissionModel> findByPage(PermissionQueryReq queryReq) { return manageByPermissionService.findByPage(queryReq); } @ApiOperation("新增权限") @PostMapping("/permission") public WebPermissionModel addPermission(@RequestBody @Validated PermissionAddReq permissionAddReq) { Permission permission = BeanMapper.mapper(permissionAddReq, Permission.class); return manageByPermissionService.addPermission(permission); } @ApiOperation("更新权限") @PutMapping("/permission/{permissionStr}") public WebPermissionModel updatePermission( @PathVariable("permissionStr") String permissionStr, @RequestBody @Validated PermissionUpdateReq permissionUpdateReq) { return manageByPermissionService.updatePermission(permissionStr, permissionUpdateReq); } @ApiOperation("获取权限信息") @GetMapping("/permission/{permissionStr}") public WebPermissionModel getPermissionModel(@PathVariable("permissionStr") String permissionStr) { return manageByPermissionService.getPermissionModel(permissionStr); } @ApiOperation("删除权限信息") @DeleteMapping("/permission/{permissionStr}") public WebPermissionModel delPermissionModel(@PathVariable("permissionStr") String permissionStr) { return manageByPermissionService.delPermissionModel(permissionStr); } @ApiOperation("删除权限信息(批量)") @DeleteMapping("/permission/batch") public List<WebPermissionModel> delPermissionModels(@RequestParam("permissionSet") Set<String> permissionSet) { if (permissionSet == null) { return null; } return manageByPermissionService.delPermissionModels(permissionSet); } }
Lzw2016/clever-security
<|start_filename|>doc/functionIndex/@mlep/encodeData.html<|end_filename|> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>Description of encodeData</title> <meta name="keywords" content="encodeData"> <meta name="description" content="ENCODEDATA - Encode data to packet."> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="generator" content="m2html v1.5 &copy; 2003-2005 <NAME>"> <meta name="robots" content="index, follow"> <link type="text/css" rel="stylesheet" href="../m2html.css"> </head> <body> <a name="_top"></a> <div><a href="../functionIndex.html">Home</a> &gt; <a href="functionIndex.html">@mlep</a> &gt; encodeData.m</div> <!--<table width="100%"><tr><td align="left"><a href="../functionIndex.html"><img alt="<" border="0" src="../left.png">&nbsp;Master index</a></td> <td align="right"><a href="functionIndex.html">Index for @mlep&nbsp;<img alt=">" border="0" src="../right.png"></a></td></tr></table>--> <h1>encodeData </h1> <h2><a name="_name"></a>PURPOSE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="box"><strong>ENCODEDATA - Encode data to packet.</strong></div> <h2><a name="_synopsis"></a>SYNOPSIS <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="box"><strong>function packet = encodeData(vernumber, flag, timevalue, realvalues, intvalues, boolvalues) </strong></div> <h2><a name="_description"></a>DESCRIPTION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="fragment"><pre class="comment">ENCODEDATA - Encode data to packet. Encode data to a packet (a string) that can be sent to the external program. The packet format follows the BCVTB co-simulation communication protocol. Syntax: packet = encodeData(vernumber, flag, timevalue, realvalues, intvalues, boolvalues) Inputs: vernumber - Version of the protocol to be used. Currently, version 1 and 2 are supported. flag - An integer specifying the (status) flag. Refer to the BCVTB protocol for allowed flag values. timevalue - A real value which is the current simulation time in seconds. realvalues - A vector of real value data to be sent. Can be empty. intvalues - A vector of integer value data to be sent. Can be empty. boolvalues - A vector of boolean value data to be sent. Can be empty. Outputs: packet - String that contains the encoded data. Protocol Version 1 &amp; 2: Packet has the form: &quot;v f dr di db t r1 r2 ... i1 i2 ... b1 b2 ... \n&quot; where v - version number (1,2) f - flag (0: communicate, 1: finish, -10: initialization error, -20: time integration error, -1: unknown error) dr - number of real values di - number of integer values db - number of boolean values t - current simulation time in seconds (format %20.15e) r1 r2 ... are real values (format %20.15e) i1 i2 ... are integer values (format %d) b1 b2 ... are boolean values (format %d) \n - carriage return Note that if f is non-zero, other values after it will not be processed. See also: <a href="mlep.html" class="code" title="">MLEP</a>.<a href="decodePacket.html" class="code" title="function [flag, timevalue, realvalues, intvalues, boolvalues] = decodePacket(packet)">DECODEPACKET</a>, <a href="mlep.html" class="code" title="">MLEP</a>.<a href="encodeRealData.html" class="code" title="function packet = encodeRealData(vernumber, flag, timevalue, realvalues)">ENCODEREALDATA</a>, <a href="mlep.html" class="code" title="">MLEP</a>.<a href="encodeStatus.html" class="code" title="function packet = encodeStatus(vernumber, flag)">ENCODESTATUS</a>, WRITE (C) 2010, <NAME> (<EMAIL>)</pre></div> <!-- crossreference --> <h2><a name="_cross"></a>CROSS-REFERENCE INFORMATION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> This function calls: <ul style="list-style-image:url(../matlabicon.gif)"> </ul> This function is called by: <ul style="list-style-image:url(../matlabicon.gif)"> </ul> <!-- crossreference --> <h2><a name="_source"></a>SOURCE CODE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="fragment"><pre>0001 <a name="_sub0" href="#_subfunctions" class="code">function packet = encodeData(vernumber, flag, timevalue, realvalues, intvalues, boolvalues)</a> 0002 <span class="comment">%ENCODEDATA - Encode data to packet.</span> 0003 <span class="comment">%Encode data to a packet (a string) that can be sent to the external</span> 0004 <span class="comment">%program. The packet format follows the BCVTB co-simulation</span> 0005 <span class="comment">%communication protocol.</span> 0006 <span class="comment">%</span> 0007 <span class="comment">% Syntax: packet = encodeData(vernumber, flag, timevalue, realvalues, intvalues, boolvalues)</span> 0008 <span class="comment">%</span> 0009 <span class="comment">% Inputs:</span> 0010 <span class="comment">% vernumber - Version of the protocol to be used. Currently, version 1</span> 0011 <span class="comment">% and 2 are supported.</span> 0012 <span class="comment">% flag - An integer specifying the (status) flag. Refer to the BCVTB</span> 0013 <span class="comment">% protocol for allowed flag values.</span> 0014 <span class="comment">% timevalue - A real value which is the current simulation time in</span> 0015 <span class="comment">% seconds.</span> 0016 <span class="comment">% realvalues - A vector of real value data to be sent. Can be empty.</span> 0017 <span class="comment">% intvalues - A vector of integer value data to be sent. Can be empty.</span> 0018 <span class="comment">% boolvalues - A vector of boolean value data to be sent. Can be</span> 0019 <span class="comment">% empty.</span> 0020 <span class="comment">%</span> 0021 <span class="comment">% Outputs:</span> 0022 <span class="comment">% packet - String that contains the encoded data.</span> 0023 <span class="comment">%</span> 0024 <span class="comment">% Protocol Version 1 &amp; 2:</span> 0025 <span class="comment">% Packet has the form:</span> 0026 <span class="comment">% &quot;v f dr di db t r1 r2 ... i1 i2 ... b1 b2 ... \n&quot;</span> 0027 <span class="comment">% where</span> 0028 <span class="comment">% v - version number (1,2)</span> 0029 <span class="comment">% f - flag (0: communicate, 1: finish, -10: initialization error,</span> 0030 <span class="comment">% -20: time integration error, -1: unknown error)</span> 0031 <span class="comment">% dr - number of real values</span> 0032 <span class="comment">% di - number of integer values</span> 0033 <span class="comment">% db - number of boolean values</span> 0034 <span class="comment">% t - current simulation time in seconds (format %20.15e)</span> 0035 <span class="comment">% r1 r2 ... are real values (format %20.15e)</span> 0036 <span class="comment">% i1 i2 ... are integer values (format %d)</span> 0037 <span class="comment">% b1 b2 ... are boolean values (format %d)</span> 0038 <span class="comment">% \n - carriage return</span> 0039 <span class="comment">%</span> 0040 <span class="comment">% Note that if f is non-zero, other values after it will not be processed.</span> 0041 <span class="comment">%</span> 0042 <span class="comment">% See also: MLEP.DECODEPACKET, MLEP.ENCODEREALDATA, MLEP.ENCODESTATUS,</span> 0043 <span class="comment">% WRITE</span> 0044 <span class="comment">%</span> 0045 <span class="comment">% (C) 2010, <NAME> (<EMAIL>)</span> 0046 0047 ni = nargin; 0048 <span class="keyword">if</span> ni &lt; 2 0049 error(<span class="string">'Not enough arguments: at least vernumber and flag must be specified.'</span>); 0050 <span class="keyword">end</span> 0051 0052 <span class="keyword">if</span> vernumber &lt;= 2 0053 <span class="keyword">if</span> flag == 0 0054 <span class="keyword">if</span> ni &lt; 3 0055 error(<span class="string">'Not enough arguments: time must be specified.'</span>); 0056 <span class="keyword">end</span> 0057 0058 <span class="keyword">if</span> ni &lt; 4, realvalues = []; <span class="keyword">end</span> 0059 0060 <span class="keyword">if</span> ni &lt; 5, intvalues = []; <span class="keyword">end</span> 0061 0062 <span class="keyword">if</span> ni &lt; 6 0063 boolvalues = []; 0064 <span class="keyword">else</span> 0065 boolvalues = logical(boolvalues(:)'); <span class="comment">% Convert to boolean values</span> 0066 <span class="keyword">end</span> 0067 0068 <span class="comment">% NOTE: although we can use num2str to print vectors to string, its</span> 0069 <span class="comment">% performance is worse than that of sprintf, which would cause this</span> 0070 <span class="comment">% function approx. 3 times slower.</span> 0071 packet = [sprintf(<span class="string">'%d 0 %d %d %d %20.15e '</span>, vernumber,<span class="keyword">...</span> 0072 length(realvalues), <span class="keyword">...</span> 0073 length(intvalues), <span class="keyword">...</span> 0074 length(boolvalues), timevalue),<span class="keyword">...</span> 0075 sprintf(<span class="string">'%20.15e '</span>, realvalues),<span class="keyword">...</span> 0076 sprintf(<span class="string">'%d '</span>, intvalues),<span class="keyword">...</span> 0077 sprintf(<span class="string">'%d '</span>, boolvalues)]; 0078 <span class="keyword">else</span> 0079 <span class="comment">% Error</span> 0080 packet = sprintf(<span class="string">'%d %d'</span>, vernumber, flag); 0081 <span class="keyword">end</span> 0082 <span class="keyword">else</span> 0083 packet = <span class="string">''</span>; 0084 <span class="keyword">end</span> 0085 0086 <span class="keyword">end</span> 0087 0088 <span class="comment">% Protocol Version 1 &amp; 2:</span> 0089 <span class="comment">% Packet has the form:</span> 0090 <span class="comment">% v f dr di db t r1 r2 ... i1 i2 ... b1 b2 ...</span> 0091 <span class="comment">% where</span> 0092 <span class="comment">% v - version number (1,2)</span> 0093 <span class="comment">% f - flag (0: communicate, 1: finish, -10: initialization error,</span> 0094 <span class="comment">% -20: time integration error, -1: unknown error)</span> 0095 <span class="comment">% dr - number of real values</span> 0096 <span class="comment">% di - number of integer values</span> 0097 <span class="comment">% db - number of boolean values</span> 0098 <span class="comment">% t - current simulation time in seconds (format %20.15e)</span> 0099 <span class="comment">% r1 r2 ... are real values (format %20.15e)</span> 0100 <span class="comment">% i1 i2 ... are integer values (format %d)</span> 0101 <span class="comment">% b1 b2 ... are boolean values (format %d)</span> 0102 <span class="comment">%</span> 0103 <span class="comment">% Note that if f is non-zero, other values after it will not be processed.</span></pre></div> <hr><address>EnergyPlus Co-simulation Toolbox &copy; 2018</address> </body> </html> <|start_filename|>doc/functionIndex/@mlep/encodeStatus.html<|end_filename|> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>Description of encodeStatus</title> <meta name="keywords" content="encodeStatus"> <meta name="description" content="ENCODESTATUS - Encode status flag to a packet."> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="generator" content="m2html v1.5 &copy; 2003-2005 <NAME>"> <meta name="robots" content="index, follow"> <link type="text/css" rel="stylesheet" href="../m2html.css"> </head> <body> <a name="_top"></a> <div><a href="../functionIndex.html">Home</a> &gt; <a href="functionIndex.html">@mlep</a> &gt; encodeStatus.m</div> <!--<table width="100%"><tr><td align="left"><a href="../functionIndex.html"><img alt="<" border="0" src="../left.png">&nbsp;Master index</a></td> <td align="right"><a href="functionIndex.html">Index for @mlep&nbsp;<img alt=">" border="0" src="../right.png"></a></td></tr></table>--> <h1>encodeStatus </h1> <h2><a name="_name"></a>PURPOSE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="box"><strong>ENCODESTATUS - Encode status flag to a packet.</strong></div> <h2><a name="_synopsis"></a>SYNOPSIS <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="box"><strong>function packet = encodeStatus(vernumber, flag) </strong></div> <h2><a name="_description"></a>DESCRIPTION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="fragment"><pre class="comment">ENCODESTATUS - Encode status flag to a packet. Encode a status flag to a packet (a string) that can be sent to the external program. This function is a special version of mlepEncodeData in which only a flag (non-zero) is transferred. Syntax: packet = mlepEncodeStatus(vernumber, flag) Inputs: vernumber - Version of the protocol to be used. Currently, version 1 and 2 are supported. flag - An integer specifying the (status) flag. Refer to the BCVTB protocol for allowed flag values. Output: packet - A string that contains the encoded data. See also: <a href="mlep.html" class="code" title="">MLEP</a>.<a href="decodePacket.html" class="code" title="function [flag, timevalue, realvalues, intvalues, boolvalues] = decodePacket(packet)">DECODEPACKET</a>, <a href="mlep.html" class="code" title="">MLEP</a>.<a href="encodeData.html" class="code" title="function packet = encodeData(vernumber, flag, timevalue, realvalues, intvalues, boolvalues)">ENCODEDATA</a>, <a href="mlep.html" class="code" title="">MLEP</a>.<a href="encodeRealData.html" class="code" title="function packet = encodeRealData(vernumber, flag, timevalue, realvalues)">ENCODEREALDATA</a>, WRITE (C) 2010, <NAME> (<EMAIL>)</pre></div> <!-- crossreference --> <h2><a name="_cross"></a>CROSS-REFERENCE INFORMATION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> This function calls: <ul style="list-style-image:url(../matlabicon.gif)"> </ul> This function is called by: <ul style="list-style-image:url(../matlabicon.gif)"> </ul> <!-- crossreference --> <h2><a name="_source"></a>SOURCE CODE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="fragment"><pre>0001 <a name="_sub0" href="#_subfunctions" class="code">function packet = encodeStatus(vernumber, flag)</a> 0002 <span class="comment">%ENCODESTATUS - Encode status flag to a packet.</span> 0003 <span class="comment">%Encode a status flag to a packet (a string) that can be sent to the</span> 0004 <span class="comment">%external program. This function is a special version of</span> 0005 <span class="comment">%mlepEncodeData in which only a flag (non-zero) is transferred.</span> 0006 <span class="comment">%</span> 0007 <span class="comment">% Syntax: packet = mlepEncodeStatus(vernumber, flag)</span> 0008 <span class="comment">%</span> 0009 <span class="comment">% Inputs:</span> 0010 <span class="comment">% vernumber - Version of the protocol to be used. Currently, version 1</span> 0011 <span class="comment">% and 2 are supported.</span> 0012 <span class="comment">% flag - An integer specifying the (status) flag. Refer to the BCVTB</span> 0013 <span class="comment">% protocol for allowed flag values.</span> 0014 <span class="comment">%</span> 0015 <span class="comment">% Output:</span> 0016 <span class="comment">% packet - A string that contains the encoded data.</span> 0017 <span class="comment">%</span> 0018 <span class="comment">% See also: MLEP.DECODEPACKET, MLEP.ENCODEDATA, MLEP.ENCODEREALDATA,</span> 0019 <span class="comment">% WRITE</span> 0020 <span class="comment">%</span> 0021 <span class="comment">% (C) 2010, <NAME> (<EMAIL>)</span> 0022 0023 ni = nargin; 0024 <span class="keyword">if</span> ni &lt; 2 0025 error(<span class="string">'Not enough arguments: all input arguments are required.'</span>); 0026 <span class="keyword">end</span> 0027 0028 <span class="keyword">if</span> vernumber &lt;= 2 0029 packet = sprintf(<span class="string">'%d %d'</span>, vernumber, flag); 0030 <span class="keyword">else</span> 0031 packet = <span class="string">''</span>; 0032 <span class="keyword">end</span> 0033 0034 <span class="keyword">end</span> 0035 0036 <span class="comment">% Protocol Version 1 &amp; 2:</span> 0037 <span class="comment">% Packet has the form:</span> 0038 <span class="comment">% v f dr di db t r1 r2 ... i1 i2 ... b1 b2 ...</span> 0039 <span class="comment">% where</span> 0040 <span class="comment">% v - version number (1,2)</span> 0041 <span class="comment">% f - flag (0: communicate, 1: finish, -10: initialization error,</span> 0042 <span class="comment">% -20: time integration error, -1: unknown error)</span> 0043 <span class="comment">% dr - number of real values</span> 0044 <span class="comment">% di - number of integer values</span> 0045 <span class="comment">% db - number of boolean values</span> 0046 <span class="comment">% t - current simulation time in seconds (format %20.15e)</span> 0047 <span class="comment">% r1 r2 ... are real values (format %20.15e)</span> 0048 <span class="comment">% i1 i2 ... are integer values (format %d)</span> 0049 <span class="comment">% b1 b2 ... are boolean values (format %d)</span> 0050 <span class="comment">%</span> 0051 <span class="comment">% Note that if f is non-zero, other values after it will not be processed.</span></pre></div> <hr><address>EnergyPlus Co-simulation Toolbox &copy; 2018</address> </body> </html> <|start_filename|>doc/functionIndex/library/slblocks.html<|end_filename|> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>Description of slblocks</title> <meta name="keywords" content="slblocks"> <meta name="description" content="SLBLOCKS - Simulink Library browser definition file"> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="generator" content="m2html v1.5 &copy; 2003-2005 <NAME>"> <meta name="robots" content="index, follow"> <link type="text/css" rel="stylesheet" href="../m2html.css"> </head> <body> <a name="_top"></a> <div><a href="../functionIndex.html">Home</a> &gt; <a href="functionIndex.html">library</a> &gt; slblocks.m</div> <!--<table width="100%"><tr><td align="left"><a href="../functionIndex.html"><img alt="<" border="0" src="../left.png">&nbsp;Master index</a></td> <td align="right"><a href="functionIndex.html">Index for library&nbsp;<img alt=">" border="0" src="../right.png"></a></td></tr></table>--> <h1>slblocks </h1> <h2><a name="_name"></a>PURPOSE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="box"><strong>SLBLOCKS - Simulink Library browser definition file</strong></div> <h2><a name="_synopsis"></a>SYNOPSIS <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="box"><strong>function blkStruct = slblocks </strong></div> <h2><a name="_description"></a>DESCRIPTION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="fragment"><pre class="comment"> SLBLOCKS - Simulink Library browser definition file</pre></div> <!-- crossreference --> <h2><a name="_cross"></a>CROSS-REFERENCE INFORMATION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> This function calls: <ul style="list-style-image:url(../matlabicon.gif)"> </ul> This function is called by: <ul style="list-style-image:url(../matlabicon.gif)"> </ul> <!-- crossreference --> <h2><a name="_source"></a>SOURCE CODE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="fragment"><pre>0001 <a name="_sub0" href="#_subfunctions" class="code">function blkStruct = slblocks</a> 0002 <span class="comment">% SLBLOCKS - Simulink Library browser definition file</span> 0003 0004 <span class="comment">% Name of the subsystem which will show up in the Simulink Blocksets</span> 0005 <span class="comment">% and Toolboxes subsystem.</span> 0006 blkStruct.Name = sprintf(<span class="string">'mlep\nLibrary'</span>); 0007 0008 <span class="comment">% The function that will be called when the user double-clicks on</span> 0009 <span class="comment">% this icon.</span> 0010 blkStruct.OpenFcn = <span class="string">'open(''mlepLibrary.slx'');'</span>; 0011 0012 <span class="comment">% The argument to be set as the Mask Display for the subsystem.</span> 0013 blkStruct.MaskDisplay = <span class="string">'disp(''mlep Library Blocks'');'</span>; 0014 0015 <span class="comment">% Library information for Simulink library browser</span> 0016 blkStruct.Browser = struct(); 0017 blkStruct.Browser.Library = <span class="string">'mlepLibrary'</span>; 0018 blkStruct.Browser.Name = <span class="string">'mlep Blocks'</span>;</pre></div> <hr><address>EnergyPlus Co-simulation Toolbox &copy; 2018</address> </body> </html> <|start_filename|>doc/functionIndex/@mlep/readIDF.html<|end_filename|> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>Description of readIDF</title> <meta name="keywords" content="readIDF"> <meta name="description" content="READIDF - Read and parse EnergyPlus IDF file."> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="generator" content="m2html v1.5 &copy; 2003-2005 <NAME>"> <meta name="robots" content="index, follow"> <link type="text/css" rel="stylesheet" href="../m2html.css"> </head> <body> <a name="_top"></a> <div><a href="../functionIndex.html">Home</a> &gt; <a href="functionIndex.html">@mlep</a> &gt; readIDF.m</div> <!--<table width="100%"><tr><td align="left"><a href="../functionIndex.html"><img alt="<" border="0" src="../left.png">&nbsp;Master index</a></td> <td align="right"><a href="functionIndex.html">Index for @mlep&nbsp;<img alt=">" border="0" src="../right.png"></a></td></tr></table>--> <h1>readIDF </h1> <h2><a name="_name"></a>PURPOSE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="box"><strong>READIDF - Read and parse EnergyPlus IDF file.</strong></div> <h2><a name="_synopsis"></a>SYNOPSIS <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="box"><strong>function data = readIDF(filename, classnames) </strong></div> <h2><a name="_description"></a>DESCRIPTION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="fragment"><pre class="comment"> READIDF - Read and parse EnergyPlus IDF file. data = readIDF(filename) reads all data entries from an IDF file with name filename. The output data is a structure array, where each item is one data entry. Each item k has two fields: data(k).class is a string of the class name data(k).fields is a cell array of strings, each cell is a data field after the class name. The order of the entries is the same as in the IDF file. data = readIDF(filename, classnames) reads all data entries of the classes given in classnames, from a given IDF file. Input argument classnames is either a string or a cell array of strings specifying the class(es) that will be read. Data entries not of those classes will be skipped. The output 'data' is a structure array (a bit DIFFERENT from above): each item k of the array contains ALL data entries for CLASS k in 'classnames' (not entry k in the IDF file), with 2 fields: data(k).class is a string, the name of the class k in 'classnames', converted to lower-case (e.g. 'TimeStep' becomes 'timestep'). data(k).fields is a cell array of cell arrays of strings, each cell contains the fields' strings for one entry of class k. If there is no entry of class k then this field is an empty cell. Class names are case insensitive. Examples: data = readIDF('SmOffPSZ.idf', 'Timestep') to read only the time step, e.g. data could be data = class: 'timestep' fields: {{1x1 cell}} with data(1).fields{1} = {'4'} data = readIDF('SmOffPSZ.idf',... {'Timestep', 'ExternalInterface:Schedule'}) to read time step and all external schedule variables. data = 1x2 struct array with fields: class fields data(2) = class: 'externalinterface:schedule' fields: {{1x3 cell} {1x3 cell}} (C) 2018 by <NAME> (<EMAIL>) (C) 2012 by <NAME> (<EMAIL>)</pre></div> <!-- crossreference --> <h2><a name="_cross"></a>CROSS-REFERENCE INFORMATION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> This function calls: <ul style="list-style-image:url(../matlabicon.gif)"> </ul> This function is called by: <ul style="list-style-image:url(../matlabicon.gif)"> </ul> <!-- crossreference --> <h2><a name="_source"></a>SOURCE CODE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="fragment"><pre>0001 <a name="_sub0" href="#_subfunctions" class="code">function data = readIDF(filename, classnames)</a> 0002 <span class="comment">% READIDF - Read and parse EnergyPlus IDF file.</span> 0003 <span class="comment">%</span> 0004 <span class="comment">% data = readIDF(filename) reads all data entries from an IDF</span> 0005 <span class="comment">% file with name filename. The output data is a structure array,</span> 0006 <span class="comment">% where each item is one data entry. Each item k has two fields:</span> 0007 <span class="comment">% data(k).class is a string of the class name</span> 0008 <span class="comment">% data(k).fields is a cell array of strings, each cell is a</span> 0009 <span class="comment">% data field after the class name.</span> 0010 <span class="comment">% The order of the entries is the same as in the IDF file.</span> 0011 <span class="comment">%</span> 0012 <span class="comment">% data = readIDF(filename, classnames) reads all data entries</span> 0013 <span class="comment">% of the classes given in classnames, from a given IDF</span> 0014 <span class="comment">% file. Input argument classnames is either a string or a cell</span> 0015 <span class="comment">% array of strings specifying the class(es) that will be</span> 0016 <span class="comment">% read. Data entries not of those classes will be skipped. The output</span> 0017 <span class="comment">% 'data' is a structure array (a bit DIFFERENT from above): each item k</span> 0018 <span class="comment">% of the array contains ALL data entries for CLASS k in 'classnames' (not</span> 0019 <span class="comment">% entry k in the IDF file), with 2 fields:</span> 0020 <span class="comment">% data(k).class is a string, the name of the class k in 'classnames',</span> 0021 <span class="comment">% converted to lower-case (e.g. 'TimeStep' becomes</span> 0022 <span class="comment">% 'timestep').</span> 0023 <span class="comment">% data(k).fields is a cell array of cell arrays of strings, each cell</span> 0024 <span class="comment">% contains the fields' strings for one entry of class k.</span> 0025 <span class="comment">% If there is no entry of class k then this field is an</span> 0026 <span class="comment">% empty cell.</span> 0027 <span class="comment">%</span> 0028 <span class="comment">% Class names are case insensitive.</span> 0029 <span class="comment">%</span> 0030 <span class="comment">% Examples:</span> 0031 <span class="comment">% data = readIDF('SmOffPSZ.idf', 'Timestep')</span> 0032 <span class="comment">% to read only the time step, e.g. data could be</span> 0033 <span class="comment">% data =</span> 0034 <span class="comment">% class: 'timestep'</span> 0035 <span class="comment">% fields: {{1x1 cell}}</span> 0036 <span class="comment">% with data(1).fields{1} = {'4'}</span> 0037 <span class="comment">%</span> 0038 <span class="comment">% data = readIDF('SmOffPSZ.idf',...</span> 0039 <span class="comment">% {'Timestep', 'ExternalInterface:Schedule'})</span> 0040 <span class="comment">% to read time step and all external schedule variables.</span> 0041 <span class="comment">% data =</span> 0042 <span class="comment">% 1x2 struct array with fields:</span> 0043 <span class="comment">% class</span> 0044 <span class="comment">% fields</span> 0045 <span class="comment">%</span> 0046 <span class="comment">% data(2) =</span> 0047 <span class="comment">% class: 'externalinterface:schedule'</span> 0048 <span class="comment">% fields: {{1x3 cell} {1x3 cell}}</span> 0049 <span class="comment">%</span> 0050 <span class="comment">%</span> 0051 <span class="comment">% (C) 2018 by <NAME> (<EMAIL>)</span> 0052 <span class="comment">% (C) 2012 by <NAME> (<EMAIL>)</span> 0053 0054 <span class="comment">% --- Input check ---------------------------------------------------------</span> 0055 narginchk(1, 2); 0056 assert(ischar(filename), <span class="string">'File name must be a string.'</span>); 0057 <span class="keyword">if</span> ~exist(<span class="string">'classnames'</span>, <span class="string">'var'</span>) 0058 classnames = {}; 0059 <span class="keyword">else</span> 0060 <span class="comment">% Lower case strings in classnames</span> 0061 <span class="keyword">if</span> ischar(classnames) 0062 classnames = {lower(classnames)}; 0063 <span class="keyword">elseif</span> iscell(classnames) 0064 assert(all(cellfun(@ischar, classnames)),<span class="keyword">...</span> 0065 <span class="string">'classnames must be a cell array of strings.'</span>); 0066 classnames = cellfun(@lower, classnames,<span class="keyword">...</span> 0067 <span class="string">'UniformOutput'</span>, false); 0068 <span class="keyword">else</span> 0069 error(<span class="string">'classnames must be either a string or a cell array.'</span>); 0070 <span class="keyword">end</span> 0071 <span class="keyword">end</span> 0072 0073 noClassnames = isempty(classnames); 0074 nClassnames = length(classnames); 0075 0076 <span class="comment">% --- Open File - preallocate ---------------------------------------------</span> 0077 0078 <span class="comment">% Open the file in text mode</span> 0079 [fid, msg] = fopen(filename, <span class="string">'rt'</span>); 0080 <span class="keyword">if</span> fid &lt; 0 0081 error(<span class="string">'Cannot open IDF file: %s'</span>, msg); 0082 <span class="keyword">end</span> 0083 0084 <span class="comment">% Read the file to system cache (performance)</span> 0085 filetext = fileread(filename); 0086 lineIdx = strfind(filetext,newline); 0087 nLines = numel(lineIdx); 0088 0089 <span class="comment">% Close the file</span> 0090 0091 <span class="comment">% Read line by line and parse</span> 0092 syntaxerr = false; <span class="comment">% If there is a syntax error in the IDF file</span> 0093 syntaxmsg = <span class="string">''</span>; 0094 0095 <span class="comment">% Pre-allocate the data struct for faster performance and less</span> 0096 <span class="comment">% fragmented memory</span> 0097 <span class="keyword">if</span> noClassnames 0098 nBlocks = 0; <span class="comment">% Number of blocks read from file</span> 0099 data = repmat(struct(<span class="string">'class'</span>, <span class="string">''</span>, <span class="string">'fields'</span>, {{}}), 1, 128); 0100 <span class="keyword">else</span> 0101 data = struct(<span class="string">'class'</span>, classnames, <span class="keyword">...</span> 0102 <span class="string">'fields'</span>, repmat({{}}, 1, nClassnames)); 0103 <span class="keyword">end</span> 0104 0105 inBlock = false; <span class="comment">% A block is a block of code ended with ;</span> 0106 saveBlock = false; <span class="comment">% Is the current block being saved?</span> 0107 0108 <span class="comment">% --- Parse ---------------------------------------------------------------</span> 0109 <span class="comment">% A field is a group of 0 or more characters not including comma,</span> 0110 <span class="comment">% semi-colon and exclamation; a line consists of a number of fields,</span> 0111 <span class="comment">% separated by either a comma or a semi-colon.</span> 0112 0113 startLineIdx = 1; 0114 <span class="keyword">for</span> iLine = 1:nLines 0115 0116 <span class="comment">% Get line</span> 0117 endLineIdx = lineIdx(iLine); 0118 line = filetext(startLineIdx:endLineIdx); 0119 startLineIdx = endLineIdx + 1; 0120 0121 <span class="comment">% Remove all surrounding spaces</span> 0122 line = strtrim(line); 0123 0124 <span class="comment">% If l is empty or a comment line, ignore it</span> 0125 <span class="keyword">if</span> isempty(line) || line(1) == <span class="string">'!'</span> 0126 <span class="keyword">continue</span>; 0127 <span class="keyword">end</span> 0128 0129 <span class="comment">% Remove the comment part if any</span> 0130 dataEndIdx = strfind(line, <span class="string">'!'</span>); 0131 <span class="keyword">if</span> ~isempty(dataEndIdx) 0132 <span class="comment">% Remove from the first occurence of '!' to the end</span> 0133 line = strtrim(line(1:dataEndIdx(1)-1)); 0134 <span class="keyword">end</span> 0135 0136 0137 0138 <span class="comment">% If we are not in a block and if class names are given, we search</span> 0139 <span class="comment">% for any class name in the current line and only parse the line if we</span> 0140 <span class="comment">% find an interested class name. Because we are not in a block, the</span> 0141 <span class="comment">% class name must be at the beginning of the line.</span> 0142 <span class="keyword">if</span> ~inBlock &amp;&amp; ~noClassnames 0143 lowerL = lower(line); 0144 foundClassname = false; 0145 0146 <span class="keyword">for</span> k = 1:nClassnames 0147 <span class="keyword">if</span> ~isempty(strncmp(classnames{k}, lowerL,strlength(classnames{k}))) 0148 foundClassname = true; 0149 <span class="keyword">break</span>; 0150 <span class="keyword">end</span> 0151 <span class="keyword">end</span> 0152 0153 <span class="keyword">if</span> ~foundClassname 0154 <span class="comment">% Could not find a class name in l, then skip this line</span> 0155 <span class="keyword">continue</span>; 0156 <span class="keyword">end</span> 0157 <span class="keyword">end</span> 0158 0159 <span class="comment">% Get all fields in the line</span> 0160 dataEndIdx = strfind(line, <span class="string">','</span>); 0161 semIdx = strfind(line, <span class="string">';'</span>); 0162 0163 <span class="keyword">if</span> (isempty(dataEndIdx) &amp;&amp; isempty(semIdx)) || <span class="keyword">...</span> 0164 (~isempty(semIdx) &amp;&amp; ~isempty(dataEndIdx) &amp;&amp; (semIdx &lt; dataEndIdx(end))) 0165 <span class="comment">% Syntax error</span> 0166 syntaxerr = true; 0167 syntaxmsg = line; 0168 <span class="keyword">break</span>; 0169 <span class="keyword">end</span> 0170 0171 <span class="comment">% Append semicolon position if any</span> 0172 <span class="keyword">if</span> ~isempty(semIdx) 0173 dataEndIdx = [dataEndIdx semIdx]; <span class="comment">%#ok&lt;AGROW&gt; % When there is only &quot;;&quot; in the line</span> 0174 <span class="keyword">end</span> 0175 0176 <span class="comment">% Parse fields</span> 0177 nFields = numel(dataEndIdx); 0178 dataEndIdx = [0 dataEndIdx]; <span class="comment">%#ok&lt;AGROW&gt;</span> 0179 <span class="keyword">for</span> k = 1:nFields 0180 field = strtrim(line(dataEndIdx(k)+1:dataEndIdx(k+1)-1)); 0181 <span class="keyword">if</span> ~inBlock 0182 <span class="comment">% Start a new block</span> 0183 inBlock = true; 0184 0185 <span class="comment">% Only save the block if its class name is desired</span> 0186 <span class="keyword">if</span> noClassnames 0187 saveBlock = true; 0188 nBlocks = nBlocks + 1; 0189 data(nBlocks).class = field; 0190 data(nBlocks).fields = {}; 0191 <span class="keyword">else</span> 0192 [saveBlock, classIdx] = <span class="keyword">...</span> 0193 ismember(lower(field), classnames); 0194 0195 <span class="keyword">if</span> saveBlock 0196 data(classIdx).fields{end+1} = {}; 0197 <span class="keyword">end</span> 0198 <span class="keyword">end</span> 0199 <span class="keyword">elseif</span> saveBlock 0200 <span class="comment">% Continue the previous block</span> 0201 <span class="keyword">if</span> noClassnames 0202 data(nBlocks).fields{end+1} = field; 0203 <span class="keyword">else</span> 0204 data(classIdx).fields{end}{end+1} = field; 0205 <span class="keyword">end</span> 0206 <span class="keyword">end</span> 0207 <span class="keyword">end</span> 0208 0209 <span class="comment">% Close block?</span> 0210 <span class="keyword">if</span> ~isempty(semIdx) 0211 inBlock = false; 0212 <span class="keyword">end</span> 0213 <span class="keyword">end</span> 0214 0215 <span class="keyword">if</span> syntaxerr 0216 error(<span class="string">'Syntax error: %s'</span>, syntaxmsg); 0217 <span class="keyword">end</span> 0218 0219 <span class="comment">% Free unused spaces (if any)</span> 0220 <span class="keyword">if</span> noClassnames 0221 data((1+nBlocks):end) = []; 0222 <span class="keyword">end</span> 0223 <span class="keyword">end</span></pre></div> <hr><address>EnergyPlus Co-simulation Toolbox &copy; 2018</address> </body> </html> <|start_filename|>doc/functionIndex/examples/legacy_example/mlepMatlab_variables_cfg_example.html<|end_filename|> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>Description of mlepMatlab_variables_cfg_example</title> <meta name="keywords" content="mlepMatlab_variables_cfg_example"> <meta name="description" content="% Co-simulation example - specify I/O in variables.cfg"> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="generator" content="m2html v1.5 &copy; 2003-2005 <NAME>"> <meta name="robots" content="index, follow"> <link type="text/css" rel="stylesheet" href="../../m2html.css"> </head> <body> <a name="_top"></a> <div><a href="../../functionIndex.html">Home</a> &gt; <a href="#">examples</a> &gt; <a href="functionIndex.html">legacy_example</a> &gt; mlepMatlab_variables_cfg_example.m</div> <!--<table width="100%"><tr><td align="left"><a href="../../functionIndex.html"><img alt="<" border="0" src="../../left.png">&nbsp;Master index</a></td> <td align="right"><a href="functionIndex.html">Index for examples\legacy_example&nbsp;<img alt=">" border="0" src="../../right.png"></a></td></tr></table>--> <h1>mlepMatlab_variables_cfg_example </h1> <h2><a name="_name"></a>PURPOSE <a href="#_top"><img alt="^" border="0" src="../../up.png"></a></h2> <div class="box"><strong>% Co-simulation example - specify I/O in variables.cfg</strong></div> <h2><a name="_synopsis"></a>SYNOPSIS <a href="#_top"><img alt="^" border="0" src="../../up.png"></a></h2> <div class="box"><strong>This is a script file. </strong></div> <h2><a name="_description"></a>DESCRIPTION <a href="#_top"><img alt="^" border="0" src="../../up.png"></a></h2> <div class="fragment"><pre class="comment">% Co-simulation example - specify I/O in variables.cfg Demonstrates the functionality of the mlep (MatLab-EnergyPlus) tool in a small office building simulation scenario. Note that a start of the simulation period as well as a timestep and an input/output configuration is defined by the the EnergyPlus simulation configuration file (.IDF). Climatic conditions are obtained from a EnergyPlus Weather data file (.EPW). See also: <a href="mlepMatlab_so_example.html" class="code" title="">mlepMatlab_so_example</a>.m, mlepSimulink_example.slx</pre></div> <!-- crossreference --> <h2><a name="_cross"></a>CROSS-REFERENCE INFORMATION <a href="#_top"><img alt="^" border="0" src="../../up.png"></a></h2> This function calls: <ul style="list-style-image:url(../../matlabicon.gif)"> </ul> This function is called by: <ul style="list-style-image:url(../../matlabicon.gif)"> </ul> <!-- crossreference --> <h2><a name="_source"></a>SOURCE CODE <a href="#_top"><img alt="^" border="0" src="../../up.png"></a></h2> <div class="fragment"><pre>0001 <span class="comment">%% Co-simulation example - specify I/O in variables.cfg</span> 0002 <span class="comment">% Demonstrates the functionality of the mlep (MatLab-EnergyPlus) tool in</span> 0003 <span class="comment">% a small office building simulation scenario.</span> 0004 <span class="comment">%</span> 0005 <span class="comment">% Note that a start of the simulation period as well as a timestep and</span> 0006 <span class="comment">% an input/output configuration is defined by the the EnergyPlus simulation</span> 0007 <span class="comment">% configuration file (.IDF). Climatic conditions are obtained from a</span> 0008 <span class="comment">% EnergyPlus Weather data file (.EPW).</span> 0009 <span class="comment">%</span> 0010 <span class="comment">% See also: mlepMatlab_so_example.m, mlepSimulink_example.slx</span> 0011 0012 <span class="comment">%% Create mlep instance and configure it</span> 0013 0014 <span class="comment">% Instantiate co-simulation tool</span> 0015 ep = mlep; 0016 0017 <span class="comment">% Building simulation configuration file</span> 0018 ep.idfFile = <span class="string">'SmOffPSZ'</span>; 0019 0020 <span class="comment">% Weather file</span> 0021 ep.epwFile = <span class="string">'USA_IL_Chicago-OHare.Intl.AP.725300_TMY3'</span>; 0022 0023 <span class="comment">% Initialize the co-simulation.</span> 0024 <span class="comment">% Note: Two configurations of inputs/outputs are present in this example.</span> 0025 <span class="comment">% It was therefore necessary to call initialization routine separately. In</span> 0026 <span class="comment">% the case of one fixed setting you can use just the 'start' method (e.g.</span> 0027 <span class="comment">% 'ep.start').</span> 0028 ep.initialize; 0029 0030 <span class="comment">%% Input/output configuration</span> 0031 <span class="comment">% If there is no &quot;variables.cfg&quot; config file present in the directory</span> 0032 <span class="comment">% where the IDF file resides, then the IDF file is parsed for configured</span> 0033 <span class="comment">% inputs/outputs (and &quot;variables.cfg&quot; file is created under output directory</span> 0034 <span class="comment">% - named 'eplusout' by default). If a user-defined &quot;variables.cfg&quot; is</span> 0035 <span class="comment">% present then it should contain a subset of the IDF I/O and it defines</span> 0036 <span class="comment">% the co-simulation inputs/outputs.</span> 0037 0038 <span class="comment">% Display inputs/outputs defined in the IDF file. (no &quot;variables.cfg&quot; file</span> 0039 <span class="comment">% present).</span> 0040 disp(<span class="string">'Input/output configuration without the &quot;variables.cfg&quot; file present.'</span>); 0041 inputTable = ep.inputTable <span class="comment">%#ok&lt;*NASGU,*NOPTS&gt;</span> 0042 outputTable = ep.outputTable 0043 0044 <span class="comment">% Now with the &quot;variables.cfg&quot; file (example file contains a subset of the</span> 0045 <span class="comment">% IDF i/o set).</span> 0046 cd(fileparts(mfilename(<span class="string">'fullpath'</span>))); 0047 copyfile(<span class="string">'variables_example.cfg'</span>,<span class="string">'variables.cfg'</span>); 0048 0049 <span class="comment">% Re-initialize</span> 0050 ep.initialize; 0051 0052 disp(<span class="string">'Input/output configuration with the &quot;variables.cfg&quot; file present.'</span>); 0053 inputTable = ep.inputTable 0054 outputTable = ep.outputTable 0055 0056 <span class="comment">% The IDF i/o configuration can still be viewed</span> 0057 disp(<span class="string">'Alternative way to obtain IDF input/output configuration.'</span>); 0058 inputTableIDF = ep.idfData.inputTable 0059 outputTableIDF = ep.idfData.outputTable 0060 0061 <span class="comment">%% Simulate</span> 0062 0063 <span class="comment">% Specify simulation duration</span> 0064 endTime = 4*24*60*60; <span class="comment">%[s]</span> 0065 0066 <span class="comment">% Prepare data logging</span> 0067 nRows = ceil(endTime / ep.timestep); <span class="comment">%Query timestep after mlep initialization</span> 0068 logTable = table(<span class="string">'Size'</span>,[0, 1 + ep.nOut],<span class="keyword">...</span> 0069 <span class="string">'VariableTypes'</span>,repmat({<span class="string">'double'</span>},1,1 + ep.nOut),<span class="keyword">...</span> 0070 <span class="string">'VariableNames'</span>,[{<span class="string">'Time'</span>}; ep.outputSigName]); 0071 iLog = 1; 0072 0073 <span class="comment">% Start the co-simulation process and communication.</span> 0074 ep.start 0075 0076 <span class="comment">% The simulation loop</span> 0077 t = 0; 0078 <span class="keyword">while</span> t &lt; endTime 0079 <span class="comment">% Prepare inputs (possibly from last outputs)</span> 0080 u = [20 25]; 0081 0082 <span class="comment">% Get outputs from EnergyPlus</span> 0083 [y, t] = ep.read; 0084 0085 <span class="comment">% Send inputs to EnergyPlus</span> 0086 ep.write(u,t); 0087 0088 <span class="comment">% Log</span> 0089 logTable(iLog, :) = num2cell([t y(:)']); 0090 iLog = iLog + 1; 0091 <span class="keyword">end</span> 0092 <span class="comment">% Stop co-simulation process</span> 0093 ep.stop; 0094 0095 <span class="comment">%% Plot results</span> 0096 0097 plot(seconds(table2array(logTable(:,1))),<span class="keyword">...</span> 0098 table2array(logTable(:,2:end))); 0099 xtickformat(<span class="string">'hh:mm:ss'</span>); 0100 legend(logTable.Properties.VariableNames(2:end),<span class="string">'Interpreter'</span>,<span class="string">'none'</span>); 0101 0102 title(ep.idfFile); 0103 xlabel(<span class="string">'Time [hh:mm:ss]'</span>); 0104 ylabel(<span class="string">'Temperature [C]'</span>); 0105 0106 <span class="comment">%% Clean up</span> 0107 delete variables.cfg</pre></div> <hr><address>EnergyPlus Co-simulation Toolbox &copy; 2018</address> </body> </html> <|start_filename|>doc/functionIndex/@mlep/decodePacket.html<|end_filename|> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>Description of decodePacket</title> <meta name="keywords" content="decodePacket"> <meta name="description" content="DECODEPACKET - Decode packet to data."> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="generator" content="m2html v1.5 &copy; 2003-2005 <NAME>"> <meta name="robots" content="index, follow"> <link type="text/css" rel="stylesheet" href="../m2html.css"> </head> <body> <a name="_top"></a> <div><a href="../functionIndex.html">Home</a> &gt; <a href="functionIndex.html">@mlep</a> &gt; decodePacket.m</div> <!--<table width="100%"><tr><td align="left"><a href="../functionIndex.html"><img alt="<" border="0" src="../left.png">&nbsp;Master index</a></td> <td align="right"><a href="functionIndex.html">Index for @mlep&nbsp;<img alt=">" border="0" src="../right.png"></a></td></tr></table>--> <h1>decodePacket </h1> <h2><a name="_name"></a>PURPOSE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="box"><strong>DECODEPACKET - Decode packet to data.</strong></div> <h2><a name="_synopsis"></a>SYNOPSIS <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="box"><strong>function [flag, timevalue, realvalues, intvalues, boolvalues] = decodePacket(packet) </strong></div> <h2><a name="_description"></a>DESCRIPTION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="fragment"><pre class="comment">DECODEPACKET - Decode packet to data. Decode a packet (a string) to data. The packet format follows the BCVTB co-simulation communication protocol . Syntax: [flag, timevalue, realvalues, intvalues, boolvalues] = mlepDecodePacket(packet) Inputs: packet: the packet to be decoded (a string). Outputs: flag - An integer specifying the (status) flag. Refer to the BCVTB protocol for allowed flag values. timevalue - A real value which is the current simulation time in seconds. realvalues - A vector of received real value data. intvalues - a vector of received integer value data. boolvalues - a vector of received boolean value data. Each of the received data vector can be empty if there is no data of that type sent. Protocol Version 1 &amp; 2: Packet has the form: &quot;v f dr di db t r1 r2 ... i1 i2 ... b1 b2 ... \n&quot; where v - version number (1,2) f - flag (0: communicate, 1: finish, -10: initialization error, -20: time integration error, -1: unknown error) dr - number of real values di - number of integer values db - number of boolean values t - current simulation time in seconds (format %20.15e) r1 r2 ... are real values (format %20.15e) i1 i2 ... are integer values (format %d) b1 b2 ... are boolean values (format %d) \n - carriage return Note that if f is non-zero, other values after it will not be processed. See also: <a href="mlep.html" class="code" title="">MLEP</a>.<a href="encodeData.html" class="code" title="function packet = encodeData(vernumber, flag, timevalue, realvalues, intvalues, boolvalues)">ENCODEDATA</a>, <a href="mlep.html" class="code" title="">MLEP</a>.<a href="encodeRealData.html" class="code" title="function packet = encodeRealData(vernumber, flag, timevalue, realvalues)">ENCODEREALDATA</a>, <a href="mlep.html" class="code" title="">MLEP</a>.<a href="encodeStatus.html" class="code" title="function packet = encodeStatus(vernumber, flag)">ENCODESTATUS</a>, READ (C) 2010, <NAME> (<EMAIL>)</pre></div> <!-- crossreference --> <h2><a name="_cross"></a>CROSS-REFERENCE INFORMATION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> This function calls: <ul style="list-style-image:url(../matlabicon.gif)"> </ul> This function is called by: <ul style="list-style-image:url(../matlabicon.gif)"> </ul> <!-- crossreference --> <h2><a name="_source"></a>SOURCE CODE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="fragment"><pre>0001 <a name="_sub0" href="#_subfunctions" class="code">function [flag, timevalue, realvalues, intvalues, boolvalues] = decodePacket(packet)</a> 0002 <span class="comment">%DECODEPACKET - Decode packet to data.</span> 0003 <span class="comment">%Decode a packet (a string) to data. The packet format follows the</span> 0004 <span class="comment">%BCVTB co-simulation communication protocol .</span> 0005 <span class="comment">%</span> 0006 <span class="comment">% Syntax: [flag, timevalue, realvalues, intvalues, boolvalues] = mlepDecodePacket(packet)</span> 0007 <span class="comment">%</span> 0008 <span class="comment">% Inputs:</span> 0009 <span class="comment">% packet: the packet to be decoded (a string).</span> 0010 <span class="comment">%</span> 0011 <span class="comment">% Outputs:</span> 0012 <span class="comment">% flag - An integer specifying the (status) flag. Refer to the BCVTB</span> 0013 <span class="comment">% protocol for allowed flag values.</span> 0014 <span class="comment">% timevalue - A real value which is the current simulation time in</span> 0015 <span class="comment">% seconds.</span> 0016 <span class="comment">% realvalues - A vector of received real value data.</span> 0017 <span class="comment">% intvalues - a vector of received integer value data.</span> 0018 <span class="comment">% boolvalues - a vector of received boolean value data.</span> 0019 <span class="comment">%</span> 0020 <span class="comment">% Each of the received data vector can be empty if there is no data</span> 0021 <span class="comment">% of that type sent.</span> 0022 <span class="comment">%</span> 0023 <span class="comment">% Protocol Version 1 &amp; 2:</span> 0024 <span class="comment">% Packet has the form:</span> 0025 <span class="comment">% &quot;v f dr di db t r1 r2 ... i1 i2 ... b1 b2 ... \n&quot;</span> 0026 <span class="comment">% where</span> 0027 <span class="comment">% v - version number (1,2)</span> 0028 <span class="comment">% f - flag (0: communicate, 1: finish, -10: initialization error,</span> 0029 <span class="comment">% -20: time integration error, -1: unknown error)</span> 0030 <span class="comment">% dr - number of real values</span> 0031 <span class="comment">% di - number of integer values</span> 0032 <span class="comment">% db - number of boolean values</span> 0033 <span class="comment">% t - current simulation time in seconds (format %20.15e)</span> 0034 <span class="comment">% r1 r2 ... are real values (format %20.15e)</span> 0035 <span class="comment">% i1 i2 ... are integer values (format %d)</span> 0036 <span class="comment">% b1 b2 ... are boolean values (format %d)</span> 0037 <span class="comment">% \n - carriage return</span> 0038 <span class="comment">%</span> 0039 <span class="comment">% Note that if f is non-zero, other values after it will not be processed.</span> 0040 <span class="comment">%</span> 0041 <span class="comment">% See also: MLEP.ENCODEDATA, MLEP.ENCODEREALDATA, MLEP.ENCODESTATUS,</span> 0042 <span class="comment">% READ</span> 0043 <span class="comment">%</span> 0044 <span class="comment">% (C) 2010, <NAME> (<EMAIL>)</span> 0045 0046 <span class="comment">% Remove non-printable characters from packet, then</span> 0047 <span class="comment">% convert packet string to a vector of numbers</span> 0048 [data, status] = str2num(packet(isstrprop(packet, <span class="string">'print'</span>))); <span class="comment">% This function is very fast</span> 0049 <span class="keyword">if</span> ~status 0050 error(<span class="string">'Error while parsing the packet string: %s'</span>, packet); 0051 <span class="keyword">end</span> 0052 0053 <span class="comment">% Check data</span> 0054 datalen = length(data); 0055 <span class="keyword">if</span> datalen &lt; 2 0056 error(<span class="string">'Invalid packet format: length is only %d.'</span>, datalen); 0057 <span class="keyword">end</span> 0058 0059 <span class="comment">% data(1) is version number</span> 0060 <span class="keyword">if</span> data(1) &lt;= 2 0061 <span class="comment">% Get the flag number</span> 0062 flag = data(2); 0063 0064 realvalues = []; 0065 intvalues = []; 0066 boolvalues = []; 0067 0068 <span class="keyword">if</span> flag == 0 <span class="comment">% Read on</span> 0069 <span class="keyword">if</span> datalen &lt; 5 0070 error(<span class="string">'Invalid packet: lacks lengths of data.'</span>); 0071 <span class="keyword">end</span> 0072 0073 data(3:5) = fix(data(3:5)); 0074 pos1 = data(3) + data(4); 0075 pos2 = pos1 + data(5); 0076 <span class="keyword">if</span> 6 + pos2 &gt; datalen 0077 error(<span class="string">'Invalid packet: not enough data.'</span>); 0078 <span class="keyword">end</span> 0079 0080 <span class="comment">% Now read data to vectors</span> 0081 timevalue = data(6); 0082 realvalues = data(7:6+data(3)); 0083 intvalues = data(7+data(3):6+pos1); 0084 boolvalues = logical(data(7+pos1:6+pos2)); 0085 <span class="keyword">else</span> 0086 <span class="comment">% Non-zero flag --&gt; don't need to read on</span> 0087 timevalue = []; 0088 <span class="keyword">end</span> 0089 0090 <span class="keyword">else</span> 0091 error(<span class="string">'Unsupported packet format version: %g.'</span>, data(1)); 0092 <span class="keyword">end</span> 0093 0094 <span class="keyword">end</span> 0095</pre></div> <hr><address>EnergyPlus Co-simulation Toolbox &copy; 2018</address> </body> </html> <|start_filename|>doc/functionIndex/library/vector2Bus_clbk.html<|end_filename|> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>Description of vector2Bus_clbk</title> <meta name="keywords" content="vector2Bus_clbk"> <meta name="description" content="VECTOR2BUS_CLBK - Callback functions."> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="generator" content="m2html v1.5 &copy; 2003-2005 <NAME>"> <meta name="robots" content="index, follow"> <link type="text/css" rel="stylesheet" href="../m2html.css"> </head> <body> <a name="_top"></a> <div><a href="../functionIndex.html">Home</a> &gt; <a href="functionIndex.html">library</a> &gt; vector2Bus_clbk.m</div> <!--<table width="100%"><tr><td align="left"><a href="../functionIndex.html"><img alt="<" border="0" src="../left.png">&nbsp;Master index</a></td> <td align="right"><a href="functionIndex.html">Index for library&nbsp;<img alt=">" border="0" src="../right.png"></a></td></tr></table>--> <h1>vector2Bus_clbk </h1> <h2><a name="_name"></a>PURPOSE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="box"><strong>VECTOR2BUS_CLBK - Callback functions.</strong></div> <h2><a name="_synopsis"></a>SYNOPSIS <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="box"><strong>function vector2Bus_clbk(block, type) </strong></div> <h2><a name="_description"></a>DESCRIPTION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="fragment"><pre class="comment">VECTOR2BUS_CLBK - Callback functions. Valid type options are 'popup', 'initMask', 'InitFcn', 'CopyFcn'.</pre></div> <!-- crossreference --> <h2><a name="_cross"></a>CROSS-REFERENCE INFORMATION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> This function calls: <ul style="list-style-image:url(../matlabicon.gif)"> </ul> This function is called by: <ul style="list-style-image:url(../matlabicon.gif)"> </ul> <!-- crossreference --> <h2><a name="_subfunctions"></a>SUBFUNCTIONS <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <ul style="list-style-image:url(../matlabicon.gif)"> <li><a href="#_sub1" class="code">function vector2Bus_popup(block)</a></li><li><a href="#_sub2" class="code">function vector2Bus_maskInit(block)</a></li><li><a href="#_sub3" class="code">function vector2Bus_InitFcn(block)</a></li><li><a href="#_sub4" class="code">function vector2Bus_CopyFcn(block)</a></li><li><a href="#_sub5" class="code">function busObj = getBusObject(model, busType)</a></li><li><a href="#_sub6" class="code">function busType = getBusTypeFromBusTypeStr(busTypeStr)</a></li><li><a href="#_sub7" class="code">function createConnection(block, nSignals)</a></li></ul> <h2><a name="_source"></a>SOURCE CODE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="fragment"><pre>0001 <a name="_sub0" href="#_subfunctions" class="code">function vector2Bus_clbk(block, type)</a> 0002 <span class="comment">%VECTOR2BUS_CLBK - Callback functions.</span> 0003 <span class="comment">% Valid type options are 'popup', 'initMask', 'InitFcn', 'CopyFcn'.</span> 0004 0005 <span class="comment">% Copyright (c) 2018, <NAME> (<EMAIL>)</span> 0006 <span class="comment">% All rights reserved.</span> 0007 0008 <span class="comment">% String to be displayed when no Bus object is selected</span> 0009 default_str = <span class="string">'Select a Bus object...'</span>; 0010 0011 <span class="comment">% String to be displayed when no Bus object is found</span> 0012 empty_str = <span class="string">'No Bus objects found.'</span>; 0013 0014 <span class="keyword">switch</span> type 0015 <span class="keyword">case</span> <span class="string">'popup'</span> 0016 <a href="#_sub1" class="code" title="subfunction vector2Bus_popup(block)">vector2Bus_popup</a>(block); 0017 <span class="keyword">case</span> <span class="string">'maskInit'</span> 0018 <a href="#_sub2" class="code" title="subfunction vector2Bus_maskInit(block)">vector2Bus_maskInit</a>(block); 0019 <span class="keyword">case</span> <span class="string">'InitFcn'</span> 0020 <a href="#_sub3" class="code" title="subfunction vector2Bus_InitFcn(block)">vector2Bus_InitFcn</a>(block); 0021 <span class="keyword">case</span> <span class="string">'CopyFcn'</span> 0022 <a href="#_sub4" class="code" title="subfunction vector2Bus_CopyFcn(block)">vector2Bus_CopyFcn</a>(block); 0023 <span class="keyword">otherwise</span> 0024 error(<span class="string">'Unknown callback: ''%s.'''</span>, type); 0025 <span class="keyword">end</span> 0026 0027 <a name="_sub1" href="#_subfunctions" class="code">function vector2Bus_popup(block)</a> 0028 <span class="comment">% Using variable names terminated with &quot;_BOBC&quot; to lessen the chances of</span> 0029 <span class="comment">% collisions with existing workspace variables.</span> 0030 0031 <span class="comment">% Get the current block handle and mask handle.</span> 0032 maskObj = Simulink.Mask.get(block); 0033 popupParam = maskObj.getParameter(<span class="string">'busType'</span>); 0034 0035 <span class="comment">% --- Find Bus objects ---</span> 0036 <span class="comment">% Get base workspace variables</span> 0037 bwVars = evalin(<span class="string">'base'</span>,<span class="string">'whos'</span>); 0038 allBusNames = {}; 0039 <span class="keyword">if</span> ~isempty(bwVars) 0040 flag = strcmp({bwVars.class},<span class="string">'Simulink.Bus'</span>); 0041 allBusNames = {bwVars(flag).name}; 0042 <span class="keyword">end</span> 0043 0044 <span class="comment">% Get Data dictionary variables</span> 0045 ddName = get_param(bdroot(block),<span class="string">'DataDictionary'</span>); 0046 <span class="keyword">if</span> ~isempty(ddName) 0047 dd = Simulink.data.dictionary.open(ddName); 0048 ddSec = getSection(dd,<span class="string">'Design Data'</span>); 0049 ddVars = find(ddSec,<span class="string">'-value'</span>,<span class="string">'-class'</span>,<span class="string">'Simulink.Bus'</span>); <span class="comment">%#ok&lt;GTARG&gt;</span> 0050 allBusNames = [allBusNames {ddVars.Name}]; 0051 <span class="keyword">end</span> 0052 0053 <span class="comment">% --- Create popup ---</span> 0054 <span class="comment">% Create popup entries</span> 0055 busOpts = strcat({<span class="string">'Bus: '</span>}, allBusNames); 0056 0057 <span class="keyword">if</span> ~isempty(busOpts) 0058 <span class="comment">% Add default option</span> 0059 extOpts = [{default_str}, busOpts]; 0060 0061 <span class="comment">% Current number of options</span> 0062 old_opts = popupParam.TypeOptions; 0063 0064 <span class="comment">% Fill out the BusType options</span> 0065 <span class="keyword">if</span> ~strcmp([old_opts{:}],[extOpts{:}]) 0066 popupParam.TypeOptions = extOpts; 0067 <span class="keyword">end</span> 0068 <span class="keyword">else</span> 0069 popupParam.TypeOptions = {empty_str}; 0070 <span class="keyword">end</span> 0071 0072 <span class="comment">% Internal Bus Creator handle</span> 0073 bch = get_param([block <span class="string">'/BusCreator'</span>],<span class="string">'handle'</span>); 0074 0075 <span class="comment">% --- Mask popup functionality ---</span> 0076 <span class="comment">% all options that can happen, hopefully</span> 0077 currentOutDataTypeStr = get_param(bch, <span class="string">'OutDataTypeStr'</span>); 0078 selectedDataType = get_param(block,<span class="string">'busType'</span>); 0079 lastManuallySelectedParam = popupParam.Value; 0080 0081 <span class="keyword">if</span> strcmp(currentOutDataTypeStr,<span class="string">'Inherit: auto'</span>) 0082 <span class="keyword">if</span> ~ismember(selectedDataType,{default_str, empty_str}) 0083 <span class="comment">% = Previously unused block and valid selection</span> 0084 <span class="comment">% Set Output Data Type to the selected value</span> 0085 set_param(bch, <span class="string">'OutDataTypeStr'</span>,selectedDataType); 0086 set_param(block,<span class="string">'busType'</span>,selectedDataType); 0087 popupParam.Value = selectedDataType; 0088 <span class="keyword">end</span> 0089 <span class="keyword">else</span> 0090 <span class="keyword">if</span> strcmp(lastManuallySelectedParam,selectedDataType) &amp;&amp; <span class="keyword">...</span> 0091 strcmp(currentOutDataTypeStr, selectedDataType) 0092 <span class="comment">% = no change</span> 0093 <span class="comment">% Do nothing, nothing changed</span> 0094 <span class="keyword">elseif</span> ismember(selectedDataType,{default_str}) || <span class="keyword">...</span> 0095 (~strcmp(lastManuallySelectedParam,selectedDataType) &amp;&amp; <span class="keyword">...</span> 0096 strcmp(lastManuallySelectedParam,currentOutDataTypeStr)) 0097 <span class="comment">% = default or empty selected, or option has disappeared</span> 0098 <span class="comment">% Keep the Output data type and try to select the popup</span> 0099 <span class="comment">% option pertaining to the Output data type</span> 0100 <span class="keyword">if</span> ismember(currentOutDataTypeStr, busOpts) 0101 set_param(block,<span class="string">'busType'</span>,currentOutDataTypeStr); 0102 popupParam.Value = currentOutDataTypeStr; 0103 <span class="keyword">else</span> 0104 set_param(block,<span class="string">'busType'</span>,default_str); 0105 popupParam.Value = default_str; 0106 <span class="keyword">end</span> 0107 <span class="keyword">elseif</span> strcmp(lastManuallySelectedParam,selectedDataType) &amp;&amp; <span class="keyword">...</span> 0108 ismember(currentOutDataTypeStr, busOpts) 0109 <span class="comment">% = bus objects changed, but the output type is still</span> 0110 <span class="comment">% available</span> 0111 <span class="comment">% Keep the Output data type and try to select the popup</span> 0112 <span class="comment">% option pertaining to the Output data type</span> 0113 set_param(block,<span class="string">'busType'</span>,currentOutDataTypeStr); 0114 popupParam.Value = currentOutDataTypeStr; 0115 <span class="keyword">elseif</span> ~strcmp(lastManuallySelectedParam,selectedDataType) 0116 <span class="comment">% = new bus option selected</span> 0117 <span class="comment">% Set Output Data Type to the selected value</span> 0118 set_param(bch, <span class="string">'OutDataTypeStr'</span>,selectedDataType); 0119 set_param(block,<span class="string">'busType'</span>,selectedDataType); 0120 popupParam.Value = selectedDataType; 0121 <span class="keyword">else</span> 0122 <span class="comment">% = bus object changed and the current selection is missing</span> 0123 <span class="comment">% Actually, it is not possible in connection to mlep.</span> 0124 set_param(bch, <span class="string">'OutDataTypeStr'</span>,<span class="string">'Inherit: auto'</span>); 0125 <span class="keyword">end</span> 0126 <span class="keyword">end</span> 0127 0128 <span class="comment">% Set the options to the BusCreator block</span> 0129 set_param(bch,<span class="string">'InheritFromInputs'</span>, <span class="string">'off'</span>); 0130 <span class="keyword">end</span> 0131 0132 <a name="_sub2" href="#_subfunctions" class="code">function vector2Bus_maskInit(block)</a> 0133 <span class="comment">% Create demux and bus creator inside. Serves also is an indicator</span> 0134 <span class="comment">% for bus selection validity</span> 0135 0136 <span class="comment">%% Validate busType</span> 0137 0138 <span class="comment">% Get current option</span> 0139 selectedBusTypeStr = get_param(block, <span class="string">'busType'</span>); 0140 0141 <span class="keyword">if</span> ismember(selectedBusTypeStr,{default_str, empty_str}) || <span class="keyword">...</span> 0142 isempty(regexp(selectedBusTypeStr,<span class="string">'Bus: '</span>,<span class="string">'ONCE'</span>)) 0143 <span class="keyword">return</span> 0144 <span class="keyword">end</span> 0145 0146 <span class="comment">% Get Bus Type</span> 0147 busType = <a href="#_sub6" class="code" title="subfunction busType = getBusTypeFromBusTypeStr(busTypeStr)">getBusTypeFromBusTypeStr</a>(selectedBusTypeStr); 0148 0149 <span class="comment">% Get Bus object</span> 0150 model = bdroot(block); 0151 busObj = <a href="#_sub5" class="code" title="subfunction busObj = getBusObject(model, busType)">getBusObject</a>(model, busType); 0152 0153 <span class="comment">% Check the busObj</span> 0154 <span class="keyword">if</span> isempty(busObj) 0155 warning(<span class="string">'Simulink.Bus object ''%s'' not found in a data dictionary nor the base workspace.'</span>,<span class="keyword">...</span> 0156 busType); 0157 <span class="keyword">return</span> 0158 <span class="keyword">end</span> 0159 0160 <span class="comment">% Get the desired number of elements</span> 0161 nSignals = busObj.getNumLeafBusElements; 0162 0163 <span class="comment">% Set internal Demux, Bus Creator and connect</span> 0164 <a href="#_sub7" class="code" title="subfunction createConnection(block, nSignals)">createConnection</a>(block, nSignals); 0165 0166 <span class="keyword">end</span> 0167 0168 <a name="_sub3" href="#_subfunctions" class="code">function vector2Bus_InitFcn(block)</a> 0169 <span class="comment">% Check if Output Data Bus object is available, set &quot;Inherit:auto&quot;</span> 0170 <span class="comment">% if not to allow for its creation elsewhere</span> 0171 0172 <span class="comment">% Validate</span> 0173 <a href="#_sub1" class="code" title="subfunction vector2Bus_popup(block)">vector2Bus_popup</a>(block); 0174 0175 <span class="comment">% Internal Bus Creator handle</span> 0176 bch = get_param([block <span class="string">'/BusCreator'</span>],<span class="string">'handle'</span>); 0177 0178 <span class="comment">% Get current Output data</span> 0179 currentOutDataTypeStr = get_param(bch, <span class="string">'OutDataTypeStr'</span>); 0180 0181 <span class="keyword">if</span> ~strcmp(currentOutDataTypeStr, <span class="string">'Inherit: auto'</span>) 0182 <span class="comment">% Get Bus Type</span> 0183 busType = <a href="#_sub6" class="code" title="subfunction busType = getBusTypeFromBusTypeStr(busTypeStr)">getBusTypeFromBusTypeStr</a>(currentOutDataTypeStr); 0184 0185 <span class="comment">% Get Bus object</span> 0186 model = bdroot(block); 0187 0188 <span class="comment">% Validate bus object</span> 0189 <span class="keyword">if</span> isempty(<a href="#_sub5" class="code" title="subfunction busObj = getBusObject(model, busType)">getBusObject</a>(model, busType)) 0190 <span class="comment">%Give error</span> 0191 hilite_system(block); 0192 error(<span class="string">'''%s'': Selected Bus object ''%s'' doesn''t exists in the base workspace nor in any linked data dictionary.'</span>, block, busType); 0193 <span class="keyword">end</span> 0194 <span class="keyword">end</span> 0195 <span class="keyword">end</span> 0196 0197 <a name="_sub4" href="#_subfunctions" class="code">function vector2Bus_CopyFcn(block)</a> 0198 <span class="comment">% Disable library link</span> 0199 set_param(block,<span class="string">'LinkStatus'</span>,<span class="string">'none'</span>); 0200 set_param(block,<span class="string">'CopyFcn'</span>,<span class="string">''</span>); 0201 <span class="keyword">end</span> 0202 0203 <a name="_sub5" href="#_subfunctions" class="code">function busObj = getBusObject(model, busType)</a> 0204 <span class="comment">% Load the selected Bus object</span> 0205 busObj = []; 0206 mws = get_param(model,<span class="string">'ModelWorkspace'</span>); 0207 <span class="keyword">if</span> Simulink.data.existsInGlobal(model,busType) 0208 <span class="comment">% From Data Dictionary first</span> 0209 busObj = Simulink.data.evalinGlobal(model,busType); 0210 <span class="comment">% elseif hasVariable(mws,busType)</span> 0211 <span class="comment">% % From Model workspace next (maybe it will be allowed in the</span> 0212 <span class="comment">% % future)</span> 0213 <span class="comment">% busObj = getVariable(mws, busType);</span> 0214 <span class="keyword">elseif</span> evalin(<span class="string">'base'</span>,[<span class="string">'exist('''</span> busType <span class="string">''',''var'')'</span>]) 0215 <span class="comment">% From Base workspace last</span> 0216 busObj = evalin(<span class="string">'base'</span>,busType); 0217 <span class="keyword">end</span> 0218 <span class="keyword">end</span> 0219 <span class="keyword">end</span> 0220 0221 <a name="_sub6" href="#_subfunctions" class="code">function busType = getBusTypeFromBusTypeStr(busTypeStr)</a> 0222 <span class="comment">% ... and parse off &quot;Bus: &quot; so the string of the desired bus contained in</span> 0223 <span class="comment">% 'OutDataTypeStr' matches the raw workspace bus names.</span> 0224 busType = regexp(busTypeStr,<span class="string">'^Bus: (.*)'</span>,<span class="string">'tokens'</span>); 0225 assert(~isempty(busType)); 0226 busType = busType{1}{1}; 0227 <span class="keyword">end</span> 0228 0229 <a name="_sub7" href="#_subfunctions" class="code">function createConnection(block, nSignals)</a> 0230 <span class="comment">%% Create demux, bus creator and connect them</span> 0231 0232 <span class="comment">% Get the current vector size</span> 0233 nDemuxSignals = str2double(get_param([block <span class="string">'/Demux'</span>],<span class="string">'Outputs'</span>)); 0234 nBCSignals = str2double(get_param([block <span class="string">'/BusCreator'</span>],<span class="string">'Inputs'</span>)); 0235 0236 <span class="keyword">if</span> nDemuxSignals ~= nBCSignals 0237 <span class="comment">% Recreate the block completely</span> 0238 0239 <span class="comment">% Find lines</span> 0240 lines = find_system(gcb, <span class="keyword">...</span> 0241 <span class="string">'LookUnderMasks'</span>,<span class="string">'all'</span>,<span class="keyword">...</span> 0242 <span class="string">'FindAll'</span>,<span class="string">'on'</span>,<span class="keyword">...</span> 0243 <span class="string">'type'</span>,<span class="string">'line'</span>); 0244 0245 <span class="comment">% Delete lines</span> 0246 delete_line(lines); 0247 0248 <span class="comment">% Add lines from/to ports</span> 0249 add_line(block,<span class="string">'In1/1'</span>,<span class="string">'Demux/1'</span>); 0250 add_line(block,<span class="string">'BusCreator/1'</span>,<span class="string">'Out1/1'</span>); 0251 0252 <span class="comment">% Set number of demux signals to trigger recreation</span> 0253 nDemuxSignals = 0; 0254 <span class="keyword">end</span> 0255 0256 <span class="comment">% Create connections</span> 0257 <span class="keyword">if</span> nSignals &gt; nDemuxSignals 0258 <span class="comment">% Add just the right number of lines</span> 0259 set_param([block <span class="string">'/Demux'</span>],<span class="string">'Outputs'</span>,num2str(nSignals)) 0260 set_param([block <span class="string">'/BusCreator'</span>],<span class="string">'Inputs'</span>,num2str(nSignals)) 0261 <span class="keyword">for</span> iSig = (nDemuxSignals+1):nSignals 0262 add_line(block,[<span class="string">'Demux/'</span> num2str(iSig)],[<span class="string">'BusCreator/'</span> num2str(iSig)]) 0263 <span class="keyword">end</span> 0264 <span class="keyword">elseif</span> nSignals &lt; nDemuxSignals 0265 <span class="comment">% Remove just the right number of lines</span> 0266 <span class="keyword">for</span> iSig = (nSignals+1):nDemuxSignals 0267 delete_line(block,[<span class="string">'Demux/'</span> num2str(iSig)],[<span class="string">'BusCreator/'</span> num2str(iSig)]) 0268 <span class="keyword">end</span> 0269 set_param([block <span class="string">'/Demux'</span>],<span class="string">'Outputs'</span>,num2str(nSignals)) 0270 set_param([block <span class="string">'/BusCreator'</span>],<span class="string">'Inputs'</span>,num2str(nSignals)) 0271 <span class="keyword">end</span> 0272 <span class="keyword">end</span></pre></div> <hr><address>EnergyPlus Co-simulation Toolbox &copy; 2018</address> </body> </html> <|start_filename|>doc/functionIndex/library/mlepEnergyPlusSimulation_clbk.html<|end_filename|> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>Description of mlepEnergyPlusSimulation_clbk</title> <meta name="keywords" content="mlepEnergyPlusSimulation_clbk"> <meta name="description" content="MLEPENERGYPLUSSIMULATION_CLBK - Callback functions for the 'EnergyPlus Simulation' block."> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="generator" content="m2html v1.5 &copy; 2003-2005 <NAME>"> <meta name="robots" content="index, follow"> <link type="text/css" rel="stylesheet" href="../m2html.css"> </head> <body> <a name="_top"></a> <div><a href="../functionIndex.html">Home</a> &gt; <a href="functionIndex.html">library</a> &gt; mlepEnergyPlusSimulation_clbk.m</div> <!--<table width="100%"><tr><td align="left"><a href="../functionIndex.html"><img alt="<" border="0" src="../left.png">&nbsp;Master index</a></td> <td align="right"><a href="functionIndex.html">Index for library&nbsp;<img alt=">" border="0" src="../right.png"></a></td></tr></table>--> <h1>mlepEnergyPlusSimulation_clbk </h1> <h2><a name="_name"></a>PURPOSE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="box"><strong>MLEPENERGYPLUSSIMULATION_CLBK - Callback functions for the 'EnergyPlus Simulation' block.</strong></div> <h2><a name="_synopsis"></a>SYNOPSIS <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="box"><strong>function mlepEnergyPlusSimulation_clbk(block, type, varargin) </strong></div> <h2><a name="_description"></a>DESCRIPTION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="fragment"><pre class="comment">MLEPENERGYPLUSSIMULATION_CLBK - Callback functions for the 'EnergyPlus Simulation' block.</pre></div> <!-- crossreference --> <h2><a name="_cross"></a>CROSS-REFERENCE INFORMATION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> This function calls: <ul style="list-style-image:url(../matlabicon.gif)"> </ul> This function is called by: <ul style="list-style-image:url(../matlabicon.gif)"> </ul> <!-- crossreference --> <h2><a name="_subfunctions"></a>SUBFUNCTIONS <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <ul style="list-style-image:url(../matlabicon.gif)"> <li><a href="#_sub1" class="code">function mlepEnergyPlusSimulation_OpenFcn(block)</a></li><li><a href="#_sub2" class="code">function mlepEnergyPlusSimulation_InitFcn(block)</a></li><li><a href="#_sub3" class="code">function selectedFile = mlepEnergyPlusSimulation_browseButton(block, varargin)</a></li></ul> <h2><a name="_source"></a>SOURCE CODE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="fragment"><pre>0001 <a name="_sub0" href="#_subfunctions" class="code">function mlepEnergyPlusSimulation_clbk(block, type, varargin)</a> 0002 <span class="comment">%MLEPENERGYPLUSSIMULATION_CLBK - Callback functions for the 'EnergyPlus Simulation' block.</span> 0003 0004 <span class="comment">% Copyright (c) 2018, <NAME> (<EMAIL>)</span> 0005 <span class="comment">% All rights reserved.</span> 0006 <span class="comment">%</span> 0007 0008 <span class="keyword">switch</span> type 0009 <span class="keyword">case</span> <span class="string">'OpenFcn'</span> 0010 <a href="#_sub1" class="code" title="subfunction mlepEnergyPlusSimulation_OpenFcn(block)">mlepEnergyPlusSimulation_OpenFcn</a>(block); 0011 <span class="keyword">case</span> {<span class="string">'InitFcn'</span>,<span class="string">'generateBus'</span>} 0012 <a href="#_sub2" class="code" title="subfunction mlepEnergyPlusSimulation_InitFcn(block)">mlepEnergyPlusSimulation_InitFcn</a>(block); 0013 <span class="keyword">case</span> <span class="string">'browseButton'</span> 0014 <a href="#_sub3" class="code" title="subfunction selectedFile = mlepEnergyPlusSimulation_browseButton(block, varargin)">mlepEnergyPlusSimulation_browseButton</a>(block, varargin{:}); 0015 <span class="keyword">otherwise</span> 0016 error(<span class="string">'Unknown callback: ''%s.'''</span>, type); 0017 <span class="keyword">end</span> 0018 <span class="keyword">end</span> 0019 0020 <a name="_sub1" href="#_subfunctions" class="code">function mlepEnergyPlusSimulation_OpenFcn(block)</a> 0021 0022 <span class="comment">% Mask of a System Object cannot be programatically opened (r18a). So</span> 0023 <span class="comment">% promoted parameters are used instead (at least semi-automatic way).</span> 0024 0025 <span class="comment">% Open mask</span> 0026 open_system(block,<span class="string">'mask'</span>); 0027 <span class="keyword">end</span> 0028 0029 <a name="_sub2" href="#_subfunctions" class="code">function mlepEnergyPlusSimulation_InitFcn(block)</a> 0030 <span class="comment">% Create new mlep instance (the actual existing instance is not reachable</span> 0031 <span class="comment">% at the moment) and run validate properties routine of the system object!</span> 0032 0033 <span class="keyword">if</span> strcmp(get_param(bdroot, <span class="string">'BlockDiagramType'</span>),<span class="string">'library'</span>) <span class="comment">%strcmp(get_param(bdroot, 'SimulationStatus'),'initializing')</span> 0034 <span class="keyword">return</span> 0035 <span class="keyword">end</span> 0036 0037 <span class="comment">% Get bus names</span> 0038 inputBusName = get_param(block,<span class="string">'inputBusName'</span>); 0039 outputBusName = get_param(block,<span class="string">'outputBusName'</span>); 0040 0041 <span class="comment">% Create mlep instance</span> 0042 ep = mlep; 0043 0044 <span class="comment">% Set its properties</span> 0045 ep.idfFile = get_param(block,<span class="string">'idfFile'</span>); 0046 ep.epwFile = get_param(block,<span class="string">'epwFile'</span>); 0047 ep.useDataDictionary = strcmp(<span class="keyword">...</span> 0048 get_param(block,<span class="string">'useDataDictionary'</span>),<span class="keyword">...</span> 0049 <span class="string">'on'</span>); 0050 ep.inputBusName = inputBusName; 0051 ep.outputBusName = outputBusName; 0052 0053 <span class="comment">% Load bus objects</span> 0054 loadBusObjects(ep); 0055 0056 <span class="comment">% The bus objects are available now. Set them into all necessary blocks.</span> 0057 <span class="comment">% Set Vector2Bus</span> 0058 set_param([block <span class="string">'/Vector to Bus'</span>], <span class="string">'busType'</span>, [<span class="string">'Bus: '</span> outputBusName]); 0059 vector2Bus_clbk([block <span class="string">'/Vector to Bus'</span>],<span class="string">'popup'</span>); 0060 0061 <span class="comment">% Set output</span> 0062 set_param([block <span class="string">'/Out'</span>], <span class="string">'OutDataTypeStr'</span>, [<span class="string">'Bus: '</span> outputBusName]); 0063 0064 <span class="comment">% Set input</span> 0065 set_param([block <span class="string">'/In'</span>], <span class="string">'OutDataTypeStr'</span>, [<span class="string">'Bus: '</span> inputBusName]); 0066 <span class="keyword">end</span> 0067 0068 <a name="_sub3" href="#_subfunctions" class="code">function selectedFile = mlepEnergyPlusSimulation_browseButton(block, varargin)</a> 0069 <span class="comment">%mlepEnergyPlusSimulation_browseButton Browse button callback.</span> 0070 <span class="comment">% Syntax: mlepEnergyPlusSimulation_browseButton(block, filetype) The</span> 0071 <span class="comment">% filetype is either 'IDF' or 'EPW' and the the block parameters are set or</span> 0072 <span class="comment">%</span> 0073 0074 assert(nargin == 2); 0075 validateattributes(varargin{1},{<span class="string">'char'</span>},{<span class="string">'scalartext'</span>}); 0076 filetype = validatestring(varargin{1},{<span class="string">'IDF'</span>,<span class="string">'EPW'</span>}); 0077 0078 fileNameToSet = [lower(filetype), <span class="string">'File'</span>]; <span class="comment">% 'idfFile_SO' or 'epwFile_SO'</span> 0079 0080 <span class="comment">% Ask for file</span> 0081 selectedFile = mlep.browseForFile(filetype); 0082 <span class="keyword">if</span> selectedFile ~= 0 <span class="comment">% not a Cancel button</span> 0083 <span class="keyword">if</span> isfield(get_param(block, <span class="string">'ObjectParameters'</span>),fileNameToSet) <span class="comment">% parameter exists</span> 0084 <span class="comment">% Set mask parameters</span> 0085 set_param(block, fileNameToSet, selectedFile); 0086 <span class="keyword">else</span> 0087 warning(<span class="string">'Parameter ''%s'' does not exist in block ''%s''. Not setting the selected path anywhere.'</span>, fileNameToSet, block); 0088 <span class="keyword">end</span> 0089 <span class="keyword">end</span> 0090 <span class="keyword">end</span> 0091 0092 0093</pre></div> <hr><address>EnergyPlus Co-simulation Toolbox &copy; 2018</address> </body> </html> <|start_filename|>doc/functionIndex/examples/legacy_example/mlepMatlab_so_example.html<|end_filename|> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>Description of mlepMatlab_so_example</title> <meta name="keywords" content="mlepMatlab_so_example"> <meta name="description" content="% Co-simulation example using System Object"> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="generator" content="m2html v1.5 &copy; 2003-2005 <NAME>"> <meta name="robots" content="index, follow"> <link type="text/css" rel="stylesheet" href="../../m2html.css"> </head> <body> <a name="_top"></a> <div><a href="../../functionIndex.html">Home</a> &gt; <a href="#">examples</a> &gt; <a href="functionIndex.html">legacy_example</a> &gt; mlepMatlab_so_example.m</div> <!--<table width="100%"><tr><td align="left"><a href="../../functionIndex.html"><img alt="<" border="0" src="../../left.png">&nbsp;Master index</a></td> <td align="right"><a href="functionIndex.html">Index for examples\legacy_example&nbsp;<img alt=">" border="0" src="../../right.png"></a></td></tr></table>--> <h1>mlepMatlab_so_example </h1> <h2><a name="_name"></a>PURPOSE <a href="#_top"><img alt="^" border="0" src="../../up.png"></a></h2> <div class="box"><strong>% Co-simulation example using System Object</strong></div> <h2><a name="_synopsis"></a>SYNOPSIS <a href="#_top"><img alt="^" border="0" src="../../up.png"></a></h2> <div class="box"><strong>This is a script file. </strong></div> <h2><a name="_description"></a>DESCRIPTION <a href="#_top"><img alt="^" border="0" src="../../up.png"></a></h2> <div class="fragment"><pre class="comment">% Co-simulation example using System Object Demonstrates the functionality of the mlep (MatLab-EnergyPlus) tool on a small office building simulation scenario. Note that a start of the simulation period as well as a timestep and an input/output configuration is defined by the the EnergyPlus simulation configuration file (.IDF). Climatic conditions are obtained from a EnergyPlus Weather data file (.EPW). For a detailed description of mlep usage please refere to the 'mlepMatlab_example.m' example. See also: mlepSimulink_example.slx</pre></div> <!-- crossreference --> <h2><a name="_cross"></a>CROSS-REFERENCE INFORMATION <a href="#_top"><img alt="^" border="0" src="../../up.png"></a></h2> This function calls: <ul style="list-style-image:url(../../matlabicon.gif)"> </ul> This function is called by: <ul style="list-style-image:url(../../matlabicon.gif)"> </ul> <!-- crossreference --> <h2><a name="_source"></a>SOURCE CODE <a href="#_top"><img alt="^" border="0" src="../../up.png"></a></h2> <div class="fragment"><pre>0001 <span class="comment">%% Co-simulation example using System Object</span> 0002 <span class="comment">% Demonstrates the functionality of the mlep (MatLab-EnergyPlus) tool on</span> 0003 <span class="comment">% a small office building simulation scenario.</span> 0004 <span class="comment">%</span> 0005 <span class="comment">% Note that a start of the simulation period as well as a timestep and</span> 0006 <span class="comment">% an input/output configuration is defined by the the EnergyPlus simulation</span> 0007 <span class="comment">% configuration file (.IDF). Climatic conditions are obtained from a</span> 0008 <span class="comment">% EnergyPlus Weather data file (.EPW).</span> 0009 <span class="comment">%</span> 0010 <span class="comment">% For a detailed description of mlep usage please refere to the</span> 0011 <span class="comment">% 'mlepMatlab_example.m' example.</span> 0012 <span class="comment">%</span> 0013 <span class="comment">% See also: mlepSimulink_example.slx</span> 0014 clear all 0015 0016 <span class="comment">%% Instantiate mlep and configure simulation</span> 0017 ep = mlep; 0018 ep.idfFile = <span class="string">'SmOffPSZ'</span>; 0019 ep.epwFile = <span class="string">'USA_IL_Chicago-OHare.Intl.AP.725300_TMY3'</span>; 0020 0021 <span class="comment">% Use user-defined I/O configuration</span> 0022 cd(fileparts(mfilename(<span class="string">'fullpath'</span>))); 0023 copyfile(<span class="string">'variables_example.cfg'</span>,<span class="string">'variables.cfg'</span>); 0024 0025 ep.setup(<span class="string">'init'</span>); 0026 pause(1); <span class="comment">% pause to have the initial EnergyPlus output in this section</span> 0027 0028 <span class="comment">%% Simulate</span> 0029 0030 endTime = 4*24*60*60; 0031 nRows = ceil(endTime / ep.timestep); 0032 logTable = table(<span class="string">'Size'</span>,[0, 1 + ep.nOut],<span class="keyword">...</span> 0033 <span class="string">'VariableTypes'</span>,repmat({<span class="string">'double'</span>},1,1 + ep.nOut),<span class="keyword">...</span> 0034 <span class="string">'VariableNames'</span>,[{<span class="string">'Time'</span>}; ep.outputSigName]); 0035 iLog = 1; 0036 t = 0; 0037 0038 <span class="keyword">while</span> t &lt; endTime 0039 0040 u = [20 25]; 0041 0042 <span class="comment">% Send inputs to/ get outputs from EnergyPlus</span> 0043 y = ep.step(u); 0044 0045 <span class="comment">% Obtain elapsed simulation time [s]</span> 0046 t = ep.time; 0047 0048 <span class="comment">% Log data</span> 0049 logTable(iLog, :) = num2cell([t y']); 0050 iLog = iLog + 1; 0051 <span class="keyword">end</span> 0052 ep.release; 0053 0054 <span class="comment">%% Plot results</span> 0055 plot(seconds(table2array(logTable(:,1))),<span class="keyword">...</span> 0056 table2array(logTable(:,2:end))); 0057 xtickformat(<span class="string">'hh:mm:ss'</span>); 0058 legend(logTable.Properties.VariableNames(2:end),<span class="string">'Interpreter'</span>,<span class="string">'none'</span>); 0059 0060 title(ep.idfFile); 0061 xlabel(<span class="string">'Time [hh:mm:ss]'</span>); 0062 ylabel(<span class="string">'Temperature [C]'</span>); 0063 0064 <span class="comment">%% Clean up</span> 0065 delete variables.cfg</pre></div> <hr><address>EnergyPlus Co-simulation Toolbox &copy; 2018</address> </body> </html> <|start_filename|>doc/functionIndex/@mlep/writeSocketConfig.html<|end_filename|> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>Description of writeSocketConfig</title> <meta name="keywords" content="writeSocketConfig"> <meta name="description" content="WRITESOCKETCONFIG - Create socket configuration file."> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="generator" content="m2html v1.5 &copy; 2003-2005 <NAME>"> <meta name="robots" content="index, follow"> <link type="text/css" rel="stylesheet" href="../m2html.css"> </head> <body> <a name="_top"></a> <div><a href="../functionIndex.html">Home</a> &gt; <a href="functionIndex.html">@mlep</a> &gt; writeSocketConfig.m</div> <!--<table width="100%"><tr><td align="left"><a href="../functionIndex.html"><img alt="<" border="0" src="../left.png">&nbsp;Master index</a></td> <td align="right"><a href="functionIndex.html">Index for @mlep&nbsp;<img alt=">" border="0" src="../right.png"></a></td></tr></table>--> <h1>writeSocketConfig </h1> <h2><a name="_name"></a>PURPOSE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="box"><strong>WRITESOCKETCONFIG - Create socket configuration file.</strong></div> <h2><a name="_synopsis"></a>SYNOPSIS <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="box"><strong>function writeSocketConfig(fullFilePath, hostname, port) </strong></div> <h2><a name="_description"></a>DESCRIPTION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="fragment"><pre class="comment"> WRITESOCKETCONFIG - Create socket configuration file. Create a BCVTB communication configuration file. Syntax: writeSocketConfig(fullFilePath, serverSocket, hostname) Inputs: fullFilePath - A path to write the configuration to. hostname - Hostname. port - Port on the host. See also: <a href="mlep.html" class="code" title="">MLEP</a>.MAKESOCKET (C) 2015, <NAME> (<EMAIL>) 2018, <NAME> (<EMAIL>) All rights reserved. Usage must follow the license given in the class definition.</pre></div> <!-- crossreference --> <h2><a name="_cross"></a>CROSS-REFERENCE INFORMATION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> This function calls: <ul style="list-style-image:url(../matlabicon.gif)"> </ul> This function is called by: <ul style="list-style-image:url(../matlabicon.gif)"> </ul> <!-- crossreference --> <h2><a name="_source"></a>SOURCE CODE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="fragment"><pre>0001 <a name="_sub0" href="#_subfunctions" class="code">function writeSocketConfig(fullFilePath, hostname, port)</a> 0002 <span class="comment">% WRITESOCKETCONFIG - Create socket configuration file.</span> 0003 <span class="comment">%Create a BCVTB communication configuration file.</span> 0004 <span class="comment">%</span> 0005 <span class="comment">% Syntax: writeSocketConfig(fullFilePath, serverSocket, hostname)</span> 0006 <span class="comment">%</span> 0007 <span class="comment">% Inputs:</span> 0008 <span class="comment">% fullFilePath - A path to write the configuration to.</span> 0009 <span class="comment">% hostname - Hostname.</span> 0010 <span class="comment">% port - Port on the host.</span> 0011 <span class="comment">%</span> 0012 <span class="comment">% See also: MLEP.MAKESOCKET</span> 0013 <span class="comment">%</span> 0014 <span class="comment">% (C) 2015, <NAME> (<EMAIL>)</span> 0015 <span class="comment">% 2018, <NAME> (<EMAIL>)</span> 0016 <span class="comment">% All rights reserved. Usage must follow the license given in the class</span> 0017 <span class="comment">% definition.</span> 0018 0019 fid = fopen(fullFilePath, <span class="string">'w'</span>); 0020 <span class="keyword">if</span> fid == -1 0021 <span class="comment">% error</span> 0022 error(<span class="string">'Error while creating socket config file: %s'</span>, ferror(fid)); 0023 <span class="keyword">end</span> 0024 0025 <span class="comment">% Write socket config to file</span> 0026 socket_config = [<span class="keyword">...</span> 0027 <span class="string">'&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;\n'</span> <span class="keyword">...</span> 0028 <span class="string">'&lt;BCVTB-client&gt;\n'</span> <span class="keyword">...</span> 0029 <span class="string">'&lt;ipc&gt;\n'</span> <span class="keyword">...</span> 0030 <span class="string">'&lt;socket port=&quot;%d&quot; hostname=&quot;%s&quot;/&gt;\n'</span> <span class="keyword">...</span> 0031 <span class="string">'&lt;/ipc&gt;\n'</span> <span class="keyword">...</span> 0032 <span class="string">'&lt;/BCVTB-client&gt;'</span>]; 0033 fprintf(fid, socket_config, port, hostname); 0034 0035 [femsg, ferr] = ferror(fid); 0036 <span class="keyword">if</span> ferr ~= 0 <span class="comment">% Error while writing config file</span> 0037 fclose(fid); 0038 error(<span class="string">'Error while writing socket config file: %s'</span>, femsg); 0039 <span class="keyword">end</span> 0040 0041 fclose(fid); 0042 <span class="keyword">end</span></pre></div> <hr><address>EnergyPlus Co-simulation Toolbox &copy; 2018</address> </body> </html> <|start_filename|>doc/functionIndex/library/busObjectBusCreator_clbk.html<|end_filename|> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>Description of busObjectBusCreator_clbk</title> <meta name="keywords" content="busObjectBusCreator_clbk"> <meta name="description" content="BUSOBJECTBUSCREATOR_CLBK - Callback functions for the 'BusObjectBusCreator' block."> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="generator" content="m2html v1.5 &copy; 2003-2005 <NAME>"> <meta name="robots" content="index, follow"> <link type="text/css" rel="stylesheet" href="../m2html.css"> </head> <body> <a name="_top"></a> <div><a href="../functionIndex.html">Home</a> &gt; <a href="functionIndex.html">library</a> &gt; busObjectBusCreator_clbk.m</div> <!--<table width="100%"><tr><td align="left"><a href="../functionIndex.html"><img alt="<" border="0" src="../left.png">&nbsp;Master index</a></td> <td align="right"><a href="functionIndex.html">Index for library&nbsp;<img alt=">" border="0" src="../right.png"></a></td></tr></table>--> <h1>busObjectBusCreator_clbk </h1> <h2><a name="_name"></a>PURPOSE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="box"><strong>BUSOBJECTBUSCREATOR_CLBK - Callback functions for the 'BusObjectBusCreator' block.</strong></div> <h2><a name="_synopsis"></a>SYNOPSIS <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="box"><strong>function busObjectBusCreator_clbk(block, type) </strong></div> <h2><a name="_description"></a>DESCRIPTION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="fragment"><pre class="comment">BUSOBJECTBUSCREATOR_CLBK - Callback functions for the 'BusObjectBusCreator' block.</pre></div> <!-- crossreference --> <h2><a name="_cross"></a>CROSS-REFERENCE INFORMATION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> This function calls: <ul style="list-style-image:url(../matlabicon.gif)"> </ul> This function is called by: <ul style="list-style-image:url(../matlabicon.gif)"> </ul> <!-- crossreference --> <h2><a name="_subfunctions"></a>SUBFUNCTIONS <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <ul style="list-style-image:url(../matlabicon.gif)"> <li><a href="#_sub1" class="code">function busObjectBusCreator_popup(block)</a></li><li><a href="#_sub2" class="code">function busObjectBusCreator_button(block)</a></li><li><a href="#_sub3" class="code">function busObjectBusCreator_CopyFcn(block)</a></li></ul> <h2><a name="_source"></a>SOURCE CODE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="fragment"><pre>0001 <a name="_sub0" href="#_subfunctions" class="code">function busObjectBusCreator_clbk(block, type)</a> 0002 <span class="comment">%BUSOBJECTBUSCREATOR_CLBK - Callback functions for the 'BusObjectBusCreator' block.</span> 0003 0004 <span class="comment">% Copyright (c) 2018, <NAME> (<EMAIL>)</span> 0005 <span class="comment">% All rights reserved.</span> 0006 <span class="comment">%</span> 0007 <span class="comment">% Code influenced by Landon Wagner, 2015 code of 'Bus Object Bus Creator'.</span> 0008 0009 <span class="comment">% String to be displayed when no Bus object is selected</span> 0010 default_str = <span class="string">'Select a Bus object...'</span>; 0011 0012 <span class="comment">% String to be displayed when no Bus object is found</span> 0013 empty_str = <span class="string">'No Bus objects found.'</span>; 0014 0015 <span class="keyword">switch</span> type 0016 <span class="keyword">case</span> <span class="string">'popup'</span> 0017 <a href="#_sub1" class="code" title="subfunction busObjectBusCreator_popup(block)">busObjectBusCreator_popup</a>(block); 0018 <span class="keyword">case</span> <span class="string">'button'</span> 0019 <a href="#_sub2" class="code" title="subfunction busObjectBusCreator_button(block)">busObjectBusCreator_button</a>(block); 0020 <span class="keyword">case</span> <span class="string">'CopyFcn'</span> 0021 <a href="#_sub3" class="code" title="subfunction busObjectBusCreator_CopyFcn(block)">busObjectBusCreator_CopyFcn</a>(block); 0022 <span class="keyword">otherwise</span> 0023 error(<span class="string">'Unknown callback: ''%s.'''</span>, type); 0024 <span class="keyword">end</span> 0025 0026 0027 <a name="_sub1" href="#_subfunctions" class="code">function busObjectBusCreator_popup(block)</a> 0028 <span class="comment">% Get the current block handle and mask handle.</span> 0029 bch = get_param(block,<span class="string">'handle'</span>); 0030 maskObj = Simulink.Mask.get(block); 0031 popupParam = maskObj.getParameter(<span class="string">'busType'</span>); 0032 0033 <span class="comment">% --- Find Bus objects ---</span> 0034 <span class="comment">% Get base workspace variables</span> 0035 bwVars = evalin(<span class="string">'base'</span>,<span class="string">'whos'</span>); 0036 allBusNames = {}; 0037 <span class="keyword">if</span> ~isempty(bwVars) 0038 flag = strcmp({bwVars.class},<span class="string">'Simulink.Bus'</span>); 0039 allBusNames = {bwVars(flag).name}; 0040 <span class="keyword">end</span> 0041 0042 <span class="comment">% Get Data dictionary - Design Data Bus objects</span> 0043 ddName = get_param(bdroot(block),<span class="string">'DataDictionary'</span>); 0044 <span class="keyword">if</span> ~isempty(ddName) 0045 dd = Simulink.data.dictionary.open(ddName); 0046 ddSec = getSection(dd,<span class="string">'Design Data'</span>); 0047 ddVars = find(ddSec,<span class="string">'-value'</span>,<span class="string">'-class'</span>,<span class="string">'Simulink.Bus'</span>); <span class="comment">%#ok&lt;GTARG&gt;</span> 0048 allBusNames = [allBusNames {ddVars.Name}]; 0049 <span class="keyword">end</span> 0050 0051 <span class="comment">% --- Create popup ---</span> 0052 <span class="comment">% Create popup entries</span> 0053 busOpts = strcat({<span class="string">'Bus: '</span>}, allBusNames); 0054 0055 <span class="keyword">if</span> ~isempty(busOpts) 0056 <span class="comment">% Add default option</span> 0057 extOpts = [{default_str}, busOpts]; 0058 0059 <span class="comment">% Current number of options</span> 0060 old_opts = popupParam.TypeOptions; 0061 0062 <span class="comment">% Fill out the BusType options</span> 0063 <span class="keyword">if</span> ~strcmp([old_opts{:}],[extOpts{:}]) 0064 popupParam.TypeOptions = extOpts; 0065 <span class="keyword">end</span> 0066 <span class="keyword">end</span> 0067 0068 <span class="comment">% If the currently selected bus data type ('OutDataTypeStr') is not</span> 0069 <span class="comment">% 'Inherit: auto' then get the current 'OutDataTypeStr' and 'maskVal.'</span> 0070 currentOutDataTypeStr = get_param(bch, <span class="string">'OutDataTypeStr'</span>); 0071 <span class="keyword">if</span> ~strcmp(currentOutDataTypeStr, <span class="string">'Inherit: auto'</span>) 0072 0073 <span class="keyword">if</span> ismember(currentOutDataTypeStr, busOpts) 0074 <span class="comment">% Upon re-opening the mask if the default 'TypeOptions' list member</span> 0075 <span class="comment">% (The first one.) contained in 'maskVal' does not match the</span> 0076 <span class="comment">% currently selected bus data type ('OutDataTypeStr') then set the</span> 0077 <span class="comment">% 'TypeOptions' list member to the selected bus data type. (Cuts down</span> 0078 <span class="comment">% on confusion to have the displayed list member match the selected</span> 0079 <span class="comment">% bus data type rather than the first entry.)</span> 0080 popupParam.Value = currentOutDataTypeStr; 0081 <span class="keyword">else</span> 0082 <span class="keyword">if</span> isempty(busOpts) 0083 popupParam.TypeOptions = {empty_str}; 0084 popupParam.Value = empty_str; 0085 <span class="keyword">else</span> 0086 popupParam.Value = default_str; 0087 <span class="keyword">end</span> 0088 warning(<span class="string">'The Output Data Type ''%s'' is no longer available in a data dictionary nor base workspace. Setting the Output Data Type to ''Inherit: auto''.'</span>,<span class="keyword">...</span> 0089 currentOutDataTypeStr); 0090 set_param(bch, <span class="string">'OutDataTypeStr'</span>,<span class="string">'Inherit: auto'</span>); 0091 <span class="keyword">end</span> 0092 <span class="keyword">end</span> 0093 <span class="keyword">end</span> 0094 0095 <a name="_sub2" href="#_subfunctions" class="code">function busObjectBusCreator_button(block)</a> 0096 <span class="comment">% Using variable names terminated with &quot;_BOBC&quot; to lessen the chances of</span> 0097 <span class="comment">% collisions with existing workspace variables.</span> 0098 0099 <span class="comment">% Get the current block, current block handle and mask handle.</span> 0100 bch = get_param(block,<span class="string">'handle'</span>); 0101 0102 <span class="comment">% Get the desired bus type...</span> 0103 selectedBusTypeStr = get_param(bch, <span class="string">'busType'</span>); 0104 0105 <span class="keyword">if</span> ismember(selectedBusTypeStr,{default_str, empty_str}) 0106 helpdlg(selectedBusTypeStr); 0107 <span class="keyword">return</span> 0108 <span class="keyword">elseif</span> isempty(regexp(selectedBusTypeStr,<span class="string">'Bus: '</span>,<span class="string">'ONCE'</span>)) 0109 warndlg(<span class="string">'Invalid data entry &quot;%s&quot;'</span>,selectedBusTypeStr); 0110 <span class="keyword">return</span> 0111 <span class="keyword">else</span> 0112 set_param(bch, <span class="string">'OutDataTypeStr'</span>,<span class="string">'Inherit: auto'</span>); 0113 <span class="keyword">end</span> 0114 0115 <span class="comment">% ... and set the 'OutDataTypeStr' to it.</span> 0116 set_param(bch, <span class="string">'OutDataTypeStr'</span>, selectedBusTypeStr); 0117 0118 0119 <span class="comment">% Get the block path for 'add_line' function.</span> 0120 blockPath = get_param(bch, <span class="string">'Parent'</span>); 0121 0122 <span class="comment">% Get the newly selected bus type ('OutDataTypeStr')...</span> 0123 busType = get_param(block, <span class="string">'OutDataTypeStr'</span>); 0124 0125 <span class="comment">% ... and parse off &quot;Bus: &quot; so the string of the desired bus contained in</span> 0126 <span class="comment">% 'OutDataTypeStr' matches the raw workspace bus names.</span> 0127 busType = busType(6:end); 0128 0129 <span class="comment">% Load the selected Bus object</span> 0130 <span class="keyword">if</span> Simulink.data.existsInGlobal(bdroot(block),busType) 0131 <span class="comment">% From Data Dictionary first</span> 0132 busObj = Simulink.data.evalinGlobal(bdroot(block),busType); 0133 <span class="keyword">elseif</span> evalin(<span class="string">'base'</span>,[<span class="string">'exist('''</span> busType <span class="string">''',''var'')'</span>]) 0134 busObj = evalin(<span class="string">'base'</span>,busType); 0135 <span class="keyword">else</span> 0136 error(<span class="string">'Simulink.Bus object ''%s'' not found in a data dictionary nor the base workspace.'</span>,<span class="keyword">...</span> 0137 busType); 0138 <span class="keyword">end</span> 0139 0140 <span class="comment">% From the parameters grab the number of lines to add.</span> 0141 nElems = busObj.getNumLeafBusElements; 0142 assert(nElems &gt; 0, <span class="string">'The Simulink.Bus object ''%s'' contains zero elements.'</span>, busType); 0143 0144 <span class="comment">% First delete any existing lines on the port.</span> 0145 <span class="comment">% Get the line handles.</span> 0146 lineHandle = get_param(bch, <span class="string">'LineHandles'</span>); 0147 0148 <span class="comment">% If any lines exist (Non- -1 line handles.), delete them and start over.</span> 0149 <span class="keyword">if</span> max(lineHandle.Inport &gt; 0) 0150 0151 <span class="keyword">for</span> i = 1:length(lineHandle.Inport) 0152 <span class="keyword">if</span> lineHandle.Inport(i) &gt; 0 0153 delete_line(lineHandle.Inport(i)) 0154 <span class="keyword">end</span> 0155 <span class="keyword">end</span> 0156 <span class="keyword">end</span> 0157 0158 <span class="comment">% Set the number of inputs of the masked bus creator to the number of lines</span> 0159 <span class="comment">% to add.</span> 0160 set_param(bch, <span class="string">'Inputs'</span>, num2str(nElems)); 0161 0162 <span class="comment">% Set heigh</span> 0163 sz = get_param(bch, <span class="string">'Position'</span>); 0164 y0 = sz(2) + (sz(4)-sz(2))/2; <span class="comment">% vertical center</span> 0165 h = max(95, nElems*10); <span class="comment">% height</span> 0166 sz = [sz(1), <span class="keyword">...</span> 0167 y0 - h/2, <span class="keyword">...</span> 0168 sz(3), <span class="keyword">...</span> 0169 y0 + h/2]; 0170 set_param(bch, <span class="string">'Position'</span>, sz); 0171 0172 <span class="comment">% Get Input port handles so we can grab the positions of them.</span> 0173 portHandle = get_param(bch, <span class="string">'PortHandles'</span>); 0174 0175 <span class="comment">% Get longest signal name to adjust the line lenght right</span> 0176 signalNames = {busObj.Elements.Name}; 0177 lineLength = ceil(50/10*max(strlength(signalNames)))+10; 0178 <span class="keyword">for</span> i = 1:nElems 0179 <span class="comment">% Get the position of input port number 'i'.</span> 0180 portPos = get_param(portHandle.Inport(i), <span class="string">'Position'</span>); 0181 <span class="comment">% Add a line long as the longest name</span> 0182 <span class="comment">%(This must be done because it's the lines that get named,</span> 0183 <span class="comment">% not the port positions.)</span> 0184 portLine = add_line(blockPath, <span class="keyword">...</span> 0185 [portPos - [lineLength 0]; portPos]); 0186 0187 <span class="comment">% Rename the new line to the bus 'i-st/nd/rd/th' element name.</span> 0188 set_param(portLine, <span class="string">'Name'</span>, busObj.Elements(i).Name) 0189 <span class="keyword">end</span> 0190 0191 <span class="keyword">end</span> 0192 0193 <a name="_sub3" href="#_subfunctions" class="code">function busObjectBusCreator_CopyFcn(block)</a> 0194 <span class="comment">% Disable library link</span> 0195 set_param(block,<span class="string">'LinkStatus'</span>,<span class="string">'none'</span>); 0196 <span class="keyword">end</span> 0197 <span class="keyword">end</span></pre></div> <hr><address>EnergyPlus Co-simulation Toolbox &copy; 2018</address> </body> </html> <|start_filename|>doc/functionIndex/@mlep/encodeRealData.html<|end_filename|> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>Description of encodeRealData</title> <meta name="keywords" content="encodeRealData"> <meta name="description" content="ENCODEREALDATA Encode real value data to packet."> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="generator" content="m2html v1.5 &copy; 2003-2005 <NAME>"> <meta name="robots" content="index, follow"> <link type="text/css" rel="stylesheet" href="../m2html.css"> </head> <body> <a name="_top"></a> <div><a href="../functionIndex.html">Home</a> &gt; <a href="functionIndex.html">@mlep</a> &gt; encodeRealData.m</div> <!--<table width="100%"><tr><td align="left"><a href="../functionIndex.html"><img alt="<" border="0" src="../left.png">&nbsp;Master index</a></td> <td align="right"><a href="functionIndex.html">Index for @mlep&nbsp;<img alt=">" border="0" src="../right.png"></a></td></tr></table>--> <h1>encodeRealData </h1> <h2><a name="_name"></a>PURPOSE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="box"><strong>ENCODEREALDATA Encode real value data to packet.</strong></div> <h2><a name="_synopsis"></a>SYNOPSIS <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="box"><strong>function packet = encodeRealData(vernumber, flag, timevalue, realvalues) </strong></div> <h2><a name="_description"></a>DESCRIPTION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="fragment"><pre class="comment">ENCODEREALDATA Encode real value data to packet. Encode real value data to a packet (a string) that can be sent to the external program. This function is a special version of mlep.encodeData in which integer and boolean data does not exist. Syntax: packet = encodeRealData(vernumber, flag, timevalue, realvalues) Inputs: vernumber - Version of the protocol to be used. Currently, version 1 and 2 are supported. flag - An integer specifying the (status) flag. Refer to the BCVTB protocol for allowed flag values. timevalue - A real value which is the current simulation time in seconds. realvalues - A vector of real value data to be sent. Can be empty. Outputs: packet - A string that contains the encoded data. See also: <a href="mlep.html" class="code" title="">MLEP</a>.<a href="decodePacket.html" class="code" title="function [flag, timevalue, realvalues, intvalues, boolvalues] = decodePacket(packet)">DECODEPACKET</a>, <a href="mlep.html" class="code" title="">MLEP</a>.<a href="encodeData.html" class="code" title="function packet = encodeData(vernumber, flag, timevalue, realvalues, intvalues, boolvalues)">ENCODEDATA</a>, <a href="mlep.html" class="code" title="">MLEP</a>.<a href="encodeStatus.html" class="code" title="function packet = encodeStatus(vernumber, flag)">ENCODESTATUS</a> (C) 2010 by <NAME> (<EMAIL>)</pre></div> <!-- crossreference --> <h2><a name="_cross"></a>CROSS-REFERENCE INFORMATION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> This function calls: <ul style="list-style-image:url(../matlabicon.gif)"> </ul> This function is called by: <ul style="list-style-image:url(../matlabicon.gif)"> </ul> <!-- crossreference --> <h2><a name="_source"></a>SOURCE CODE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="fragment"><pre>0001 <a name="_sub0" href="#_subfunctions" class="code">function packet = encodeRealData(vernumber, flag, timevalue, realvalues)</a> 0002 <span class="comment">%ENCODEREALDATA Encode real value data to packet.</span> 0003 <span class="comment">%Encode real value data to a packet (a string) that can be sent to the</span> 0004 <span class="comment">%external program. This function is a special version of</span> 0005 <span class="comment">%mlep.encodeData in which integer and boolean data does not exist.</span> 0006 <span class="comment">%</span> 0007 <span class="comment">% Syntax: packet = encodeRealData(vernumber, flag, timevalue, realvalues)</span> 0008 <span class="comment">%</span> 0009 <span class="comment">% Inputs:</span> 0010 <span class="comment">% vernumber - Version of the protocol to be used. Currently, version 1</span> 0011 <span class="comment">% and 2 are supported.</span> 0012 <span class="comment">% flag - An integer specifying the (status) flag. Refer to the BCVTB</span> 0013 <span class="comment">% protocol for allowed flag values.</span> 0014 <span class="comment">% timevalue - A real value which is the current simulation time in</span> 0015 <span class="comment">% seconds.</span> 0016 <span class="comment">% realvalues - A vector of real value data to be sent. Can be empty.</span> 0017 <span class="comment">%</span> 0018 <span class="comment">% Outputs:</span> 0019 <span class="comment">% packet - A string that contains the encoded data.</span> 0020 <span class="comment">%</span> 0021 <span class="comment">% See also:</span> 0022 <span class="comment">% MLEP.DECODEPACKET, MLEP.ENCODEDATA, MLEP.ENCODESTATUS</span> 0023 <span class="comment">%</span> 0024 <span class="comment">% (C) 2010 by <NAME> (<EMAIL>)</span> 0025 0026 ni = nargin; 0027 <span class="keyword">if</span> ni &lt; 4 0028 error(<span class="string">'Not enough arguments: all input arguments are required.'</span>); 0029 <span class="keyword">end</span> 0030 0031 <span class="keyword">if</span> vernumber &lt;= 2 0032 <span class="keyword">if</span> flag == 0 0033 packet = [sprintf(<span class="string">'%d 0 %d 0 0 %20.15e '</span>, <span class="keyword">...</span> 0034 vernumber,<span class="keyword">...</span> 0035 length(realvalues),<span class="keyword">...</span> 0036 timevalue), <span class="keyword">...</span> 0037 sprintf(<span class="string">'%20.15e '</span>, realvalues)]; 0038 <span class="keyword">else</span> 0039 <span class="comment">% Error</span> 0040 packet = sprintf(<span class="string">'%d %d'</span>, vernumber, flag); 0041 <span class="keyword">end</span> 0042 <span class="keyword">else</span> 0043 packet = <span class="string">''</span>; 0044 <span class="keyword">end</span> 0045 0046 <span class="keyword">end</span> 0047 0048 <span class="comment">% Protocol Version 1 &amp; 2:</span> 0049 <span class="comment">% Packet has the form:</span> 0050 <span class="comment">% v f dr di db t r1 r2 ... i1 i2 ... b1 b2 ...</span> 0051 <span class="comment">% where</span> 0052 <span class="comment">% v - version number (1,2)</span> 0053 <span class="comment">% f - flag (0: communicate, 1: finish, -10: initialization error,</span> 0054 <span class="comment">% -20: time integration error, -1: unknown error)</span> 0055 <span class="comment">% dr - number of real values</span> 0056 <span class="comment">% di - number of integer values</span> 0057 <span class="comment">% db - number of boolean values</span> 0058 <span class="comment">% t - current simulation time in seconds (format %20.15e)</span> 0059 <span class="comment">% r1 r2 ... are real values (format %20.15e)</span> 0060 <span class="comment">% i1 i2 ... are integer values (format %d)</span> 0061 <span class="comment">% b1 b2 ... are boolean values (format %d)</span> 0062 <span class="comment">%</span> 0063 <span class="comment">% Note that if f is non-zero, other values after it will not be processed.</span></pre></div> <hr><address>EnergyPlus Co-simulation Toolbox &copy; 2018</address> </body> </html> <|start_filename|>doc/functionIndex/@mlep/writeVariableConfig.html<|end_filename|> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>Description of writeVariableConfig</title> <meta name="keywords" content="writeVariableConfig"> <meta name="description" content="WRITEVARIABLECONFIG - Create XML definition of the variable exchange for the BCVTB protocol."> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="generator" content="m2html v1.5 &copy; 2003-2005 <NAME>"> <meta name="robots" content="index, follow"> <link type="text/css" rel="stylesheet" href="../m2html.css"> </head> <body> <a name="_top"></a> <div><a href="../functionIndex.html">Home</a> &gt; <a href="functionIndex.html">@mlep</a> &gt; writeVariableConfig.m</div> <!--<table width="100%"><tr><td align="left"><a href="../functionIndex.html"><img alt="<" border="0" src="../left.png">&nbsp;Master index</a></td> <td align="right"><a href="functionIndex.html">Index for @mlep&nbsp;<img alt=">" border="0" src="../right.png"></a></td></tr></table>--> <h1>writeVariableConfig </h1> <h2><a name="_name"></a>PURPOSE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="box"><strong>WRITEVARIABLECONFIG - Create XML definition of the variable exchange for the BCVTB protocol.</strong></div> <h2><a name="_synopsis"></a>SYNOPSIS <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="box"><strong>function writeVariableConfig(fullFilePath, inputTable, outputTable) </strong></div> <h2><a name="_description"></a>DESCRIPTION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="fragment"><pre class="comment"> WRITEVARIABLECONFIG - Create XML definition of the variable exchange for the BCVTB protocol. Create a XML file (&quot;variables.cfg&quot;) with input/output configuration to be used by the BCVTB protocol on both sides of the communication socket. Syntax: writeVariableConfig(fullFilePath, inputTable, outputTable) Inputs: fullFilePath - A path to write the configuration to. inputTable - Table containing specification of the inputs to EnergyPlus. outputTable - Table containing specification of the outputs from EnergyPlus. See also: <a href="mlep.html" class="code" title="">MLEP</a>.PARSEVARIABLESCONFIGFILE, <a href="mlep.html" class="code" title="">MLEP</a>.MAKEVARIABLESCONFIGFILE (C) 2015, <NAME> (<EMAIL>) 2018, <NAME> (<EMAIL>) All rights reserved. Usage must follow the license given in the class definition.</pre></div> <!-- crossreference --> <h2><a name="_cross"></a>CROSS-REFERENCE INFORMATION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> This function calls: <ul style="list-style-image:url(../matlabicon.gif)"> </ul> This function is called by: <ul style="list-style-image:url(../matlabicon.gif)"> </ul> <!-- crossreference --> <h2><a name="_source"></a>SOURCE CODE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2> <div class="fragment"><pre>0001 <a name="_sub0" href="#_subfunctions" class="code">function writeVariableConfig(fullFilePath, inputTable, outputTable)</a> 0002 <span class="comment">% WRITEVARIABLECONFIG - Create XML definition of the variable exchange for the BCVTB protocol.</span> 0003 <span class="comment">%Create a XML file (&quot;variables.cfg&quot;) with input/output configuration to be</span> 0004 <span class="comment">%used by the BCVTB protocol on both sides of the communication socket.</span> 0005 <span class="comment">%</span> 0006 <span class="comment">% Syntax: writeVariableConfig(fullFilePath, inputTable, outputTable)</span> 0007 <span class="comment">%</span> 0008 <span class="comment">% Inputs:</span> 0009 <span class="comment">% fullFilePath - A path to write the configuration to.</span> 0010 <span class="comment">% inputTable - Table containing specification of the inputs to</span> 0011 <span class="comment">% EnergyPlus.</span> 0012 <span class="comment">% outputTable - Table containing specification of the outputs from</span> 0013 <span class="comment">% EnergyPlus.</span> 0014 <span class="comment">%</span> 0015 <span class="comment">% See also: MLEP.PARSEVARIABLESCONFIGFILE, MLEP.MAKEVARIABLESCONFIGFILE</span> 0016 <span class="comment">%</span> 0017 <span class="comment">% (C) 2015, <NAME> (<EMAIL>)</span> 0018 <span class="comment">% 2018, <NAME> (<EMAIL>)</span> 0019 <span class="comment">% All rights reserved. Usage must follow the license given in the class</span> 0020 <span class="comment">% definition.</span> 0021 0022 <span class="comment">% XML header</span> 0023 docType = com.mathworks.xml.XMLUtils.createDocumentType(<span class="string">'SYSTEM'</span>, [],<span class="string">'variables.dtd'</span>); 0024 docNode = com.mathworks.xml.XMLUtils.createDocument([], <span class="string">'BCVTB-variables'</span>, docType); 0025 setEncoding(docNode, <span class="string">'ISO-8859-1'</span>); 0026 setVersion(docNode, <span class="string">'1.0'</span>) 0027 0028 <span class="comment">% Disclaimer</span> 0029 disclaimer = docNode.createComment([newline, <span class="keyword">...</span> 0030 <span class="string">'|===========================================================|'</span> newline,<span class="keyword">...</span> 0031 <span class="string">'| THIS FILE IS AUTOMATICALLY GENERATED |'</span> newline,<span class="keyword">...</span> 0032 <span class="string">'| DO NOT EDIT THIS FILE AS ANY CHANGES WILL BE OVERWRITTEN! |'</span> newline,<span class="keyword">...</span> 0033 <span class="string">'|===========================================================|'</span> newline,<span class="keyword">...</span> 0034 ]); 0035 0036 <span class="comment">% INPUT to E+</span> 0037 docRootNode = docNode.getDocumentElement; 0038 insertBefore(docNode, disclaimer, docRootNode); 0039 <span class="comment">%docRootNode.setAttribute('SYSTEM','variables.dtd');</span> 0040 appendChild(docRootNode, docNode.createComment(<span class="string">'INPUT to E+'</span>)); 0041 0042 table = inputTable; 0043 names = table.Name; 0044 types = table.Type; 0045 <span class="keyword">for</span> i=1:height(inputTable) 0046 0047 <span class="comment">%Example: &lt;variable source=&quot;Ptolemy&quot;&gt;</span> 0048 thisElement = createElement(docNode, <span class="string">'variable'</span>); 0049 setAttribute(thisElement, <span class="string">'source'</span>,<span class="string">'Ptolemy'</span>); 0050 0051 <span class="comment">%Example: &lt;EnergyPlus schedule=&quot;TSetHea&quot;/&gt;</span> 0052 newElement = createElement(docNode, <span class="string">'EnergyPlus'</span>); 0053 setAttribute(newElement, names(i),<span class="keyword">...</span><span class="comment"> % schedule, actuator, variable</span> 0054 types(i)); <span class="comment">% particular name</span> 0055 0056 appendChild(thisElement, newElement); 0057 appendChild(docRootNode, thisElement); 0058 <span class="keyword">end</span> 0059 0060 <span class="comment">% OUTPUT from E+</span> 0061 docRootNode.appendChild(docNode.createComment(<span class="string">'OUTPUT from E+'</span>)); 0062 table = outputTable; 0063 names = table.Name; 0064 types = table.Type; 0065 <span class="keyword">for</span> i=1:height(outputTable) 0066 0067 <span class="comment">%Example: &lt;variable source=&quot;EnergyPlus&quot;&gt;</span> 0068 thisElement = createElement(docNode, <span class="string">'variable'</span>); 0069 setAttribute(thisElement, <span class="string">'source'</span>,<span class="string">'EnergyPlus'</span>); 0070 0071 <span class="comment">%Example: &lt;EnergyPlus name=&quot;ZSF1&quot; type=&quot;Zone Air Temperature&quot;/&gt;</span> 0072 newElement = createElement(docNode, <span class="string">'EnergyPlus'</span>); 0073 setAttribute(newElement, <span class="string">'name'</span>,names(i)); <span class="comment">% key value ('zone name')</span> 0074 setAttribute(newElement, <span class="string">'type'</span>,types(i)); <span class="comment">% variable name ('signal')</span> 0075 0076 appendChild(thisElement, newElement); 0077 appendChild(docRootNode, thisElement); 0078 <span class="keyword">end</span> 0079 0080 xmlwrite_r18a(fullFilePath,docNode); 0081 <span class="keyword">end</span></pre></div> <hr><address>EnergyPlus Co-simulation Toolbox &copy; 2018</address> </body> </html> <|start_filename|>doc/functionIndex/library/functionIndex.html<|end_filename|> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>Index for Directory library</title> <meta name="keywords" content="library"> <meta name="description" content="Index for Directory library"> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="generator" content="m2html v1.5 &copy; 2003-2005 <NAME>"> <meta name="robots" content="index, follow"> <link type="text/css" rel="stylesheet" href="../m2html.css"> </head> <body> <a name="_top"></a> <table width="100%"><tr><td align="left"><a href="../functionIndex.html"><img alt="<" border="0" src="../left.png">&nbsp;Master index</a></td> <td align="right"><a href="functionIndex.html">Index for library&nbsp;<img alt=">" border="0" src="../right.png"></a></td></tr></table> <h1>Index for library</h1> <h2>Matlab files in this directory:</h2> <table> <tr><td><img src="../matlabicon.gif" alt="" border="">&nbsp;<a href="busObjectBusCreator_clbk.html">busObjectBusCreator_clbk</a></td><td>BUSOBJECTBUSCREATOR_CLBK - Callback functions for the 'BusObjectBusCreator' block. </td></tr><tr><td><img src="../matlabicon.gif" alt="" border="">&nbsp;<a href="mlepEnergyPlusSimulation_clbk.html">mlepEnergyPlusSimulation_clbk</a></td><td>MLEPENERGYPLUSSIMULATION_CLBK - Callback functions for the 'EnergyPlus Simulation' block. </td></tr><tr><td><img src="../matlabicon.gif" alt="" border="">&nbsp;<a href="mlepSO.html">mlepSO</a></td><td>MLEPSO EnergyPlus co-simulation system object. </td></tr><tr><td><img src="../matlabicon.gif" alt="" border="">&nbsp;<a href="slblocks.html">slblocks</a></td><td>SLBLOCKS - Simulink Library browser definition file </td></tr><tr><td><img src="../matlabicon.gif" alt="" border="">&nbsp;<a href="vector2Bus_clbk.html">vector2Bus_clbk</a></td><td>VECTOR2BUS_CLBK - Callback functions. </td></tr></table> <hr><address>EnergyPlus Co-simulation Toolbox &copy; 2018</address> </body> </html> <|start_filename|>doc/functionIndex/examples/legacy_example/mlepMatlab_example.html<|end_filename|> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>Description of mlepMatlab_example</title> <meta name="keywords" content="mlepMatlab_example"> <meta name="description" content="% Simple Matlab &lt;-&gt; EnergyPlus co-simulation example"> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="generator" content="m2html v1.5 &copy; 2003-2005 <NAME>"> <meta name="robots" content="index, follow"> <link type="text/css" rel="stylesheet" href="../../m2html.css"> </head> <body> <a name="_top"></a> <div><a href="../../functionIndex.html">Home</a> &gt; <a href="#">examples</a> &gt; <a href="functionIndex.html">legacy_example</a> &gt; mlepMatlab_example.m</div> <!--<table width="100%"><tr><td align="left"><a href="../../functionIndex.html"><img alt="<" border="0" src="../../left.png">&nbsp;Master index</a></td> <td align="right"><a href="functionIndex.html">Index for examples\legacy_example&nbsp;<img alt=">" border="0" src="../../right.png"></a></td></tr></table>--> <h1>mlepMatlab_example </h1> <h2><a name="_name"></a>PURPOSE <a href="#_top"><img alt="^" border="0" src="../../up.png"></a></h2> <div class="box"><strong>% Simple Matlab &lt;-&gt; EnergyPlus co-simulation example</strong></div> <h2><a name="_synopsis"></a>SYNOPSIS <a href="#_top"><img alt="^" border="0" src="../../up.png"></a></h2> <div class="box"><strong>This is a script file. </strong></div> <h2><a name="_description"></a>DESCRIPTION <a href="#_top"><img alt="^" border="0" src="../../up.png"></a></h2> <div class="fragment"><pre class="comment">% Simple Matlab &lt;-&gt; EnergyPlus co-simulation example Demonstrates the functionality of the mlep (MatLab-EnergyPlus) tool in a small office building simulation scenario. Note that a start of the simulation period as well as a timestep and an input/output configuration is defined by the the EnergyPlus simulation configuration file (.IDF). Climatic conditions are obtained from a EnergyPlus Weather data file (.EPW). See also: <a href="mlepMatlab_so_example.html" class="code" title="">mlepMatlab_so_example</a>.m, mlepSimulink_example.slx</pre></div> <!-- crossreference --> <h2><a name="_cross"></a>CROSS-REFERENCE INFORMATION <a href="#_top"><img alt="^" border="0" src="../../up.png"></a></h2> This function calls: <ul style="list-style-image:url(../../matlabicon.gif)"> </ul> This function is called by: <ul style="list-style-image:url(../../matlabicon.gif)"> </ul> <!-- crossreference --> <h2><a name="_source"></a>SOURCE CODE <a href="#_top"><img alt="^" border="0" src="../../up.png"></a></h2> <div class="fragment"><pre>0001 <span class="comment">%% Simple Matlab &lt;-&gt; EnergyPlus co-simulation example</span> 0002 <span class="comment">% Demonstrates the functionality of the mlep (MatLab-EnergyPlus) tool in</span> 0003 <span class="comment">% a small office building simulation scenario.</span> 0004 <span class="comment">%</span> 0005 <span class="comment">% Note that a start of the simulation period as well as a timestep and</span> 0006 <span class="comment">% an input/output configuration is defined by the the EnergyPlus simulation</span> 0007 <span class="comment">% configuration file (.IDF). Climatic conditions are obtained from a</span> 0008 <span class="comment">% EnergyPlus Weather data file (.EPW).</span> 0009 <span class="comment">%</span> 0010 <span class="comment">% See also: mlepMatlab_so_example.m, mlepSimulink_example.slx</span> 0011 0012 <span class="comment">%% Create mlep instance and configure it</span> 0013 0014 <span class="comment">% Instantiate co-simulation tool</span> 0015 ep = mlep; 0016 0017 <span class="comment">% Building simulation configuration file</span> 0018 ep.idfFile = <span class="string">'SmOffPSZ'</span>; 0019 0020 <span class="comment">% Weather file</span> 0021 ep.epwFile = <span class="string">'USA_IL_Chicago-OHare.Intl.AP.725300_TMY3'</span>; 0022 0023 0024 <span class="comment">%% Input/output configuration</span> 0025 0026 <span class="comment">% Initialize the co-simulation. This will load the IDF file.</span> 0027 ep.initialize; 0028 0029 <span class="comment">% Display inputs/outputs defined in the IDF file.</span> 0030 disp(<span class="string">'Input/output configuration.'</span>); 0031 inputTable = ep.inputTable <span class="comment">%#ok&lt;*NASGU,*NOPTS&gt;</span> 0032 outputTable = ep.outputTable 0033 0034 <span class="comment">%% Simulate</span> 0035 0036 <span class="comment">% Specify simulation duration</span> 0037 endTime = 4*24*60*60; <span class="comment">%[s]</span> 0038 0039 <span class="comment">% Prepare data logging</span> 0040 nRows = ceil(endTime / ep.timestep); <span class="comment">%Query timestep after mlep initialization</span> 0041 logTable = table(<span class="string">'Size'</span>,[0, 1 + ep.nOut],<span class="keyword">...</span> 0042 <span class="string">'VariableTypes'</span>,repmat({<span class="string">'double'</span>},1,1 + ep.nOut),<span class="keyword">...</span> 0043 <span class="string">'VariableNames'</span>,[{<span class="string">'Time'</span>}; ep.outputSigName]); 0044 iLog = 1; 0045 0046 <span class="comment">% Start the co-simulation process and communication.</span> 0047 ep.start 0048 0049 <span class="comment">% The simulation loop</span> 0050 t = 0; 0051 <span class="keyword">while</span> t &lt; endTime 0052 <span class="comment">% Prepare inputs (possibly from last outputs)</span> 0053 u = [20 25]; 0054 0055 <span class="comment">% Get outputs from EnergyPlus</span> 0056 [y, t] = ep.read; 0057 0058 <span class="comment">% Send inputs to EnergyPlus</span> 0059 ep.write(u,t); 0060 0061 <span class="comment">% Log</span> 0062 logTable(iLog, :) = num2cell([t y(:)']); 0063 iLog = iLog + 1; 0064 <span class="keyword">end</span> 0065 <span class="comment">% Stop co-simulation process</span> 0066 ep.stop; 0067 0068 <span class="comment">%% Plot results</span> 0069 0070 plot(seconds(table2array(logTable(:,1))),<span class="keyword">...</span> 0071 table2array(logTable(:,2:end))); 0072 xtickformat(<span class="string">'hh:mm:ss'</span>); 0073 legend(logTable.Properties.VariableNames(2:end),<span class="string">'Interpreter'</span>,<span class="string">'none'</span>); 0074 0075 title(ep.idfFile); 0076 xlabel(<span class="string">'Time [hh:mm:ss]'</span>); 0077 ylabel(<span class="string">'Temperature [C]'</span>);</pre></div> <hr><address>EnergyPlus Co-simulation Toolbox &copy; 2018</address> </body> </html>
UCEEB/EnergyPlus-co-simulation-toolbox
<|start_filename|>src/k81x-fkeys.cpp<|end_filename|> // Copyright 2017 <NAME> <<EMAIL>> #include "./k81x.h" #include <unistd.h> #include <cstring> #include <iostream> using std::cerr; using std::cout; using std::endl; void usage() { cout << "Usage: sudo k81x-fkeys [-d device_path] [-u udev_path] [-v] on|off" << endl; cout << "Controls the functions of Logitech K810/K811 Keyboard F-keys" << endl << endl; cout << "As seen above, this tool needs root privileges to operate. Options:" << endl; cout << "\t-d device_path\tOptional Device file path of the Logitech keyboard," << endl << "\t\t\tusually /dev/hidraw0. Autodetecion is peformed if" << endl << "\t\t\tthis and -u parameters are omitted." << endl; cout << "\t-u udev_path\tUdev path of the Logitech keyboard, usually" << endl << "\t\t\tstarting with /sys/devices. Autodetecion is peformed" << endl << "\t\t\tif this and -d parameters are omitted." << endl; cout << "\t-v\t\tVerbose mode." << endl; cout << "\ton|off\t\t\"on\" causes the F-keys to act like standard" << endl << "\t\t\tF1-F12 keys, \"off\" enables the enhanced functions." << endl; } int main(int argc, char **argv) { bool verbose = false, switch_on, silent = false; int error_return = 1; const char *device_path = NULL, *device_udevpath = NULL; // Fetch the command line arguments. int opt; while ((opt = getopt(argc, argv, "d:u:vs")) != -1) { switch (opt) { case 'd': device_path = optarg; break; case 'u': device_udevpath = optarg; break; case 'v': verbose = true; break; case 's': silent = true; error_return = 0; break; } } if (optind >= argc) { // No on/off argument. usage(); return error_return; } if (!strcmp("on", argv[optind])) { switch_on = true; } else if (!strcmp("off", argv[optind])) { switch_on = false; } else { cerr << "Invalid switch value, should be either \"on\" or \"off\"." << endl; usage(); return error_return; } // Check the privileges. if (geteuid() != 0 && !silent) { cerr << "Warning: Program not running as root. It will most likely fail." << endl; } // Initialize the device. K81x *k81x = NULL; if (device_path == NULL && device_udevpath == NULL) { k81x = K81x::FromAutoFind(verbose); if (NULL == k81x && !silent) { cerr << "Error while looking for a Logitech K810/K811 keyboard." << endl; } } else { if (NULL != device_path) { k81x = K81x::FromDevicePath(device_path, verbose); if (NULL == k81x && !silent) { cerr << "Device " << device_path << " cannot be recognized as a supported Logitech K810/K811 keyboard." << endl; } } if (NULL == k81x && NULL != device_udevpath) { k81x = K81x::FromDeviceSysPath(device_udevpath, verbose); if (NULL == k81x && !silent) { cerr << "Udev device " << device_udevpath << " cannot be recognized as a supported Logitech K810/K811 keyboard." << endl; } } } int result = 0; if (k81x != NULL) { // Switch the Kn keys mode. if (!k81x->SetFnKeysMode(switch_on) && !silent) { cerr << "Error while setting the F-keys mode." << endl; result = error_return; } delete k81x; } else { result = error_return; } if (result && !verbose && !silent) { cerr << "Try running with -v parameter to get more details." << endl; } return result; } <|start_filename|>Makefile<|end_filename|> CC=gcc CXX=g++ RM=rm -f CPPFLAGS=-g -pthread LDFLAGS=-g -Wl,-z,now,-z,relro LDLIBS=-ludev TARGET=k81x-fkeys SRCS=src/k81x.cpp src/k81x-fkeys.cpp OBJS=$(subst .cpp,.o,$(SRCS)) all: $(TARGET) $(TARGET): $(OBJS) $(CXX) $(LDFLAGS) -o $(TARGET) $(OBJS) $(LDLIBS) depend: .depend .depend: $(SRCS) $(RM) ./.depend $(CXX) $(CPPFLAGS) -MM $^>>./.depend; clean: $(RM) $(OBJS) distclean: clean $(RM) *~ .depend $(RM) $(TARGET) install: $(TARGET) install -D -m 0755 $(TARGET) $(DESTDIR)/opt/k81x/$(TARGET) install -D -m 0755 contrib/k81x.sh $(DESTDIR)/opt/k81x/k81x.sh install -D -m 0644 contrib/00-k81x.rules $(DESTDIR)/etc/udev/rules.d/00-k81x.rules include .depend <|start_filename|>src/k81x.cpp<|end_filename|> // Copyright 2017 <NAME> <<EMAIL>> #include "./k81x.h" #include <errno.h> #include <fcntl.h> #include <libudev.h> #include <linux/hidraw.h> #include <linux/input.h> #include <sys/ioctl.h> #include <unistd.h> #include <cstddef> #include <cstring> #include <iostream> using std::cout; using std::cerr; using std::endl; using std::string; #define LOGITECH_VENDOR (__u32)0x046d #define PRODUCT_K810 (__s16)0xb319 #define PRODUCT_K811 (__s16)0xb317 const unsigned char fn_keys_on[] = {<KEY>}; const unsigned char fn_keys_off[] = {<KEY>}; K81x::K81x(string device_path, int device_file, bool verbose) { device_path_ = device_path; device_file_ = device_file; verbose_ = verbose; } K81x::~K81x() { if (device_file_ >= 0) { close(device_file_); } } K81x* K81x::FromDevicePath(const string device_path, bool verbose) { int device_file_ = open(device_path.c_str(), O_RDWR | O_NONBLOCK); if (device_file_ < 0) { if (verbose) cerr << "Unable to open device " << device_path << endl; return NULL; } struct hidraw_devinfo info; memset(&info, 0x0, sizeof(info)); K81x* result = NULL; if (ioctl(device_file_, HIDIOCGRAWINFO, &info) >= 0) { if (verbose) cout << "Checking whether " << device_path << " is a Logitech K810/K811 keyboard." << endl; if (info.bustype != BUS_BLUETOOTH || info.vendor != LOGITECH_VENDOR || (info.product != PRODUCT_K810 && info.product != PRODUCT_K811)) { if (verbose) cerr << "Cannot identify " << device_path << " as a supported Logitech Keyboard" << endl; } else { result = new K81x(device_path, device_file_, verbose); } } else { if (verbose) cerr << "Cannot fetch parameter of a device: " << device_path << endl; } if (result == NULL) { close(device_file_); } return result; } K81x* K81x::FromDeviceSysPath(const string device_syspath, bool verbose) { struct udev* udev; udev = udev_new(); if (!udev) { if (verbose) cerr << "Cannot create udev." << endl; return NULL; } udev_device* raw_dev = udev_device_new_from_syspath(udev, device_syspath.c_str()); udev_unref(udev); if (!raw_dev) { if (verbose) cerr << "Unknown udev device " << device_syspath << endl; return NULL; } string device_path = udev_device_get_devnode(raw_dev); if (verbose) cout << "Device path: " << device_path << endl; return K81x::FromDevicePath(device_path, verbose); } K81x* K81x::FromAutoFind(bool verbose) { struct udev* udev; udev = udev_new(); if (!udev) { if (verbose) cerr << "Cannot create udev." << endl; return NULL; } if (verbose) cout << "Looking for hidraw devices" << endl; udev_enumerate* enumerate = udev_enumerate_new(udev); udev_enumerate_add_match_subsystem(enumerate, "hidraw"); udev_enumerate_scan_devices(enumerate); udev_list_entry* devices = udev_enumerate_get_list_entry(enumerate); udev_list_entry* dev_list_entry; K81x* result = NULL; udev_list_entry_foreach(dev_list_entry, devices) { const char* sysfs_path = udev_list_entry_get_name(dev_list_entry); if (verbose) cout << "Found hidraw device: " << sysfs_path << endl; udev_device* raw_dev = udev_device_new_from_syspath(udev, sysfs_path); string device_path = udev_device_get_devnode(raw_dev); if (verbose) cout << "Device path: " << device_path << endl; result = K81x::FromDevicePath(device_path, verbose); if (NULL != result) break; } udev_enumerate_unref(enumerate); udev_unref(udev); if (NULL == result) { if (verbose) cerr << "Couldn't find a Logitech K810/K811 keyboard." << endl; } return result; } bool K81x::SetFnKeysMode(bool enabled) { if (enabled) { return WriteSequence(fn_keys_on, sizeof(fn_keys_on)); } return WriteSequence(fn_keys_off, sizeof(fn_keys_off)); } bool K81x::WriteSequence(const unsigned char* sequence, unsigned int size) { if (write(device_file_, sequence, size) < 0) { if (verbose_) cerr << "Error while writing to the device: " << string(strerror(errno)) << endl; return false; } else { if (verbose_) cout << "Successfully set the mode of keyboard F-keys!" << endl; } return true; } <|start_filename|>src/k81x.h<|end_filename|> // Copyright 2017 <NAME> <<EMAIL>> #ifndef K81X_H_ #define K81X_H_ #include <string> class K81x { public: static K81x* FromDevicePath(const std::string device_path, bool verbose); static K81x* FromDeviceSysPath(const std::string device_syspath, bool verbose); static K81x* FromAutoFind(bool verbose); ~K81x(); bool SetFnKeysMode(bool enabled); private: K81x(std::string device_path, int device_file, bool verbose); bool WriteSequence(const unsigned char* sequence, unsigned int size); int device_file_; std::string device_path_; bool verbose_; }; #endif // K81X_H_
themech/k810_k811_fkeys
<|start_filename|>components/widgets/krnpanel/assets/js/core/jquery.shapeshift.coffee<|end_filename|> # Project: jQuery.Shapeshift # Description: Align elements to grid with drag and drop. # Author: <NAME> # Maintained By: We the Media, inc. # License: MIT (($, window, document) -> pluginName = "shapeshift" defaults = # The Basics selector: "*" # Features enableDrag: true enableCrossDrop: true enableResize: true enableTrash: false # Grid Properties align: "center" colWidth: null columns: null minColumns: 1 autoHeight: true maxHeight: null minHeight: 100 gutterX: 10 gutterY: 10 paddingX: 10 paddingY: 10 # Animation animated: true animateOnInit: false animationSpeed: 225 animationThreshold: 100 # Drag/Drop Options dragClone: false deleteClone: true dragRate: 100 dragWhitelist: "*" crossDropWhitelist: "*" cutoffStart: null cutoffEnd: null handle: false # Customize CSS cloneClass: "ss-cloned-child" activeClass: "ss-active-child" draggedClass: "ss-dragged-child" placeholderClass: "ss-placeholder-child" originalContainerClass: "ss-original-container" currentContainerClass: "ss-current-container" previousContainerClass: "ss-previous-container" class Plugin constructor: (@element, options) -> @options = $.extend {}, defaults, options @globals = {} @$container = $(element) if @errorCheck() @init() # ---------------------------- # errorCheck: # Determine if there are any conflicting options # ---------------------------- errorCheck: -> options = @options errors = false error_msg = "Shapeshift ERROR:" # If there are no available children, a colWidth must be set if options.colWidth is null $children = @$container.children(options.selector) if $children.length is 0 errors = true console.error "#{error_msg} option colWidth must be specified if Shapeshift is initialized with no active children." return !errors # ---------------------------- # Init: # Only enable features on initialization, # then call a full render of the elements # ---------------------------- init: -> @createEvents() @setGlobals() @setIdentifier() @setActiveChildren() @enableFeatures() @gridInit() @render() @afterInit() # ---------------------------- # createEvents: # Triggerable events on the container # which run certain functions # ---------------------------- createEvents: -> options = @options $container = @$container $container.off("ss-arrange").on "ss-arrange", (e, trigger_drop_finished = false) => @render(false, trigger_drop_finished) $container.off("ss-rearrange").on "ss-rearrange", => @render(true) $container.off("ss-setTargetPosition").on "ss-setTargetPosition", => @setTargetPosition() $container.off("ss-destroy").on "ss-destroy", => @destroy() $container.off("ss-shuffle").on "ss-shuffle", => @shuffle() # ---------------------------- # setGlobals: # Globals that only need to be set on initialization # ---------------------------- setGlobals: -> # Prevent initial animation if applicable @globals.animated = @options.animateOnInit @globals.dragging = false # ---------------------------- # afterInit: # Take care of some dirty business # ---------------------------- afterInit: -> # Return animation to normal @globals.animated = @options.animated # ---------------------------- # setIdentifier # Create a random identifier to tie to this container so that # it is easy to unbind the specific resize event from the browser # ---------------------------- setIdentifier: -> @identifier = "shapeshifted_container_" + Math.random().toString(36).substring(7) @$container.addClass(@identifier) # ---------------------------- # enableFeatures: # Enables options features # ---------------------------- enableFeatures: -> @enableResize() if @options.enableResize @enableDragNDrop() if @options.enableDrag or @options.enableCrossDrop # ---------------------------- # setActiveChildren: # Make sure that only the children set by the # selector option can be affected by Shapeshifting # ---------------------------- setActiveChildren: -> options = @options # Add active child class to each available child element $children = @$container.children(options.selector) active_child_class = options.activeClass total = $children.length for i in [0...total] $($children[i]).addClass(active_child_class) @setParsedChildren() # Detect if there are any colspans wider than # the column options that were set columns = options.columns for i in [0...@parsedChildren.length] colspan = @parsedChildren[i].colspan min_columns = options.minColumns if colspan > columns and colspan > min_columns options.minColumns = colspan console.error "Shapeshift ERROR: There are child elements that have a larger colspan than the minimum columns set through options.\noptions.minColumns has been set to #{colspan}" # ---------------------------- # setParsedChildren: # Calculates and returns commonly used # attributes for all the active children # ---------------------------- setParsedChildren: -> $children = @$container.find("." + @options.activeClass).filter(":visible") total = $children.length parsedChildren = [] for i in [0...total] $child = $($children[i]) child = i: i el: $child colspan: parseInt($child.attr("data-ss-colspan")) || 1 height: $child.outerHeight() parsedChildren.push child @parsedChildren = parsedChildren # ---------------------------- # setGrid: # Calculates the dimensions of each column # and determines to total number of columns # ---------------------------- gridInit: -> gutter_x = @options.gutterX unless @options.colWidth >= 1 # Determine single item / col width first_child = @parsedChildren[0] fc_width = first_child.el.outerWidth() fc_colspan = first_child.colspan single_width = (fc_width - ((fc_colspan - 1) * gutter_x)) / fc_colspan @globals.col_width = single_width + gutter_x else @globals.col_width = @options.colWidth + gutter_x # ---------------------------- # render: # Determine the active children and # arrange them to the calculated grid # ---------------------------- render: (reparse = false, trigger_drop_finished) -> @setActiveChildren() if reparse @setGridColumns() @arrange(false, trigger_drop_finished) # ---------------------------- # setGrid: # Calculates the dimensions of each column # and determines to total number of columns # ---------------------------- setGridColumns: -> # Common globals = @globals options = @options col_width = globals.col_width gutter_x = options.gutterX padding_x = options.paddingX inner_width = @$container.innerWidth() - (padding_x * 2) # Determine how many columns there currently can be minColumns = options.minColumns columns = options.columns || Math.floor (inner_width + gutter_x) / col_width if minColumns and minColumns > columns columns = minColumns globals.columns = columns # Columns cannot exceed children span children_count = @parsedChildren.length if columns > children_count actual_columns = 0 for i in [0...@parsedChildren.length] colspan = @parsedChildren[i].colspan if colspan + actual_columns <= columns actual_columns += colspan columns = actual_columns # Calculate the child offset from the left globals.child_offset = padding_x switch options.align when "center" grid_width = (columns * col_width) - gutter_x globals.child_offset += (inner_width - grid_width) / 2 when "right" grid_width = (columns * col_width) - gutter_x globals.child_offset += (inner_width - grid_width) # ---------------------------- # arrange: # Animates the elements into their calcluated positions # ---------------------------- arrange: (reparse, trigger_drop_finished) -> @setParsedChildren() if reparse globals = @globals options = @options # Common $container = @$container child_positions = @getPositions() parsed_children = @parsedChildren total_children = parsed_children.length animated = globals.animated and total_children <= options.animationThreshold animation_speed = options.animationSpeed dragged_class = options.draggedClass # Arrange each child element for i in [0...total_children] $child = parsed_children[i].el attributes = child_positions[i] is_dragged_child = $child.hasClass(dragged_class) if is_dragged_child placeholder_class = options.placeholderClass $child = $child.siblings("." + placeholder_class) if animated and !is_dragged_child $child.stop(true, false).animate attributes, animation_speed, -> else $child.css attributes if trigger_drop_finished if animated setTimeout (-> $container.trigger("ss-drop-complete") ), animation_speed else $container.trigger("ss-drop-complete") $container.trigger("ss-arranged") # Set the container height if options.autoHeight container_height = globals.container_height max_height = options.maxHeight min_height = options.minHeight if min_height and container_height < min_height container_height = min_height else if max_height and container_height > max_height container_height = max_height $container.height container_height # ---------------------------- # getPositions: # Go over each child and determine which column they # fit into and return an array of their x/y dimensions # ---------------------------- getPositions: (include_dragged = true) -> globals = @globals options = @options gutter_y = options.gutterY padding_y = options.paddingY dragged_class = options.draggedClass parsed_children = @parsedChildren total_children = parsed_children.length # Store the height for each column col_heights = [] for i in [0...globals.columns] col_heights.push padding_y # ---------------------------- # savePosition # Takes a child which has been correctly placed in a # column and saves it to that final x/y position. # ---------------------------- savePosition = (child) => col = child.col colspan = child.colspan offset_x = (child.col * globals.col_width) + globals.child_offset offset_y = col_heights[col] positions[child.i] = left: offset_x, top: offset_y col_heights[col] += child.height + gutter_y if colspan >= 1 for j in [1...colspan] col_heights[col + j] = col_heights[col] # ---------------------------- # determineMultiposition # Children with multiple column spans will need special # rules to determine if they are currently able to be # placed in the grid. # ---------------------------- determineMultiposition = (child) => # Only use the columns that this child can fit into possible_cols = col_heights.length - child.colspan + 1 possible_col_heights = col_heights.slice(0).splice(0, possible_cols) chosen_col = undefined for offset in [0...possible_cols] col = @lowestCol(possible_col_heights, offset) colspan = child.colspan height = col_heights[col] kosher = true # Determine if it is able to be placed at this col for span in [1...colspan] next_height = col_heights[col + span] # The next height must not be higher if height < next_height kosher = false break if kosher chosen_col = col break return chosen_col # ---------------------------- # recalculateSavedChildren # Sometimes child elements cannot save the first time around, # iterate over those children and determine if its ok to place now. # ---------------------------- saved_children = [] recalculateSavedChildren = => to_pop = [] for saved_i in [0...saved_children.length] saved_child = saved_children[saved_i] saved_child.col = determineMultiposition(saved_child) if saved_child.col >= 0 savePosition(saved_child) to_pop.push(saved_i) # Popeye. Lol. for pop_i in [to_pop.length - 1..0] by -1 index = to_pop[pop_i] saved_children.splice(index,1) # ---------------------------- # determinePositions # Iterate over all the parsed children and determine # the calculations needed to get its x/y value. # ---------------------------- positions = [] do determinePositions = => for i in [0...total_children] child = parsed_children[i] unless !include_dragged and child.el.hasClass(dragged_class) if child.colspan > 1 child.col = determineMultiposition(child) else child.col = @lowestCol(col_heights) if child.col is undefined saved_children.push child else savePosition(child) recalculateSavedChildren() # Store the container height since we already have the data if options.autoHeight grid_height = col_heights[@highestCol(col_heights)] - gutter_y globals.container_height = grid_height + padding_y return positions # ---------------------------- # enableDrag: # Optional feature. # Initialize dragging. # ---------------------------- enableDragNDrop: -> options = @options $container = @$container active_class = options.activeClass dragged_class = options.draggedClass placeholder_class = options.placeholderClass original_container_class = options.originalContainerClass current_container_class = options.currentContainerClass previous_container_class = options.previousContainerClass delete_clone = options.deleteClone drag_rate = options.dragRate drag_clone = options.dragClone clone_class = options.cloneClass $selected = $placeholder = $clone = selected_offset_y = selected_offset_x = null drag_timeout = false if options.enableDrag $container.children("." + active_class).filter(options.dragWhitelist).draggable addClasses: false containment: 'document' handle: options.handle zIndex: 9999 start: (e, ui) => @globals.dragging = true # Set $selected globals $selected = $(e.target) if drag_clone $clone = $selected.clone(false, false).insertBefore($selected).addClass(clone_class) $selected.addClass(dragged_class) # Create Placeholder selected_tag = $selected.prop("tagName") $placeholder = $("<#{selected_tag} class='#{placeholder_class}' style='height: #{$selected.height()}px; width: #{$selected.width()}px'></#{selected_tag}>") # Set current container $selected.parent().addClass(original_container_class).addClass(current_container_class) # For manually centering the element with respect to mouse position selected_offset_y = $selected.outerHeight() / 2 selected_offset_x = $selected.outerWidth() / 2 drag: (e, ui) => if !drag_timeout and !(drag_clone and delete_clone and $("." + current_container_class)[0] is $("." + original_container_class)[0]) # Append placeholder to container $placeholder.remove().appendTo("." + current_container_class) # Set drag target and rearrange everything $("." + current_container_class).trigger("ss-setTargetPosition") # Disallow dragging from occurring too much drag_timeout = true window.setTimeout ( -> drag_timeout = false ), drag_rate # Manually center the element with respect to mouse position ui.position.left = e.pageX - $selected.parent().offset().left - selected_offset_x; ui.position.top = e.pageY - $selected.parent().offset().top - selected_offset_y; stop: => @globals.dragging = false $original_container = $("." + original_container_class) $current_container = $("." + current_container_class) $previous_container = $("." + previous_container_class) # Clear globals $selected.removeClass(dragged_class) $("." + placeholder_class).remove() if drag_clone if delete_clone and $("." + current_container_class)[0] is $("." + original_container_class)[0] $clone.remove() $("." + current_container_class).trigger("ss-rearrange") else $clone.removeClass(clone_class) # Trigger Events if $original_container[0] is $current_container[0] $current_container.trigger("ss-rearranged", $selected) else $original_container.trigger("ss-removed", $selected) $current_container.trigger("ss-added", $selected) # Arrange dragged item into place and clear container classes $original_container.trigger("ss-arrange").removeClass(original_container_class) $current_container.trigger("ss-arrange", true).removeClass(current_container_class) $previous_container.trigger("ss-arrange").removeClass(previous_container_class) $selected = $placeholder = null if options.enableCrossDrop $container.droppable accept: options.crossDropWhitelist tolerance: 'intersect' over: (e) => $("." + previous_container_class).removeClass(previous_container_class) $("." + current_container_class).removeClass(current_container_class).addClass(previous_container_class) $(e.target).addClass(current_container_class) drop: (e, selected) => if @options.enableTrash $original_container = $("." + original_container_class) $current_container = $("." + current_container_class) $previous_container = $("." + previous_container_class) $selected = $(selected.helper) $current_container.trigger("ss-trashed", $selected) $selected.remove() $original_container.trigger("ss-rearrange").removeClass(original_container_class) $current_container.trigger("ss-rearrange").removeClass(current_container_class) $previous_container.trigger("ss-arrange").removeClass(previous_container_class) # ---------------------------- # getTargetPosition: # Determine the target position for the selected # element and arrange it into place # ---------------------------- setTargetPosition: -> options = @options unless options.enableTrash dragged_class = options.draggedClass $selected = $("." + dragged_class) $start_container = $selected.parent() parsed_children = @parsedChildren child_positions = @getPositions(false) total_positions = child_positions.length selected_x = $selected.offset().left - $start_container.offset().left + (@globals.col_width / 2) selected_y = $selected.offset().top - $start_container.offset().top + ($selected.height() / 2) shortest_distance = 9999999 target_position = 0 if total_positions > 1 cutoff_start = options.cutoffStart + 1 || 0 cutoff_end = options.cutoffEnd || total_positions for position_i in [cutoff_start...cutoff_end] attributes = child_positions[position_i] if attributes y_dist = selected_x - attributes.left x_dist = selected_y - attributes.top if y_dist > 0 and x_dist > 0 distance = Math.sqrt((x_dist * x_dist) + (y_dist * y_dist)) if distance < shortest_distance shortest_distance = distance target_position = position_i if position_i is total_positions - 1 if y_dist > parsed_children[position_i].height / 2 target_position++ if target_position is parsed_children.length $target = parsed_children[target_position - 1].el $selected.insertAfter($target) else $target = parsed_children[target_position].el $selected.insertBefore($target) else if total_positions is 1 attributes = child_positions[0] if attributes.left < selected_x @$container.append $selected else @$container.prepend $selected else @$container.append $selected @arrange(true) if $start_container[0] isnt $selected.parent()[0] previous_container_class = options.previousContainerClass $("." + previous_container_class).trigger "ss-rearrange" else placeholder_class = @options.placeholderClass $("." + placeholder_class).remove() # ---------------------------- # resize: # Optional feature. # Runs a full render of the elements when # the browser window is resized. # ---------------------------- enableResize: -> animation_speed = @options.animationSpeed resizing = false binding = "resize." + @identifier $(window).on binding, => unless resizing resizing = true # Some funkyness to prevent too many renderings setTimeout (=> @render()), animation_speed / 3 setTimeout (=> @render()), animation_speed / 3 setTimeout => resizing = false @render() , animation_speed / 3 # ---------------------------- # shuffle: # Randomly sort the child elements # ---------------------------- shuffle: -> calculateShuffled = (container, activeClass) -> shuffle = (arr) -> j = undefined x = undefined i = arr.length while i j = parseInt(Math.random() * i) x = arr[--i] arr[i] = arr[j] arr[j] = x arr return container.each(-> items = container.find("." + activeClass).filter(":visible") (if (items.length) then container.html(shuffle(items)) else this) ) unless @globals.dragging calculateShuffled @$container, @options.activeClass @enableFeatures() @$container.trigger "ss-rearrange" # ---------------------------- # lowestCol: # Helper # Returns the index position of the # array column with the lowest number # ---------------------------- lowestCol: (array, offset = 0) -> length = array.length augmented_array = [] for i in [0...length] augmented_array.push [array[i], i] augmented_array.sort (a, b) -> ret = a[0] - b[0] ret = a[1] - b[1] if ret is 0 ret augmented_array[offset][1] # ---------------------------- # highestCol: # Helper # Returns the index position of the # array column with the highest number # ---------------------------- highestCol: (array) -> $.inArray Math.max.apply(window,array), array # ---------------------------- # destroy: # ---------------------------- destroy: -> $container = @$container $container.off("ss-arrange") $container.off("ss-rearrange") $container.off("ss-setTargetPosition") $container.off("ss-destroy") active_class = @options.activeClass $active_children = $container.find("." + active_class) if @options.enableDrag $active_children.draggable('destroy') if @options.enableCrossDrop $container.droppable('destroy') $active_children.removeClass(active_class) $container.removeClass(@identifier) $.fn[pluginName] = (options) -> @each -> # Destroy any old resize events old_class = $(@).attr("class")?.match(/shapeshifted_container_\w+/)?[0] if old_class bound_indentifier = "resize." + old_class $(window).off(bound_indentifier) $(@).removeClass(old_class) # Create the new plugin instance $.data(@, "plugin_#{pluginName}", new Plugin(@, options)) )(jQuery, window, document)
Sylveriam/proyecto-Todo-Tu-Club
<|start_filename|>src/game/client/tf/c_sdkversionchecker.cpp<|end_filename|> #include "cbase.h" #include "c_sdkversionchecker.h" #include "script_parser.h" #include "tier3/tier3.h" #include "cdll_util.h" //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- static C_SDKVersionChecker g_SDKVersionChecker; C_SDKVersionChecker *GetSDKVersionChecker() { return &g_SDKVersionChecker; } class C_SDKVersionParser : public C_ScriptParser { public: DECLARE_CLASS_GAMEROOT(C_SDKVersionParser, C_ScriptParser); C_SDKVersionParser() { Q_strncpy(sKey, "Unknown", sizeof(sKey)); } void Parse(KeyValues *pKeyValuesData, bool bWildcard, const char *szFileWithoutEXT) { for (KeyValues *pData = pKeyValuesData->GetFirstSubKey(); pData != NULL; pData = pData->GetNextKey()) { if (!Q_stricmp(pData->GetName(), "UserConfig")) { Q_strncpy(sKey, pData->GetString("BetaKey", ""), sizeof(sKey)); if (!Q_stricmp(sKey, "")) { Q_strncpy(sKey, "Default", sizeof(sKey)); } } } }; void SetSDKVersionChecker(C_SDKVersionChecker *pChecker) { pSDKVersionChecker = pChecker; } const char* GetKey() { char *szResult = (char*)malloc(sizeof(sKey)); Q_strncpy(szResult, sKey, sizeof(sKey)); return szResult; } private: char sKey[64]; C_SDKVersionChecker *pSDKVersionChecker; }; C_SDKVersionParser g_SDKVersionParser; void PrintBranchName(const CCommand &args) { Msg("SDK branch: %s\n", g_SDKVersionParser.GetKey()); } ConCommand tf2c_getsdkbranch("tf2c_getsdkbranch", PrintBranchName); //----------------------------------------------------------------------------- // Purpose: constructor //----------------------------------------------------------------------------- C_SDKVersionChecker::C_SDKVersionChecker() : CAutoGameSystemPerFrame("C_SDKVersionChecker") { if (!filesystem) return; m_bInited = false; Init(); } C_SDKVersionChecker::~C_SDKVersionChecker() { } //----------------------------------------------------------------------------- // Purpose: Initializer //----------------------------------------------------------------------------- bool C_SDKVersionChecker::Init() { if (!m_bInited) { g_SDKVersionParser.SetSDKVersionChecker(this); g_SDKVersionParser.InitParser("../../appmanifest_243750.acf", true, false, true); m_bInited = true; } return true; } const char* C_SDKVersionChecker::GetKey() { return g_SDKVersionParser.GetKey(); } <|start_filename|>src/game/shared/econ/econ_item_schema.cpp<|end_filename|> #include "cbase.h" #include "econ_item_schema.h" #include "econ_item_system.h" #include "tier3/tier3.h" #include "vgui/ILocalize.h" //----------------------------------------------------------------------------- // CEconItemAttribute //----------------------------------------------------------------------------- BEGIN_NETWORK_TABLE_NOBASE( CEconItemAttribute, DT_EconItemAttribute ) #ifdef CLIENT_DLL RecvPropInt( RECVINFO( m_iAttributeDefinitionIndex ) ), RecvPropFloat( RECVINFO( value ) ), RecvPropString( RECVINFO( value_string ) ), RecvPropString( RECVINFO( attribute_class ) ), #else SendPropInt( SENDINFO( m_iAttributeDefinitionIndex ) ), SendPropFloat( SENDINFO( value ) ), SendPropString( SENDINFO( value_string ) ), SendPropString( SENDINFO( attribute_class ) ), #endif END_NETWORK_TABLE() //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CEconItemAttribute::Init( int iIndex, float flValue, const char *pszAttributeClass /*= NULL*/ ) { m_iAttributeDefinitionIndex = iIndex; value = flValue; value_string.GetForModify()[0] = '\0'; if ( pszAttributeClass ) { V_strncpy( attribute_class.GetForModify(), pszAttributeClass, sizeof( attribute_class ) ); } else { EconAttributeDefinition *pAttribDef = GetStaticData(); if ( pAttribDef ) { V_strncpy( attribute_class.GetForModify(), pAttribDef->attribute_class, sizeof( attribute_class ) ); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CEconItemAttribute::Init( int iIndex, const char *pszValue, const char *pszAttributeClass /*= NULL*/ ) { m_iAttributeDefinitionIndex = iIndex; value = 0.0f; V_strncpy( value_string.GetForModify(), pszValue, sizeof( value_string ) ); if ( pszAttributeClass ) { V_strncpy( attribute_class.GetForModify(), pszAttributeClass, sizeof( attribute_class ) ); } else { EconAttributeDefinition *pAttribDef = GetStaticData(); if ( pAttribDef ) { V_strncpy( attribute_class.GetForModify(), pAttribDef->attribute_class, sizeof( attribute_class ) ); } } } EconAttributeDefinition *CEconItemAttribute::GetStaticData( void ) { return GetItemSchema()->GetAttributeDefinition( m_iAttributeDefinitionIndex ); } //----------------------------------------------------------------------------- // Purpose: for the UtlMap //----------------------------------------------------------------------------- static bool actLessFunc( const int &lhs, const int &rhs ) { return lhs < rhs; } //----------------------------------------------------------------------------- // EconItemVisuals //----------------------------------------------------------------------------- EconItemVisuals::EconItemVisuals() { animation_replacement.SetLessFunc( actLessFunc ); memset( aWeaponSounds, 0, sizeof( aWeaponSounds ) ); } //----------------------------------------------------------------------------- // CEconItemDefinition //----------------------------------------------------------------------------- EconItemVisuals *CEconItemDefinition::GetVisuals( int iTeamNum /*= TEAM_UNASSIGNED*/ ) { if ( iTeamNum > LAST_SHARED_TEAM && iTeamNum < TF_TEAM_COUNT ) { return &visual[iTeamNum]; } return &visual[TEAM_UNASSIGNED]; } int CEconItemDefinition::GetLoadoutSlot( int iClass /*= TF_CLASS_UNDEFINED*/ ) { if ( iClass && item_slot_per_class[iClass] != -1 ) { return item_slot_per_class[iClass]; } return item_slot; } //----------------------------------------------------------------------------- // Purpose: Generate item name to show in UI with prefixes, qualities, etc... //----------------------------------------------------------------------------- const wchar_t *CEconItemDefinition::GenerateLocalizedFullItemName( void ) { static wchar_t wszFullName[256]; wszFullName[0] = '\0'; wchar_t wszQuality[128]; wszQuality[0] = '\0'; if ( item_quality == QUALITY_UNIQUE ) { // Attach "the" if necessary to unique items. if ( propername ) { const wchar_t *pszPrepend = g_pVGuiLocalize->Find( "#TF_Unique_Prepend_Proper_Quality" ); if ( pszPrepend ) { V_wcsncpy( wszQuality, pszPrepend, sizeof( wszQuality ) ); } } } else if ( item_quality != QUALITY_NORMAL ) { // Live TF2 allows multiple qualities per item but eh, we don't need that for now. const wchar_t *pszQuality = g_pVGuiLocalize->Find( g_szQualityLocalizationStrings[item_quality] ); if ( pszQuality ) { V_wcsncpy( wszQuality, pszQuality, sizeof( wszQuality ) ); } } // Attach the original item name after we're done with all the prefixes. wchar_t wszItemName[256]; const wchar_t *pszLocalizedName = g_pVGuiLocalize->Find( item_name ); if ( pszLocalizedName && pszLocalizedName[0] ) { V_wcsncpy( wszItemName, pszLocalizedName, sizeof( wszItemName ) ); } else { g_pVGuiLocalize->ConvertANSIToUnicode( item_name, wszItemName, sizeof( wszItemName ) ); } g_pVGuiLocalize->ConstructString( wszFullName, sizeof( wszFullName ), L"%s1 %s2", 2, wszQuality, wszItemName ); return wszFullName; } //----------------------------------------------------------------------------- // Purpose: Generate item name without qualities, prefixes, etc. for disguise HUD... //----------------------------------------------------------------------------- const wchar_t *CEconItemDefinition::GenerateLocalizedItemNameNoQuality( void ) { static wchar_t wszFullName[256]; wszFullName[0] = '\0'; wchar_t wszQuality[128]; wszQuality[0] = '\0'; // Attach "the" if necessary to unique items. if ( propername ) { const wchar_t *pszPrepend = g_pVGuiLocalize->Find( "#TF_Unique_Prepend_Proper_Quality" ); if ( pszPrepend ) { V_wcsncpy( wszQuality, pszPrepend, sizeof( wszQuality ) ); } } // Attach the original item name after we're done with all the prefixes. wchar_t wszItemName[256]; const wchar_t *pszLocalizedName = g_pVGuiLocalize->Find( item_name ); if ( pszLocalizedName && pszLocalizedName[0] ) { V_wcsncpy( wszItemName, pszLocalizedName, sizeof( wszItemName ) ); } else { g_pVGuiLocalize->ConvertANSIToUnicode( item_name, wszItemName, sizeof( wszItemName ) ); } g_pVGuiLocalize->ConstructString( wszFullName, sizeof( wszFullName ), L"%s1 %s2", 2, wszQuality, wszItemName ); return wszFullName; } CEconItemAttribute *CEconItemDefinition::IterateAttributes( string_t strClass ) { // Returning the first attribute found. for ( int i = 0; i < attributes.Count(); i++ ) { CEconItemAttribute *pAttribute = &attributes[i]; if ( pAttribute->m_strAttributeClass == strClass ) { return pAttribute; } } return NULL; } <|start_filename|>src/game/shared/tf/tf_projectile_stunball.h<|end_filename|> //=============================================================================// // // Purpose: StunBallate Projectile // //=============================================================================// #ifndef TF_PROJECTILE_STUNBALL_H #define TF_PROJECTILE_STUNBALL_H #ifdef _WIN32 #pragma once #endif #include "tf_weaponbase_grenadeproj.h" #ifdef GAME_DLL #include "iscorer.h" #endif #ifdef CLIENT_DLL #define CTFStunBall C_TFStunBall #endif #ifdef GAME_DLL class CTFStunBall : public CTFWeaponBaseGrenadeProj, public IScorer #else class C_TFStunBall : public C_TFWeaponBaseGrenadeProj #endif { public: DECLARE_CLASS( CTFStunBall, CTFWeaponBaseGrenadeProj ); DECLARE_NETWORKCLASS(); #ifdef GAME_DLL DECLARE_DATADESC(); #endif CTFStunBall(); ~CTFStunBall(); virtual int GetWeaponID( void ) const { return TF_WEAPON_BAT_WOOD; } #ifdef GAME_DLL static CTFStunBall *Create( CBaseEntity *pWeapon, const Vector &vecOrigin, const QAngle &vecAngles, const Vector &vecVelocity, CBaseCombatCharacter *pOwner, CBaseEntity *pScorer, const AngularImpulse &angVelocity, const CTFWeaponInfo &weaponInfo ); // IScorer interface virtual CBasePlayer *GetScorer( void ) { return NULL; } virtual CBasePlayer *GetAssistant( void ); virtual void Precache( void ); virtual void Spawn( void ); virtual int GetDamageType(); virtual void Detonate( void ); virtual void VPhysicsCollision( int index, gamevcollisionevent_t *pEvent ); void StunBallTouch( CBaseEntity *pOther ); const char *GetTrailParticleName( void ); void CreateTrail( void ); void SetScorer( CBaseEntity *pScorer ); void SetCritical( bool bCritical ) { m_bCritical = bCritical; } virtual bool IsDeflectable() { return true; } virtual void Deflected( CBaseEntity *pDeflectedBy, Vector &vecDir ); virtual void Explode( trace_t *pTrace, int bitsDamageType ); bool CanStun( CTFPlayer *pOther ); #else virtual void OnDataChanged( DataUpdateType_t updateType ); virtual void CreateTrails( void ); virtual int DrawModel( int flags ); #endif private: #ifdef GAME_DLL CNetworkVar( bool, m_bCritical ); CHandle<CBaseEntity> m_hEnemy; EHANDLE m_Scorer; EHANDLE m_hSpriteTrail; #else bool m_bCritical; #endif float m_flCreationTime; }; #endif // TF_PROJECTILE_STUNBALL_H <|start_filename|>src/game/client/tf/c_tf_viewmodeladdon.cpp<|end_filename|> //========= Copyright Valve Corporation, All rights reserved. =================// // // Purpose: // //=============================================================================// #include "cbase.h" #include "c_tf_viewmodeladdon.h" #include "c_tf_player.h" #include "tf_viewmodel.h" #include "model_types.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" extern ConVar r_drawothermodels; void C_ViewmodelAttachmentModel::SetViewmodel( C_TFViewModel *vm ) { m_viewmodel.Set(vm); } int C_ViewmodelAttachmentModel::InternalDrawModel( int flags ) { CMatRenderContextPtr pRenderContext(materials); if (m_viewmodel->ShouldFlipViewModel()) pRenderContext->CullMode(MATERIAL_CULLMODE_CW); int ret = BaseClass::InternalDrawModel(flags); pRenderContext->CullMode(MATERIAL_CULLMODE_CCW); return ret; } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- bool C_ViewmodelAttachmentModel::OnPostInternalDrawModel( ClientModelRenderInfo_t *pInfo ) { if ( BaseClass::OnPostInternalDrawModel( pInfo ) ) { C_EconEntity *pEntity = GetOwningWeapon(); if ( pEntity ) { DrawEconEntityAttachedModels( this, pEntity, pInfo, 2 ); } return true; } return false; } //----------------------------------------------------------------------------- // Purpose: We're overriding this because DrawModel keeps calling the FollowEntity DrawModel function // which in this case is CTFViewModel::DrawModel. // This is basically just a straight copy of C_BaseAnimating::DrawModel, without the FollowEntity part //----------------------------------------------------------------------------- int C_ViewmodelAttachmentModel::DrawOverriddenViewmodel( int flags ) { if ( !m_bReadyToDraw ) return 0; int drawn = 0; ValidateModelIndex(); if (r_drawothermodels.GetInt()) { MDLCACHE_CRITICAL_SECTION(); int extraFlags = 0; if (r_drawothermodels.GetInt() == 2) { extraFlags |= STUDIO_WIREFRAME; } if (flags & STUDIO_SHADOWDEPTHTEXTURE) { extraFlags |= STUDIO_SHADOWDEPTHTEXTURE; } if (flags & STUDIO_SSAODEPTHTEXTURE) { extraFlags |= STUDIO_SSAODEPTHTEXTURE; } // Necessary for lighting blending CreateModelInstance(); drawn = InternalDrawModel(flags | extraFlags); } // If we're visualizing our bboxes, draw them DrawBBoxVisualizations(); return drawn; } int C_ViewmodelAttachmentModel::DrawModel( int flags ) { if ( !IsVisible() ) return 0; if (m_viewmodel.Get() == NULL) return 0; C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer(); C_TFPlayer *pPlayer = ToTFPlayer( m_viewmodel.Get()->GetOwner() ); if ( pLocalPlayer && pLocalPlayer->IsObserver() && pLocalPlayer->GetObserverTarget() != m_viewmodel.Get()->GetOwner() ) return false; if ( pLocalPlayer && !pLocalPlayer->IsObserver() && ( pLocalPlayer != pPlayer ) ) return false; return BaseClass::DrawModel( flags ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_ViewmodelAttachmentModel::StandardBlendingRules( CStudioHdr *hdr, Vector pos[], Quaternion q[], float currentTime, int boneMask ) { BaseClass::StandardBlendingRules( hdr, pos, q, currentTime, boneMask ); CTFWeaponBase *pWeapon = ( CTFWeaponBase * )m_viewmodel->GetOwningWeapon(); if ( !pWeapon ) return; if ( m_viewmodel->GetViewModelType() == VMTYPE_TF2 ) { pWeapon->SetMuzzleAttachment( LookupAttachment( "muzzle" ) ); } pWeapon->ViewModelAttachmentBlending( hdr, pos, q, currentTime, boneMask ); } <|start_filename|>src/game/shared/tf/tf_weapon_sniperrifle.cpp<|end_filename|> //====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======// // // Purpose: TF Sniper Rifle // //=============================================================================// #include "cbase.h" #include "tf_fx_shared.h" #include "tf_weapon_sniperrifle.h" #include "in_buttons.h" // Client specific. #ifdef CLIENT_DLL #include "view.h" #include "beamdraw.h" #include "vgui/ISurface.h" #include <vgui/ILocalize.h> #include "vgui_controls/Controls.h" #include "hud_crosshair.h" #include "functionproxy.h" #include "materialsystem/imaterialvar.h" #include "toolframework_client.h" #include "input.h" // For TFGameRules() and Player resources #include "tf_gamerules.h" #include "c_tf_playerresource.h" // forward declarations void ToolFramework_RecordMaterialParams( IMaterial *pMaterial ); #endif #define TF_WEAPON_SNIPERRIFLE_CHARGE_PER_SEC 50.0 #define TF_WEAPON_SNIPERRIFLE_UNCHARGE_PER_SEC 75.0 #define TF_WEAPON_SNIPERRIFLE_DAMAGE_MIN 50 #define TF_WEAPON_SNIPERRIFLE_DAMAGE_MAX 150 #define TF_WEAPON_SNIPERRIFLE_RELOAD_TIME 1.5f #define TF_WEAPON_SNIPERRIFLE_ZOOM_TIME 0.3f #define TF_WEAPON_SNIPERRIFLE_NO_CRIT_AFTER_ZOOM_TIME 0.2f #define SNIPER_DOT_SPRITE_RED "effects/sniperdot_red.vmt" #define SNIPER_DOT_SPRITE_BLUE "effects/sniperdot_blue.vmt" #define SNIPER_DOT_SPRITE_GREEN "effects/sniperdot_green.vmt" #define SNIPER_DOT_SPRITE_YELLOW "effects/sniperdot_yellow.vmt" #define SNIPER_DOT_SPRITE_CLEAR "effects/sniperdot_clear.vmt" //============================================================================= // // Weapon Sniper Rifles tables. // IMPLEMENT_NETWORKCLASS_ALIASED( TFSniperRifle, DT_TFSniperRifle ) BEGIN_NETWORK_TABLE_NOBASE( CTFSniperRifle, DT_SniperRifleLocalData ) #if !defined( CLIENT_DLL ) SendPropFloat( SENDINFO(m_flChargedDamage), 0, SPROP_NOSCALE | SPROP_CHANGES_OFTEN ), #else RecvPropFloat( RECVINFO(m_flChargedDamage) ), #endif END_NETWORK_TABLE() BEGIN_NETWORK_TABLE( CTFSniperRifle, DT_TFSniperRifle ) #if !defined( CLIENT_DLL ) SendPropDataTable( "SniperRifleLocalData", 0, &REFERENCE_SEND_TABLE( DT_SniperRifleLocalData ), SendProxy_SendLocalWeaponDataTable ), #else RecvPropDataTable( "SniperRifleLocalData", 0, 0, &REFERENCE_RECV_TABLE( DT_SniperRifleLocalData ) ), #endif END_NETWORK_TABLE() BEGIN_PREDICTION_DATA( CTFSniperRifle ) #ifdef CLIENT_DLL DEFINE_PRED_FIELD( m_flUnzoomTime, FIELD_FLOAT, 0 ), DEFINE_PRED_FIELD( m_flRezoomTime, FIELD_FLOAT, 0 ), DEFINE_PRED_FIELD( m_bRezoomAfterShot, FIELD_BOOLEAN, 0 ), DEFINE_PRED_FIELD( m_flChargedDamage, FIELD_FLOAT, 0 ), #endif END_PREDICTION_DATA() LINK_ENTITY_TO_CLASS( tf_weapon_sniperrifle, CTFSniperRifle ); PRECACHE_WEAPON_REGISTER( tf_weapon_sniperrifle ); //============================================================================= // // Weapon Sniper Rifles funcions. // //----------------------------------------------------------------------------- // Purpose: Constructor. //----------------------------------------------------------------------------- CTFSniperRifle::CTFSniperRifle() { // Server specific. #ifdef GAME_DLL m_hSniperDot = NULL; #endif } //----------------------------------------------------------------------------- // Purpose: Destructor. //----------------------------------------------------------------------------- CTFSniperRifle::~CTFSniperRifle() { // Server specific. #ifdef GAME_DLL DestroySniperDot(); #endif } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFSniperRifle::Spawn() { m_iAltFireHint = HINT_ALTFIRE_SNIPERRIFLE; BaseClass::Spawn(); ResetTimers(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFSniperRifle::Precache() { BaseClass::Precache(); PrecacheModel( SNIPER_DOT_SPRITE_RED ); PrecacheModel( SNIPER_DOT_SPRITE_BLUE ); PrecacheModel(SNIPER_DOT_SPRITE_GREEN); PrecacheModel(SNIPER_DOT_SPRITE_YELLOW); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFSniperRifle::ResetTimers( void ) { m_flUnzoomTime = -1; m_flRezoomTime = -1; m_bRezoomAfterShot = false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CTFSniperRifle::Reload( void ) { // We currently don't reload. return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CTFSniperRifle::CanHolster( void ) const { CTFPlayer *pPlayer = GetTFPlayerOwner(); if ( pPlayer ) { // don't allow us to holster this weapon if we're in the process of zooming and // we've just fired the weapon (next primary attack is only 1.5 seconds after firing) if ( ( pPlayer->GetFOV() < pPlayer->GetDefaultFOV() ) && ( m_flNextPrimaryAttack > gpGlobals->curtime ) ) { return false; } } return BaseClass::CanHolster(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CTFSniperRifle::Holster( CBaseCombatWeapon *pSwitchingTo ) { // Server specific. #ifdef GAME_DLL // Destroy the sniper dot. DestroySniperDot(); #endif CTFPlayer *pPlayer = ToTFPlayer( GetPlayerOwner() ); if ( pPlayer && pPlayer->m_Shared.InCond( TF_COND_ZOOMED ) ) { ZoomOut(); } m_flChargedDamage = 0.0f; ResetTimers(); return BaseClass::Holster( pSwitchingTo ); } void CTFSniperRifle::WeaponReset( void ) { BaseClass::WeaponReset(); ZoomOut(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFSniperRifle::HandleZooms( void ) { // Get the owning player. CTFPlayer *pPlayer = ToTFPlayer( GetOwner() ); if ( !pPlayer ) return; // Handle the zoom when taunting. if ( pPlayer->m_Shared.InCond( TF_COND_TAUNTING ) || pPlayer->m_Shared.InCond( TF_COND_STUNNED ) ) { if ( pPlayer->m_Shared.InCond( TF_COND_AIMING ) ) { ToggleZoom(); } //Don't rezoom in the middle of a taunt. ResetTimers(); } if ( m_flUnzoomTime > 0 && gpGlobals->curtime > m_flUnzoomTime ) { if ( m_bRezoomAfterShot ) { ZoomOutIn(); m_bRezoomAfterShot = false; } else { ZoomOut(); } m_flUnzoomTime = -1; } if ( m_flRezoomTime > 0 ) { if ( gpGlobals->curtime > m_flRezoomTime ) { ZoomIn(); m_flRezoomTime = -1; } } if ( ( pPlayer->m_nButtons & IN_ATTACK2 ) && ( m_flNextSecondaryAttack <= gpGlobals->curtime ) ) { // If we're in the process of rezooming, just cancel it if ( m_flRezoomTime > 0 || m_flUnzoomTime > 0 ) { // Prevent them from rezooming in less time than they would have m_flNextSecondaryAttack = m_flRezoomTime + TF_WEAPON_SNIPERRIFLE_ZOOM_TIME; m_flRezoomTime = -1; } else { Zoom(); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFSniperRifle::ItemPostFrame( void ) { // If we're lowered, we're not allowed to fire if ( m_bLowered ) return; // Get the owning player. CTFPlayer *pPlayer = ToTFPlayer( GetOwner() ); if ( !pPlayer ) return; if ( !CanAttack() ) { if ( IsZoomed() ) { ToggleZoom(); } return; } HandleZooms(); #ifdef GAME_DLL // Update the sniper dot position if we have one if ( m_hSniperDot ) { UpdateSniperDot(); } #endif // Start charging when we're zoomed in, and allowed to fire if ( pPlayer->m_Shared.IsJumping() ) { // Unzoom if we're jumping if ( IsZoomed() ) { ToggleZoom(); } m_flChargedDamage = 0.0f; m_bRezoomAfterShot = false; } else if ( m_flNextSecondaryAttack <= gpGlobals->curtime ) { // Don't start charging in the time just after a shot before we unzoom to play rack anim. if ( pPlayer->m_Shared.InCond( TF_COND_AIMING ) && !m_bRezoomAfterShot ) { m_flChargedDamage = min( m_flChargedDamage + gpGlobals->frametime * TF_WEAPON_SNIPERRIFLE_CHARGE_PER_SEC, TF_WEAPON_SNIPERRIFLE_DAMAGE_MAX ); } else { m_flChargedDamage = max( 0, m_flChargedDamage - gpGlobals->frametime * TF_WEAPON_SNIPERRIFLE_UNCHARGE_PER_SEC ); } } // Fire. if ( pPlayer->m_nButtons & IN_ATTACK ) { Fire( pPlayer ); } // Idle. if ( !( ( pPlayer->m_nButtons & IN_ATTACK) || ( pPlayer->m_nButtons & IN_ATTACK2 ) ) ) { // No fire buttons down or reloading if ( !ReloadOrSwitchWeapons() && ( m_bInReload == false ) ) { WeaponIdle(); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CTFSniperRifle::Lower( void ) { if ( BaseClass::Lower() ) { if ( IsZoomed() ) { ToggleZoom(); } return true; } return false; } //----------------------------------------------------------------------------- // Purpose: Secondary attack. //----------------------------------------------------------------------------- void CTFSniperRifle::Zoom( void ) { // Don't allow the player to zoom in while jumping CTFPlayer *pPlayer = GetTFPlayerOwner(); if ( pPlayer && pPlayer->m_Shared.IsJumping() ) { if ( pPlayer->GetFOV() >= 75 ) return; } ToggleZoom(); // at least 0.1 seconds from now, but don't stomp a previous value m_flNextPrimaryAttack = max( m_flNextPrimaryAttack, gpGlobals->curtime + 0.1 ); m_flNextSecondaryAttack = gpGlobals->curtime + TF_WEAPON_SNIPERRIFLE_ZOOM_TIME; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFSniperRifle::ZoomOutIn( void ) { ZoomOut(); CTFPlayer *pPlayer = GetTFPlayerOwner(); if ( pPlayer && pPlayer->ShouldAutoRezoom() ) { m_flRezoomTime = gpGlobals->curtime + 0.9; } else { m_flNextSecondaryAttack = gpGlobals->curtime + 1.0f; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFSniperRifle::ZoomIn( void ) { // Start aiming. CTFPlayer *pPlayer = GetTFPlayerOwner(); if ( !pPlayer ) return; if ( pPlayer->GetAmmoCount( m_iPrimaryAmmoType ) <= 0 ) return; BaseClass::ZoomIn(); pPlayer->m_Shared.AddCond( TF_COND_AIMING ); pPlayer->TeamFortress_SetSpeed(); #ifdef GAME_DLL // Create the sniper dot. CreateSniperDot(); pPlayer->ClearExpression(); #endif } bool CTFSniperRifle::IsZoomed( void ) { CTFPlayer *pPlayer = GetTFPlayerOwner(); if ( pPlayer ) { return pPlayer->m_Shared.InCond( TF_COND_ZOOMED ); } return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFSniperRifle::ZoomOut( void ) { BaseClass::ZoomOut(); // Stop aiming CTFPlayer *pPlayer = GetTFPlayerOwner(); if ( !pPlayer ) return; pPlayer->m_Shared.RemoveCond( TF_COND_AIMING ); pPlayer->TeamFortress_SetSpeed(); #ifdef GAME_DLL // Destroy the sniper dot. DestroySniperDot(); pPlayer->ClearExpression(); #endif // if we are thinking about zooming, cancel it m_flUnzoomTime = -1; m_flRezoomTime = -1; m_bRezoomAfterShot = false; m_flChargedDamage = 0.0f; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFSniperRifle::Fire( CTFPlayer *pPlayer ) { // Check the ammo. We don't use clip ammo, check the primary ammo type. if ( pPlayer->GetAmmoCount( m_iPrimaryAmmoType ) <= 0 ) { HandleFireOnEmpty(); return; } if ( m_flNextPrimaryAttack > gpGlobals->curtime ) return; // Fire the sniper shot. PrimaryAttack(); if ( IsZoomed() ) { // If we have more bullets, zoom out, play the bolt animation and zoom back in if( pPlayer->GetAmmoCount( m_iPrimaryAmmoType ) > 0 ) { SetRezoom( true, 0.5f ); // zoom out in 0.5 seconds, then rezoom } else { //just zoom out SetRezoom( false, 0.5f ); // just zoom out in 0.5 seconds } } else { // Prevent primary fire preventing zooms m_flNextSecondaryAttack = gpGlobals->curtime + SequenceDuration(); } m_flChargedDamage = 0.0f; #ifdef GAME_DLL if ( m_hSniperDot ) { m_hSniperDot->ResetChargeTime(); } #endif } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFSniperRifle::SetRezoom( bool bRezoom, float flDelay ) { m_flUnzoomTime = gpGlobals->curtime + flDelay; m_bRezoomAfterShot = bRezoom; } //----------------------------------------------------------------------------- // Purpose: // Output : float //----------------------------------------------------------------------------- float CTFSniperRifle::GetProjectileDamage( void ) { // Uncharged? Min damage. return max( m_flChargedDamage, TF_WEAPON_SNIPERRIFLE_DAMAGE_MIN ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CTFSniperRifle::GetDamageType( void ) const { // Only do hit location damage if we're zoomed CTFPlayer *pPlayer = ToTFPlayer( GetPlayerOwner() ); if ( pPlayer && pPlayer->m_Shared.InCond( TF_COND_ZOOMED ) ) return BaseClass::GetDamageType(); return ( BaseClass::GetDamageType() & ~DMG_USE_HITLOCATIONS ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFSniperRifle::CreateSniperDot( void ) { // Server specific. #ifdef GAME_DLL // Check to see if we have already been created? if ( m_hSniperDot ) return; // Get the owning player (make sure we have one). CBaseCombatCharacter *pPlayer = GetOwner(); if ( !pPlayer ) return; // Create the sniper dot, but do not make it visible yet. m_hSniperDot = CSniperDot::Create( GetAbsOrigin(), pPlayer, true ); m_hSniperDot->ChangeTeam( pPlayer->GetTeamNumber() ); #endif } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFSniperRifle::DestroySniperDot( void ) { // Server specific. #ifdef GAME_DLL // Destroy the sniper dot. if ( m_hSniperDot ) { UTIL_Remove( m_hSniperDot ); m_hSniperDot = NULL; } #endif } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFSniperRifle::UpdateSniperDot( void ) { // Server specific. #ifdef GAME_DLL CBasePlayer *pPlayer = ToBasePlayer( GetOwner() ); if ( !pPlayer ) return; // Get the start and endpoints. Vector vecMuzzlePos = pPlayer->Weapon_ShootPosition(); Vector forward; pPlayer->EyeVectors( &forward ); Vector vecEndPos = vecMuzzlePos + ( forward * MAX_TRACE_LENGTH ); trace_t trace; UTIL_TraceLine( vecMuzzlePos, vecEndPos, ( MASK_SHOT & ~CONTENTS_WINDOW ), GetOwner(), COLLISION_GROUP_NONE, &trace ); // Update the sniper dot. if ( m_hSniperDot ) { CBaseEntity *pEntity = NULL; if ( trace.DidHitNonWorldEntity() ) { pEntity = trace.m_pEnt; if ( !pEntity || !pEntity->m_takedamage ) { pEntity = NULL; } } m_hSniperDot->Update( pEntity, trace.endpos, trace.plane.normal ); } #endif } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CTFSniperRifle::CanFireCriticalShot( bool bIsHeadshot ) { // can only fire a crit shot if this is a headshot if ( !bIsHeadshot ) return false; CTFPlayer *pPlayer = GetTFPlayerOwner(); if ( pPlayer ) { // no crits if they're not zoomed if ( pPlayer->GetFOV() >= pPlayer->GetDefaultFOV() ) { return false; } // no crits for 0.2 seconds after starting to zoom if ( ( gpGlobals->curtime - pPlayer->GetFOVTime() ) < TF_WEAPON_SNIPERRIFLE_NO_CRIT_AFTER_ZOOM_TIME ) { return false; } } return true; } //============================================================================= // // Client specific functions. // #ifdef CLIENT_DLL //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- float CTFSniperRifle::GetHUDDamagePerc( void ) { return (m_flChargedDamage / TF_WEAPON_SNIPERRIFLE_DAMAGE_MAX); } //----------------------------------------------------------------------------- // Returns the sniper chargeup from 0 to 1 //----------------------------------------------------------------------------- class CProxySniperRifleCharge : public CResultProxy { public: void OnBind( void *pC_BaseEntity ); }; void CProxySniperRifleCharge::OnBind( void *pC_BaseEntity ) { Assert( m_pResult ); C_TFPlayer *pPlayer = C_TFPlayer::GetLocalTFPlayer(); if ( GetSpectatorTarget() != 0 && GetSpectatorMode() == OBS_MODE_IN_EYE ) { pPlayer = (C_TFPlayer *)UTIL_PlayerByIndex( GetSpectatorTarget() ); } if ( pPlayer ) { CTFSniperRifle *pWeapon = assert_cast<CTFSniperRifle*>(pPlayer->GetActiveTFWeapon()); if ( pWeapon ) { float flChargeValue = ( ( 1.0 - pWeapon->GetHUDDamagePerc() ) * 0.8 ) + 0.6; VMatrix mat, temp; Vector2D center( 0.5, 0.5 ); MatrixBuildTranslation( mat, -center.x, -center.y, 0.0f ); // scale { Vector2D scale( 1.0f, 0.25f ); MatrixBuildScale( temp, scale.x, scale.y, 1.0f ); MatrixMultiply( temp, mat, mat ); } MatrixBuildTranslation( temp, center.x, center.y, 0.0f ); MatrixMultiply( temp, mat, mat ); // translation { Vector2D translation( 0.0f, flChargeValue ); MatrixBuildTranslation( temp, translation.x, translation.y, 0.0f ); MatrixMultiply( temp, mat, mat ); } m_pResult->SetMatrixValue( mat ); } } if ( ToolsEnabled() ) { ToolFramework_RecordMaterialParams( GetMaterial() ); } } EXPOSE_INTERFACE( CProxySniperRifleCharge, IMaterialProxy, "SniperRifleCharge" IMATERIAL_PROXY_INTERFACE_VERSION ); #endif //============================================================================= // // Laser Dot functions. // IMPLEMENT_NETWORKCLASS_ALIASED( SniperDot, DT_SniperDot ) BEGIN_NETWORK_TABLE( CSniperDot, DT_SniperDot ) #ifdef CLIENT_DLL RecvPropFloat( RECVINFO( m_flChargeStartTime ) ), #else SendPropTime( SENDINFO( m_flChargeStartTime ) ), #endif END_NETWORK_TABLE() LINK_ENTITY_TO_CLASS( env_sniperdot, CSniperDot ); BEGIN_DATADESC( CSniperDot ) DEFINE_FIELD( m_vecSurfaceNormal, FIELD_VECTOR ), DEFINE_FIELD( m_hTargetEnt, FIELD_EHANDLE ), END_DATADESC() //----------------------------------------------------------------------------- // Purpose: Constructor. //----------------------------------------------------------------------------- CSniperDot::CSniperDot( void ) { m_vecSurfaceNormal.Init(); m_hTargetEnt = NULL; #ifdef CLIENT_DLL m_hSpriteMaterial = NULL; #endif ResetChargeTime(); } //----------------------------------------------------------------------------- // Purpose: Destructor. //----------------------------------------------------------------------------- CSniperDot::~CSniperDot( void ) { } //----------------------------------------------------------------------------- // Purpose: // Input : &origin - // Output : CSniperDot //----------------------------------------------------------------------------- CSniperDot *CSniperDot::Create( const Vector &origin, CBaseEntity *pOwner, bool bVisibleDot ) { // Client specific. #ifdef CLIENT_DLL return NULL; // Server specific. #else // Create the sniper dot entity. CSniperDot *pDot = static_cast<CSniperDot*>( CBaseEntity::Create( "env_sniperdot", origin, QAngle( 0.0f, 0.0f, 0.0f ) ) ); if ( !pDot ) return NULL; //Create the graphic pDot->SetMoveType( MOVETYPE_NONE ); pDot->AddSolidFlags( FSOLID_NOT_SOLID ); pDot->AddEffects( EF_NOSHADOW ); UTIL_SetSize( pDot, -Vector( 4.0f, 4.0f, 4.0f ), Vector( 4.0f, 4.0f, 4.0f ) ); // Set owner. pDot->SetOwnerEntity( pOwner ); // Force updates even though we don't have a model. pDot->AddEFlags( EFL_FORCE_CHECK_TRANSMIT ); return pDot; #endif } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSniperDot::Update( CBaseEntity *pTarget, const Vector &vecOrigin, const Vector &vecNormal ) { SetAbsOrigin( vecOrigin ); m_vecSurfaceNormal = vecNormal; m_hTargetEnt = pTarget; } //============================================================================= // // Client specific functions. // #ifdef CLIENT_DLL //----------------------------------------------------------------------------- // Purpose: // TFTODO: Make the sniper dot get brighter the more damage it will do. //----------------------------------------------------------------------------- int CSniperDot::DrawModel( int flags ) { // Get the owning player. C_TFPlayer *pPlayer = ToTFPlayer( GetOwnerEntity() ); if ( !pPlayer ) return -1; // Get the sprite rendering position. Vector vecEndPos; float flSize = 6.0; if ( !pPlayer->IsDormant() ) { Vector vecAttachment, vecDir; QAngle angles; float flDist = MAX_TRACE_LENGTH; // Always draw the dot in front of our faces when in first-person. if ( pPlayer->IsLocalPlayer() ) { // Take our view position and orientation vecAttachment = CurrentViewOrigin(); vecDir = CurrentViewForward(); // Clamp the forward distance for the sniper's firstperson flDist = 384; flSize = 2.0; } else { // Take the owning player eye position and direction. vecAttachment = pPlayer->EyePosition(); QAngle angles = pPlayer->EyeAngles(); AngleVectors( angles, &vecDir ); } trace_t tr; UTIL_TraceLine( vecAttachment, vecAttachment + ( vecDir * flDist ), MASK_SHOT, pPlayer, COLLISION_GROUP_NONE, &tr ); // Backup off the hit plane, towards the source vecEndPos = tr.endpos + vecDir * -4; } else { // Just use our position if we can't predict it otherwise. vecEndPos = GetAbsOrigin(); } // Draw our laser dot in space. CMatRenderContextPtr pRenderContext( materials ); pRenderContext->Bind( m_hSpriteMaterial, this ); float flLifeTime = gpGlobals->curtime - m_flChargeStartTime; float flStrength = RemapValClamped( flLifeTime, 0.0, TF_WEAPON_SNIPERRIFLE_DAMAGE_MAX / TF_WEAPON_SNIPERRIFLE_CHARGE_PER_SEC, 0.1, 1.0 ); color32 innercolor = { 255, 255, 255, 255 }; color32 outercolor = { 255, 255, 255, 128 }; DrawSprite( vecEndPos, flSize, flSize, outercolor ); DrawSprite( vecEndPos, flSize * flStrength, flSize * flStrength, innercolor ); // Successful. return 1; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CSniperDot::ShouldDraw( void ) { if ( IsEffectActive( EF_NODRAW ) ) return false; #if 0 // Don't draw the sniper dot when in thirdperson. if ( ::input->CAM_IsThirdPerson() ) return false; #endif return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSniperDot::OnDataChanged( DataUpdateType_t updateType ) { if ( updateType == DATA_UPDATE_CREATED ) { switch (GetTeamNumber()) { case TF_TEAM_RED: m_hSpriteMaterial.Init(SNIPER_DOT_SPRITE_RED, TEXTURE_GROUP_CLIENT_EFFECTS); break; case TF_TEAM_BLUE: m_hSpriteMaterial.Init(SNIPER_DOT_SPRITE_BLUE, TEXTURE_GROUP_CLIENT_EFFECTS); break; } } } #endif <|start_filename|>src/game/shared/tf/tf_inventory.cpp<|end_filename|> //========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: Simple Inventory // by MrModez // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "tf_shareddefs.h" #include "tf_inventory.h" #include "econ_item_system.h" static CTFInventory g_TFInventory; CTFInventory *GetTFInventory() { return &g_TFInventory; } CTFInventory::CTFInventory() : CAutoGameSystemPerFrame( "CTFInventory" ) { #ifdef CLIENT_DLL m_pInventory = NULL; #endif // Generate dummy base items. for ( int iClass = 0; iClass < TF_CLASS_COUNT_ALL; iClass++ ) { for ( int iSlot = 0; iSlot < TF_LOADOUT_SLOT_COUNT; iSlot++ ) { m_Items[iClass][iSlot].AddToTail( NULL ); } } }; CTFInventory::~CTFInventory() { #if defined( CLIENT_DLL ) m_pInventory->deleteThis(); #endif } bool CTFInventory::Init( void ) { GetItemSchema()->Init(); // Generate item list. FOR_EACH_MAP( GetItemSchema()->m_Items, i ) { int iItemID = GetItemSchema()->m_Items.Key( i ); CEconItemDefinition *pItemDef = GetItemSchema()->m_Items.Element( i ); if ( pItemDef->item_slot == -1 ) continue; // Add it to each class that uses it. for ( int iClass = 0; iClass < TF_CLASS_COUNT_ALL; iClass++ ) { if ( pItemDef->used_by_classes & ( 1 << iClass ) ) { // Show it if it's either base item or has show_in_armory flag. int iSlot = pItemDef->GetLoadoutSlot( iClass ); if ( pItemDef->baseitem ) { CEconItemView *pBaseItem = m_Items[iClass][iSlot][0]; if ( pBaseItem != NULL ) { Warning( "Duplicate base item %d for class %s in slot %s!\n", iItemID, g_aPlayerClassNames_NonLocalized[iClass], g_LoadoutSlots[iSlot] ); delete pBaseItem; } CEconItemView *pNewItem = new CEconItemView( iItemID ); #if defined ( GAME_DLL ) pNewItem->SetItemClassNumber( iClass ); #endif m_Items[iClass][iSlot][0] = pNewItem; } else if ( pItemDef->show_in_armory ) { CEconItemView *pNewItem = new CEconItemView( iItemID ); #if defined ( GAME_DLL ) pNewItem->SetItemClassNumber( iClass ); #endif m_Items[iClass][iSlot].AddToTail( pNewItem ); } } } } #if defined( CLIENT_DLL ) LoadInventory(); #endif return true; } void CTFInventory::LevelInitPreEntity( void ) { GetItemSchema()->Precache(); } int CTFInventory::GetNumPresets(int iClass, int iSlot) { return m_Items[iClass][iSlot].Count(); }; int CTFInventory::GetWeapon(int iClass, int iSlot) { return Weapons[iClass][iSlot]; }; CEconItemView *CTFInventory::GetItem( int iClass, int iSlot, int iNum ) { if ( CheckValidWeapon( iClass, iSlot, iNum ) == false ) return NULL; return m_Items[iClass][iSlot][iNum]; }; bool CTFInventory::CheckValidSlot(int iClass, int iSlot, bool bHudCheck /*= false*/) { if (iClass < TF_CLASS_UNDEFINED || iClass > TF_CLASS_COUNT) return false; int iCount = (bHudCheck ? INVENTORY_ROWNUM : TF_LOADOUT_SLOT_COUNT); // Array bounds check. if ( iSlot >= iCount || iSlot < 0 ) return false; // Slot must contain a base item. if ( m_Items[iClass][iSlot][0] == NULL ) return false; return true; }; bool CTFInventory::CheckValidWeapon(int iClass, int iSlot, int iWeapon, bool bHudCheck /*= false*/) { if (iClass < TF_CLASS_UNDEFINED || iClass > TF_CLASS_COUNT) return false; int iCount = ( bHudCheck ? INVENTORY_COLNUM : m_Items[iClass][iSlot].Count() ); // Array bounds check. if ( iWeapon >= iCount || iWeapon < 0 ) return false; // Don't allow switching if this class has no weapon at this position. if ( m_Items[iClass][iSlot][iWeapon] == NULL ) return false; return true; }; #if defined( CLIENT_DLL ) void CTFInventory::LoadInventory() { bool bExist = filesystem->FileExists("scripts/tf_inventory.txt", "MOD"); if (bExist) { if (!m_pInventory) { m_pInventory = new KeyValues("Inventory"); } m_pInventory->LoadFromFile(filesystem, "scripts/tf_inventory.txt"); } else { ResetInventory(); } }; void CTFInventory::SaveInventory() { m_pInventory->SaveToFile(filesystem, "scripts/tf_inventory.txt"); }; void CTFInventory::ResetInventory() { if (m_pInventory) { m_pInventory->deleteThis(); } m_pInventory = new KeyValues("Inventory"); for (int i = TF_CLASS_UNDEFINED; i < TF_CLASS_COUNT_ALL; i++) { KeyValues *pClassInv = new KeyValues(g_aPlayerClassNames_NonLocalized[i]); for (int j = 0; j < TF_LOADOUT_SLOT_COUNT; j++) { pClassInv->SetInt( g_LoadoutSlots[j], 0 ); } m_pInventory->AddSubKey(pClassInv); } SaveInventory(); } int CTFInventory::GetWeaponPreset(int iClass, int iSlot) { KeyValues *pClass = m_pInventory->FindKey(g_aPlayerClassNames_NonLocalized[iClass]); if (!pClass) //cannot find class node { ResetInventory(); return 0; } int iPreset = pClass->GetInt(g_LoadoutSlots[iSlot], -1); if (iPreset == -1) //cannot find slot node { ResetInventory(); return 0; } if ( CheckValidWeapon( iClass, iSlot, iPreset ) == false ) return 0; return iPreset; }; void CTFInventory::SetWeaponPreset(int iClass, int iSlot, int iPreset) { KeyValues* pClass = m_pInventory->FindKey(g_aPlayerClassNames_NonLocalized[iClass]); if (!pClass) //cannot find class node { ResetInventory(); pClass = m_pInventory->FindKey(g_aPlayerClassNames_NonLocalized[iClass]); } pClass->SetInt(GetSlotName(iSlot), iPreset); SaveInventory(); } const char* CTFInventory::GetSlotName(int iSlot) { return g_LoadoutSlots[iSlot]; }; #endif // Legacy array, used when we're forced to use old method of giving out weapons. const int CTFInventory::Weapons[TF_CLASS_COUNT_ALL][TF_PLAYER_WEAPON_COUNT] = { { }, { TF_WEAPON_SCATTERGUN, TF_WEAPON_PISTOL_SCOUT, TF_WEAPON_BAT }, { TF_WEAPON_SNIPERRIFLE, TF_WEAPON_SMG, TF_WEAPON_CLUB }, { TF_WEAPON_ROCKETLAUNCHER, TF_WEAPON_SHOTGUN_SOLDIER, TF_WEAPON_SHOVEL }, { TF_WEAPON_GRENADELAUNCHER, TF_WEAPON_PIPEBOMBLAUNCHER, TF_WEAPON_BOTTLE }, { TF_WEAPON_SYRINGEGUN_MEDIC, TF_WEAPON_MEDIGUN, TF_WEAPON_BONESAW }, { TF_WEAPON_MINIGUN, TF_WEAPON_SHOTGUN_HWG, TF_WEAPON_FISTS }, { TF_WEAPON_FLAMETHROWER, TF_WEAPON_SHOTGUN_PYRO, TF_WEAPON_FIREAXE }, { TF_WEAPON_REVOLVER, TF_WEAPON_NONE, TF_WEAPON_KNIFE, TF_WEAPON_PDA_SPY, TF_WEAPON_INVIS }, { TF_WEAPON_SHOTGUN_PRIMARY, TF_WEAPON_PISTOL, TF_WEAPON_WRENCH, TF_WEAPON_PDA_ENGINEER_BUILD, TF_WEAPON_PDA_ENGINEER_DESTROY }, }; <|start_filename|>src/game/shared/tf/tf_weapon_buff_item.cpp<|end_filename|> //=========== Copyright © 2018, LFE-Team, Not All rights reserved. ============ // // Purpose: // //============================================================================= #include "cbase.h" #include "tf_weapon_buff_item.h" #include "tf_fx_shared.h" #include "in_buttons.h" #include "datacache/imdlcache.h" #include "effect_dispatch_data.h" #include "engine/IEngineSound.h" #include "tf_gamerules.h" // Client specific. #ifdef CLIENT_DLL #include "c_tf_player.h" #include "particles_new.h" #include "tf_wearable.h" #include "tf_projectile_arrow.h" // Server specific. #else #include "tf_player.h" #include "ai_basenpc.h" #include "soundent.h" #include "te_effect_dispatch.h" #include "tf_fx.h" #include "tf_gamestats.h" #endif const char *g_BannerModels[] = { "models/weapons/c_models/c_buffbanner/c_buffbanner.mdl", "models/workshop/weapons/c_models/c_battalion_buffbanner/c_battalion_buffbanner.mdl", "models/workshop_partner/weapons/c_models/c_shogun_warbanner/c_shogun_warbanner.mdl", "models/workshop/weapons/c_models/c_paratooper_pack/c_paratrooper_parachute.mdl", }; //============================================================================= // // Weapon BUFF item tables. // IMPLEMENT_NETWORKCLASS_ALIASED( TFBuffItem, DT_WeaponBuffItem ) BEGIN_NETWORK_TABLE( CTFBuffItem, DT_WeaponBuffItem ) #ifdef CLIENT_DLL RecvPropBool( RECVINFO( m_bBuffUsed ) ), #else SendPropBool( SENDINFO( m_bBuffUsed ) ), #endif END_NETWORK_TABLE() BEGIN_PREDICTION_DATA( CTFBuffItem ) #ifdef CLIENT_DLL #endif END_PREDICTION_DATA() LINK_ENTITY_TO_CLASS( tf_weapon_buff_item, CTFBuffItem ); PRECACHE_WEAPON_REGISTER( tf_weapon_buff_item ); // Server specific. #ifndef CLIENT_DLL BEGIN_DATADESC( CTFBuffItem ) END_DATADESC() #endif CTFBuffItem::CTFBuffItem() { m_flEffectBarRegenTime = 0.0f; UseClientSideAnimation(); #ifdef CLIENT_DLL ListenForGameEvent( "deploy_buff_banner" ); #endif } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFBuffItem::Precache( void ) { PrecacheTeamParticles( "soldierbuff_%s_buffed" ); PrecacheParticleSystem( "soldierbuff_mvm" ); for ( int i = 0; i < ARRAYSIZE( g_BannerModels ); i++ ) { PrecacheModel( g_BannerModels[i] ); } PrecacheModel( "models/weapons/c_models/c_buffpack/c_buffpack.mdl" ); PrecacheModel( "models/workshop/weapons/c_models/c_battalion_buffpack/c_battalion_buffpack.mdl" ); PrecacheModel( "models/workshop_partner/weapons/c_models/c_shogun_warpack/c_shogun_warpack.mdl" ); PrecacheModel( "models/workshop/weapons/c_models/c_paratooper_pack/c_paratrooper_pack_open.mdl" ); PrecacheModel( "models/workshop/weapons/c_models/c_paratooper_pack/c_paratrooper_pack.mdl" ); PrecacheScriptSound( "Weapon_BuffBanner.HornRed" ); PrecacheScriptSound( "Weapon_BuffBanner.HornBlue" ); PrecacheScriptSound( "Weapon_BattalionsBackup.HornRed" ); PrecacheScriptSound( "Weapon_BattalionsBackup.HornBlue" ); PrecacheScriptSound( "Samurai.Conch" ); PrecacheScriptSound( "Weapon_BuffBanner.Flag" ); BaseClass::Precache(); } //----------------------------------------------------------------------------- // Purpose: Only holster when the buff isn't used //----------------------------------------------------------------------------- bool CTFBuffItem::Holster( CBaseCombatWeapon *pSwitchingTo ) { if ( !m_bBuffUsed ) { return BaseClass::Holster( pSwitchingTo ); } return false; } //----------------------------------------------------------------------------- // Purpose: Reset the charge meter //----------------------------------------------------------------------------- void CTFBuffItem::WeaponReset( void ) { m_bBuffUsed = false; BaseClass::WeaponReset(); } // ---------------------------------------------------------------------------- - // Purpose: //----------------------------------------------------------------------------- void CTFBuffItem::PrimaryAttack( void ) { // Rage not ready //if ( !IsFull() ) //return; if ( !CanAttack() ) return; CTFPlayer *pOwner = GetTFPlayerOwner(); if ( !pOwner ) return; if ( !m_bBuffUsed && pOwner->m_Shared.GetRageProgress() >= 100.0f ) { if ( GetTeamNumber() == TF_TEAM_RED ) { SendWeaponAnim( ACT_VM_PRIMARYATTACK ); } else { SendWeaponAnim( ACT_VM_SECONDARYATTACK ); } pOwner->DoAnimationEvent( PLAYERANIMEVENT_ATTACK_SECONDARY ); #ifdef GAME_DLL SetContextThink( &CTFBuffItem::BlowHorn, gpGlobals->curtime + 0.22f, "BlowHorn" ); #endif } } // ---------------------------------------------------------------------------- - // Purpose: //----------------------------------------------------------------------------- void CTFBuffItem::BlowHorn( void ) { if ( !CanAttack() ) return; CTFPlayer *pOwner = GetTFPlayerOwner(); if ( !pOwner || !pOwner->IsAlive() ) return; int iBuffType = GetBuffType(); const char *iszSound = "\0"; switch( iBuffType ) { case TF_BUFF_OFFENSE: if ( pOwner->GetTeamNumber() == TF_TEAM_RED ) iszSound = "Weapon_BuffBanner.HornRed"; else iszSound = "Weapon_BuffBanner.HornBlue"; break; case TF_BUFF_DEFENSE: if ( pOwner->GetTeamNumber() == TF_TEAM_RED ) iszSound = "Weapon_BattalionsBackup.HornRed"; else iszSound = "Weapon_BattalionsBackup.HornBlue"; break; case TF_BUFF_REGENONDAMAGE: iszSound = "Samurai.Conch"; break; }; pOwner->EmitSound( iszSound ); } // ---------------------------------------------------------------------------- - // Purpose: //----------------------------------------------------------------------------- void CTFBuffItem::RaiseFlag( void ) { if ( !CanAttack() ) return; CTFPlayer *pOwner = GetTFPlayerOwner(); if ( !pOwner || !pOwner->IsAlive() ) return; int iBuffType = GetBuffType(); #ifdef GAME_DLL m_bBuffUsed = false; IGameEvent *event = gameeventmanager->CreateEvent( "deploy_buff_banner" ); if ( event ) { event->SetInt( "buff_type", iBuffType ); event->SetInt( "buff_owner", pOwner->entindex() ); gameeventmanager->FireEvent( event ); } pOwner->EmitSound( "Weapon_BuffBanner.Flag" ); pOwner->SpeakConceptIfAllowed( MP_CONCEPT_PLAYER_BATTLECRY ); #endif pOwner->m_Shared.ActivateRageBuff( this, iBuffType ); pOwner->SwitchToNextBestWeapon( this ); } // ----------------------------------------------------------------------------- // Purpose: // ----------------------------------------------------------------------------- int CTFBuffItem::GetBuffType( void ) { int iBuffType = 0; CALL_ATTRIB_HOOK_INT( iBuffType, set_buff_type ); return iBuffType; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- float CTFBuffItem::GetEffectBarProgress( void ) { CTFPlayer *pOwner = GetTFPlayerOwner(); if ( pOwner) { return pOwner->m_Shared.GetRageProgress() / 100.0f; } return 0.0f; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CTFBuffItem::EffectMeterShouldFlash( void ) { CTFPlayer *pOwner = GetTFPlayerOwner(); // Rage meter should flash while draining if ( pOwner && pOwner->m_Shared.IsRageActive() && pOwner->m_Shared.GetRageProgress() < 100.0f ) { return true; } return false; } //----------------------------------------------------------------------------- // Purpose: Make sure the weapon uses the correct animations //----------------------------------------------------------------------------- bool CTFBuffItem::SendWeaponAnim( int iActivity ) { int iNewActivity = iActivity; switch ( iActivity ) { case ACT_VM_DRAW: iNewActivity =ACT_ITEM1_VM_DRAW; break; case ACT_VM_HOLSTER: iNewActivity = ACT_ITEM1_VM_HOLSTER; break; case ACT_VM_IDLE: iNewActivity = ACT_ITEM1_VM_IDLE; // Do the flag raise animation if ( m_bBuffUsed ) { RaiseFlag(); iNewActivity = ACT_RESET; } else break; case ACT_VM_PULLBACK: iNewActivity = ACT_ITEM1_VM_PULLBACK; break; case ACT_VM_PRIMARYATTACK: iNewActivity = ACT_ITEM1_VM_PRIMARYATTACK; m_bBuffUsed = true; break; case ACT_VM_SECONDARYATTACK: iNewActivity = ACT_ITEM1_VM_SECONDARYATTACK; m_bBuffUsed = true; break; case ACT_VM_IDLE_TO_LOWERED: iNewActivity = ACT_ITEM1_VM_IDLE_TO_LOWERED; break; case ACT_VM_IDLE_LOWERED: iNewActivity = ACT_ITEM1_VM_IDLE_LOWERED; break; case ACT_VM_LOWERED_TO_IDLE: iNewActivity = ACT_ITEM1_VM_LOWERED_TO_IDLE; break; }; return BaseClass::SendWeaponAnim( iNewActivity ); } #ifdef CLIENT_DLL //----------------------------------------------------------------------------- // Purpose: Create the banner addon for the backpack //----------------------------------------------------------------------------- void C_TFBuffItem::CreateBanner( int iBuffType ) { C_TFPlayer *pOwner = GetTFPlayerOwner(); if ( !pOwner || !pOwner->IsAlive() ) return; C_EconWearable *pWearable = pOwner->GetWearableForLoadoutSlot( TF_LOADOUT_SLOT_SECONDARY ); // if we don't have a backpack for some reason don't make a banner if ( !pWearable ) return; // yes I really am using the arrow class as a base // create the flag C_TFProjectile_Arrow *pBanner = new C_TFProjectile_Arrow(); if ( pBanner ) { pBanner->InitializeAsClientEntity( g_BannerModels[iBuffType - 1], RENDER_GROUP_OPAQUE_ENTITY ); // Attach the flag to the backpack int bone = pWearable->LookupBone( "bip_spine_3" ); if ( bone != -1 ) { pBanner->SetDieTime( gpGlobals->curtime + 10.0f ); pBanner->AttachEntityToBone( pWearable, bone ); } } } /*//----------------------------------------------------------------------------- // Purpose: Destroy the banner addon for the backpack //----------------------------------------------------------------------------- void C_TFBuffItem::DestroyBanner( void ) { C_TFPlayer *pOwner = GetTFPlayerOwner(); if ( !pOwner ) return; C_EconWearable *pWearable = pOwner->GetWearableForLoadoutSlot( TF_LOADOUT_SLOT_SECONDARY ); if ( !pWearable ) return; pWearable->DestroyBoneAttachments(); }*/ //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_TFBuffItem::FireGameEvent(IGameEvent *event) { if ( V_strcmp( event->GetName(), "deploy_buff_banner" ) == 0 ) { int entindex = event->GetInt( "buff_owner" ); // Make sure the person who deployed owns this weapon if ( UTIL_PlayerByIndex( entindex ) == GetPlayerOwner() ) { // Create the banner addon CreateBanner( event->GetInt( "buff_type" ) ); } } } #endif <|start_filename|>src/game/shared/tf/tf_projectile_jar.cpp<|end_filename|> #include "cbase.h" #include "tf_projectile_jar.h" #include "tf_gamerules.h" #include "effect_dispatch_data.h" #include "tf_weapon_jar.h" #ifdef GAME_DLL #include "tf_fx.h" #else #include "particles_new.h" #endif #define TF_WEAPON_JAR_MODEL "models/weapons/c_models/urinejar.mdl" #define TF_WEAPON_JAR_LIFETIME 2.0f IMPLEMENT_NETWORKCLASS_ALIASED( TFProjectile_Jar, DT_TFProjectile_Jar ) BEGIN_NETWORK_TABLE( CTFProjectile_Jar, DT_TFProjectile_Jar ) #ifdef CLIENT_DLL RecvPropBool( RECVINFO( m_bCritical ) ), #else SendPropBool( SENDINFO( m_bCritical ) ), #endif END_NETWORK_TABLE() #ifdef GAME_DLL BEGIN_DATADESC( CTFProjectile_Jar ) END_DATADESC() #endif ConVar tf_jar_show_radius( "tf_jar_show_radius", "0", FCVAR_REPLICATED | FCVAR_CHEAT /*| FCVAR_DEVELOPMENTONLY*/, "Render jar radius." ); LINK_ENTITY_TO_CLASS( tf_projectile_jar, CTFProjectile_Jar ); PRECACHE_REGISTER( tf_projectile_jar ); CTFProjectile_Jar::CTFProjectile_Jar() { } CTFProjectile_Jar::~CTFProjectile_Jar() { #ifdef CLIENT_DLL ParticleProp()->StopEmission(); #endif } #ifdef GAME_DLL CTFProjectile_Jar *CTFProjectile_Jar::Create( CBaseEntity *pWeapon, const Vector &vecOrigin, const QAngle &vecAngles, const Vector &vecVelocity, CBaseCombatCharacter *pOwner, CBaseEntity *pScorer, const AngularImpulse &angVelocity, const CTFWeaponInfo &weaponInfo ) { CTFProjectile_Jar *pJar = static_cast<CTFProjectile_Jar *>( CBaseEntity::CreateNoSpawn( "tf_projectile_jar", vecOrigin, vecAngles, pOwner ) ); if ( pJar ) { // Set scorer. pJar->SetScorer( pScorer ); // Set firing weapon. pJar->SetLauncher( pWeapon ); DispatchSpawn( pJar ); pJar->InitGrenade( vecVelocity, angVelocity, pOwner, weaponInfo ); pJar->ApplyLocalAngularVelocityImpulse( angVelocity ); } return pJar; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFProjectile_Jar::Precache( void ) { PrecacheModel( TF_WEAPON_JAR_MODEL ); PrecacheTeamParticles( "peejar_trail_%s", false, g_aTeamNamesShort ); PrecacheParticleSystem( "peejar_impact" ); PrecacheScriptSound( "Jar.Explode" ); BaseClass::Precache(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFProjectile_Jar::Spawn( void ) { SetModel( TF_WEAPON_JAR_MODEL ); SetDetonateTimerLength( TF_WEAPON_JAR_LIFETIME ); BaseClass::Spawn(); SetTouch( &CTFProjectile_Jar::JarTouch ); // Pumpkin Bombs AddFlag( FL_GRENADE ); // Don't collide with anything for a short time so that we never get stuck behind surfaces SetCollisionGroup( TFCOLLISION_GROUP_NONE ); AddSolidFlags( FSOLID_TRIGGER ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFProjectile_Jar::Explode( trace_t *pTrace, int bitsDamageType ) { // Invisible. SetModelName( NULL_STRING ); AddSolidFlags( FSOLID_NOT_SOLID ); m_takedamage = DAMAGE_NO; // Pull out of the wall a bit if ( pTrace->fraction != 1.0 ) { SetAbsOrigin( pTrace->endpos + ( pTrace->plane.normal * 1.0f ) ); } CTFWeaponBase *pWeapon = dynamic_cast<CTFWeaponBase *>( m_hLauncher.Get() ); // Pull out a bit. if ( pTrace->fraction != 1.0 ) { SetAbsOrigin( pTrace->endpos + ( pTrace->plane.normal * 1.0f ) ); } // Play explosion sound and effect. Vector vecOrigin = GetAbsOrigin(); //EmitSound( "Jar.Explode" ); CPVSFilter filter( vecOrigin ); TE_TFExplosion( filter, 0.0f, vecOrigin, pTrace->plane.normal, GetWeaponID(), -1 ); // Damage. CBaseEntity *pAttacker = NULL; pAttacker = pWeapon->GetOwnerEntity(); float flRadius = GetDamageRadius(); CTFRadiusDamageInfo radiusInfo; radiusInfo.info.Set( this, pAttacker, m_hLauncher, vec3_origin, vecOrigin, GetDamage(), GetDamageType() ); radiusInfo.m_vecSrc = vecOrigin; radiusInfo.m_flRadius = flRadius; radiusInfo.m_flSelfDamageRadius = 121.0f; // Original rocket radius? // If we extinguish a friendly player reduce our recharge time by four seconds if ( TFGameRules()->RadiusJarEffect( radiusInfo, TF_COND_URINE ) && m_iDeflected == 0 && pWeapon ) { pWeapon->ReduceEffectBarRegenTime( 4.0f ); } // Debug! if ( tf_jar_show_radius.GetBool() ) { DrawRadius( flRadius ); } SetThink( &CBaseGrenade::SUB_Remove ); SetTouch( NULL ); UTIL_Remove( this ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFProjectile_Jar::JarTouch( CBaseEntity *pOther ) { if ( pOther == GetThrower() ) { // Make us solid if we're not already if ( GetCollisionGroup() == TFCOLLISION_GROUP_NONE ) { SetCollisionGroup( COLLISION_GROUP_PROJECTILE ); } return; } // Verify a correct "other." if ( !pOther->IsSolid() || pOther->IsSolidFlagSet( FSOLID_VOLUME_CONTENTS ) ) return; // Handle hitting skybox (disappear). trace_t pTrace; Vector velDir = GetAbsVelocity(); VectorNormalize( velDir ); Vector vecSpot = GetAbsOrigin() - velDir * 32; UTIL_TraceLine( vecSpot, vecSpot + velDir * 64, MASK_SOLID, this, COLLISION_GROUP_NONE, &pTrace ); if ( pTrace.fraction < 1.0 && pTrace.surface.flags & SURF_SKY ) { UTIL_Remove( this ); return; } // Blow up if we hit a player if ( pOther->IsPlayer() ) { Explode( &pTrace, GetDamageType() ); } // We should bounce off of certain surfaces (resupply cabinets, spawn doors, etc.) else { return; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFProjectile_Jar::Detonate() { trace_t tr; Vector vecSpot;// trace starts here! SetThink( NULL ); vecSpot = GetAbsOrigin() + Vector ( 0 , 0 , 8 ); UTIL_TraceLine ( vecSpot, vecSpot + Vector ( 0, 0, -32 ), MASK_SHOT_HULL, this, COLLISION_GROUP_NONE, & tr); Explode( &tr, GetDamageType() ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFProjectile_Jar::VPhysicsCollision( int index, gamevcollisionevent_t *pEvent ) { BaseClass::VPhysicsCollision( index, pEvent ); int otherIndex = !index; CBaseEntity *pHitEntity = pEvent->pEntities[otherIndex]; if ( !pHitEntity ) { return; } // TODO: This needs to be redone properly /*if ( pHitEntity->GetMoveType() == MOVETYPE_NONE ) { // Blow up SetThink( &CTFProjectile_Jar::Detonate ); SetNextThink( gpGlobals->curtime ); }*/ // Blow up SetThink( &CTFProjectile_Jar::Detonate ); SetNextThink( gpGlobals->curtime ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFProjectile_Jar::SetScorer( CBaseEntity *pScorer ) { m_Scorer = pScorer; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CBasePlayer *CTFProjectile_Jar::GetAssistant( void ) { return dynamic_cast<CBasePlayer *>( m_Scorer.Get() ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFProjectile_Jar::Deflected( CBaseEntity *pDeflectedBy, Vector &vecDir ) { /*// Get jar's speed. float flVel = GetAbsVelocity().Length(); QAngle angForward; VectorAngles( vecDir, angForward ); AngularImpulse angVelocity( ( 600, random->RandomInt( -1200, 1200 ), 0 ) ); // Now change jar's direction. SetAbsAngles( angForward ); SetAbsVelocity( vecDir * flVel ); // Bounce it up a bit ApplyLocalAngularVelocityImpulse( angVelocity ); IncremenentDeflected(); SetOwnerEntity( pDeflectedBy ); ChangeTeam( pDeflectedBy->GetTeamNumber() ); SetScorer( pDeflectedBy );*/ IPhysicsObject *pPhysicsObject = VPhysicsGetObject(); if ( pPhysicsObject ) { Vector vecOldVelocity, vecVelocity; pPhysicsObject->GetVelocity( &vecOldVelocity, NULL ); float flVel = vecOldVelocity.Length(); vecVelocity = vecDir; vecVelocity *= flVel; AngularImpulse angVelocity( ( 600, random->RandomInt( -1200, 1200 ), 0 ) ); // Now change grenade's direction. pPhysicsObject->SetVelocityInstantaneous( &vecVelocity, &angVelocity ); } CBaseCombatCharacter *pBCC = pDeflectedBy->MyCombatCharacterPointer(); IncremenentDeflected(); m_hDeflectOwner = pDeflectedBy; SetThrower( pBCC ); ChangeTeam( pDeflectedBy->GetTeamNumber() ); } #else //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_TFProjectile_Jar::OnDataChanged( DataUpdateType_t updateType ) { BaseClass::OnDataChanged( updateType ); if ( updateType == DATA_UPDATE_CREATED ) { m_flCreationTime = gpGlobals->curtime; CreateTrails(); } if ( m_iOldTeamNum && m_iOldTeamNum != m_iTeamNum ) { ParticleProp()->StopEmission(); CreateTrails(); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_TFProjectile_Jar::CreateTrails( void ) { if ( IsDormant() ) return; const char *pszEffectName = ConstructTeamParticle( "peejar_trail_%s", GetTeamNumber(), false, g_aTeamNamesShort ); ParticleProp()->Create( pszEffectName, PATTACH_ABSORIGIN_FOLLOW ); } //----------------------------------------------------------------------------- // Purpose: Don't draw if we haven't yet gone past our original spawn point //----------------------------------------------------------------------------- int CTFProjectile_Jar::DrawModel( int flags ) { if ( gpGlobals->curtime - m_flCreationTime < 0.1f ) return 0; return BaseClass::DrawModel( flags ); } #endif <|start_filename|>src/game/shared/econ/econ_entity.cpp<|end_filename|> //========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //===========================================================================// #include "cbase.h" #include "econ_entity.h" #include "eventlist.h" #ifdef GAME_DLL #include "tf_player.h" #else #include "c_tf_player.h" #include "model_types.h" #endif // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #ifdef CLIENT_DLL EXTERN_RECV_TABLE( DT_ScriptCreatedItem ) #else EXTERN_SEND_TABLE( DT_ScriptCreatedItem ) #endif IMPLEMENT_NETWORKCLASS_ALIASED( EconEntity, DT_EconEntity ) BEGIN_NETWORK_TABLE( CEconEntity, DT_EconEntity ) #ifdef CLIENT_DLL RecvPropDataTable( RECVINFO_DT( m_Item ), 0, &REFERENCE_RECV_TABLE( DT_ScriptCreatedItem ) ), RecvPropDataTable( RECVINFO_DT( m_AttributeManager ), 0, &REFERENCE_RECV_TABLE( DT_AttributeContainer ) ), #else SendPropDataTable( SENDINFO_DT( m_Item ), &REFERENCE_SEND_TABLE( DT_ScriptCreatedItem ) ), SendPropDataTable( SENDINFO_DT( m_AttributeManager ), &REFERENCE_SEND_TABLE( DT_AttributeContainer ) ), #endif END_NETWORK_TABLE() #ifdef CLIENT_DLL BEGIN_PREDICTION_DATA( C_EconEntity ) DEFINE_PRED_TYPEDESCRIPTION( m_AttributeManager, CAttributeContainer ), END_PREDICTION_DATA() #endif CEconEntity::CEconEntity() { m_pAttributes = this; } #ifdef CLIENT_DLL void CEconEntity::OnPreDataChanged( DataUpdateType_t updateType ) { BaseClass::OnPreDataChanged( updateType ); m_AttributeManager.OnPreDataChanged( updateType ); } void CEconEntity::OnDataChanged( DataUpdateType_t updateType ) { BaseClass::OnDataChanged( updateType ); m_AttributeManager.OnDataChanged( updateType ); } void CEconEntity::FireEvent( const Vector& origin, const QAngle& angles, int event, const char *options ) { if ( event == AE_CL_BODYGROUP_SET_VALUE_CMODEL_WPN ) { C_ViewmodelAttachmentModel *pAttach = GetViewmodelAddon(); if ( pAttach) { pAttach->FireEvent( origin, angles, AE_CL_BODYGROUP_SET_VALUE, options ); } } else BaseClass::FireEvent( origin, angles, event, options ); } bool CEconEntity::OnFireEvent( C_BaseViewModel *pViewModel, const Vector& origin, const QAngle& angles, int event, const char *options ) { if ( event == AE_CL_BODYGROUP_SET_VALUE_CMODEL_WPN ) { C_ViewmodelAttachmentModel *pAttach = GetViewmodelAddon(); if ( pAttach) { pAttach->FireEvent( origin, angles, AE_CL_BODYGROUP_SET_VALUE, options ); return true; } } return false; } bool CEconEntity::OnInternalDrawModel( ClientModelRenderInfo_t *pInfo ) { if ( BaseClass::OnInternalDrawModel( pInfo ) ) { DrawEconEntityAttachedModels( this, this, pInfo, 1 ); return true; } return false; } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CEconEntity::ViewModelAttachmentBlending( CStudioHdr *hdr, Vector pos[], Quaternion q[], float currentTime, int boneMask ) { // NUB } #endif void CEconEntity::SetItem( CEconItemView &newItem ) { m_Item = newItem; } CEconItemView *CEconEntity::GetItem( void ) { return &m_Item; } bool CEconEntity::HasItemDefinition( void ) const { return ( m_Item.GetItemDefIndex() >= 0 ); } //----------------------------------------------------------------------------- // Purpose: Shortcut to get item ID. //----------------------------------------------------------------------------- int CEconEntity::GetItemID( void ) { return m_Item.GetItemDefIndex(); } //----------------------------------------------------------------------------- // Purpose: Derived classes need to override this. //----------------------------------------------------------------------------- void CEconEntity::GiveTo( CBaseEntity *pEntity ) { } //----------------------------------------------------------------------------- // Purpose: Add or remove this from owner's attribute providers list. //----------------------------------------------------------------------------- void CEconEntity::ReapplyProvision( void ) { CBaseEntity *pOwner = GetOwnerEntity(); CBaseEntity *pOldOwner = m_hOldOwner.Get(); if ( pOwner != pOldOwner ) { if ( pOldOwner ) { m_AttributeManager.StopProvidingTo( pOldOwner ); } if ( pOwner ) { m_AttributeManager.ProviteTo( pOwner ); m_hOldOwner = pOwner; } else { m_hOldOwner = NULL; } } } //----------------------------------------------------------------------------- // Purpose: Update visible bodygroups //----------------------------------------------------------------------------- void CEconEntity::UpdatePlayerBodygroups( void ) { CTFPlayer *pPlayer = dynamic_cast < CTFPlayer * >( GetOwnerEntity() ); if ( !pPlayer ) { return; } // bodygroup enabling/disabling CEconItemDefinition *pStatic = m_Item.GetStaticData(); if ( pStatic ) { EconItemVisuals *pVisuals = pStatic->GetVisuals(); if ( pVisuals ) { for ( int i = 0; i < pPlayer->GetNumBodyGroups(); i++ ) { unsigned int index = pVisuals->player_bodygroups.Find( pPlayer->GetBodygroupName( i ) ); if ( pVisuals->player_bodygroups.IsValidIndex( index ) ) { bool bTrue = pVisuals->player_bodygroups.Element( index ); if ( bTrue ) { pPlayer->SetBodygroup( i , 1 ); } else { pPlayer->SetBodygroup( i , 0 ); } } } } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CEconEntity::UpdateOnRemove( void ) { SetOwnerEntity( NULL ); ReapplyProvision(); BaseClass::UpdateOnRemove(); } CEconEntity::~CEconEntity() { } #ifdef CLIENT_DLL void DrawEconEntityAttachedModels( C_BaseAnimating *pAnimating, C_EconEntity *pEconEntity, ClientModelRenderInfo_t const *pInfo, int iModelType ) { /*if ( pAnimating && pEconEntity && pInfo ) { if ( pEconEntity->HasItemDefinition() ) { CEconItemDefinition *pItemDef = pEconEntity->GetItem()->GetStaticData(); if ( pItemDef ) { EconItemVisuals *pVisuals = pItemDef->GetVisuals( pEconEntity->GetTeamNumber() ); if ( pVisuals ) { const char *pszModelName = NULL; for ( int i = 0; i < pVisuals->attached_models.Count(); i++ ) { switch ( iModelType ) { case 1: if ( pVisuals->attached_models[i].world_model == 1 ) { pszModelName = pVisuals->attached_models[i].model; } break; case 2: if ( pVisuals->attached_models[i].view_model == 1 ) { pszModelName = pVisuals->attached_models[i].model; } break; }; } if ( pszModelName != NULL ) { ClientModelRenderInfo_t *pNewInfo = new ClientModelRenderInfo_t( *pInfo ); model_t *model = (model_t *)engine->LoadModel( pszModelName ); pNewInfo->pModel = model; pNewInfo->pModelToWorld = &pNewInfo->modelToWorld; // Turns the origin + angles into a matrix AngleMatrix( pNewInfo->angles, pNewInfo->origin, pNewInfo->modelToWorld ); DrawModelState_t state; matrix3x4_t *pBoneToWorld = NULL; bool bMarkAsDrawn = modelrender->DrawModelSetup( *pNewInfo, &state, NULL, &pBoneToWorld ); pAnimating->DoInternalDrawModel( pNewInfo, ( bMarkAsDrawn && ( pNewInfo->flags & STUDIO_RENDER ) ) ? &state : NULL, pBoneToWorld ); } } } } }*/ } #endif <|start_filename|>src/game/client/tf/vgui/panels/tf_statsummarydialog.cpp<|end_filename|> #include "cbase.h" #include <vgui_controls/Label.h> #include <vgui_controls/Button.h> #include <vgui_controls/ComboBox.h> #include <vgui_controls/ImagePanel.h> #include <vgui_controls/RichText.h> #include <vgui_controls/Frame.h> #include <vgui_controls/QueryBox.h> #include <vgui/IScheme.h> #include <vgui/ILocalize.h> #include <vgui/ISurface.h> #include "ienginevgui.h" #include <game/client/iviewport.h> #include "tf_statsummarydialog.h" #include "tf_mainmenu.h" #include <convar.h> #include "fmtstr.h" using namespace vgui; //----------------------------------------------------------------------------- // Purpose: Constructor //----------------------------------------------------------------------------- CTFStatsSummaryDialog::CTFStatsSummaryDialog(vgui::Panel* parent, const char *panelName) : CTFDialogPanelBase(parent, panelName) { Init(); } bool CTFStatsSummaryDialog::Init() { BaseClass::Init(); m_bControlsLoaded = false; m_xStartLHBar = 0; m_xStartRHBar = 0; m_iBarHeight = 1; m_iBarMaxWidth = 1; m_pPlayerData = new vgui::EditablePanel(this, "statdata"); m_pBarChartComboBoxA = new vgui::ComboBox(m_pPlayerData, "BarChartComboA", 10, false); m_pBarChartComboBoxB = new vgui::ComboBox(m_pPlayerData, "BarChartComboB", 10, false); m_pClassComboBox = new vgui::ComboBox(m_pPlayerData, "ClassCombo", 10, false); m_pBarChartComboBoxA->AddActionSignalTarget(this); m_pBarChartComboBoxB->AddActionSignalTarget(this); m_pClassComboBox->AddActionSignalTarget(this); Reset(); return true; } //----------------------------------------------------------------------------- // Purpose: Applies scheme settings //----------------------------------------------------------------------------- void CTFStatsSummaryDialog::ApplySchemeSettings(vgui::IScheme *pScheme) { BaseClass::ApplySchemeSettings(pScheme); LoadControlSettings("Resource/UI/main_menu/StatsSummaryDialog.res"); m_bControlsLoaded = true; // get the dimensions and position of a left-hand bar and a right-hand bar so we can do bar sizing later Panel *pLHBar = m_pPlayerData->FindChildByName("ClassBar1A"); Panel *pRHBar = m_pPlayerData->FindChildByName("ClassBar1B"); if (pLHBar && pRHBar) { int y; pLHBar->GetBounds(m_xStartLHBar, y, m_iBarMaxWidth, m_iBarHeight); pRHBar->GetBounds(m_xStartRHBar, y, m_iBarMaxWidth, m_iBarHeight); } // fill the combo box selections appropriately InitBarChartComboBox(m_pBarChartComboBoxA); InitBarChartComboBox(m_pBarChartComboBoxB); // fill the class names in the class combo box HFont hFont = scheme()->GetIScheme(GetScheme())->GetFont("ScoreboardSmall", true); m_pClassComboBox->SetFont(hFont); m_pClassComboBox->RemoveAll(); KeyValues *pKeyValues = new KeyValues("data"); pKeyValues->SetInt("class", TF_CLASS_UNDEFINED); m_pClassComboBox->AddItem("#StatSummary_Label_AsAnyClass", pKeyValues); for (int iClass = TF_FIRST_NORMAL_CLASS; iClass <= TF_CLASS_COUNT; iClass++) { pKeyValues = new KeyValues("data"); pKeyValues->SetInt("class", iClass); m_pClassComboBox->AddItem(g_aPlayerClassNames[iClass], pKeyValues); } m_pClassComboBox->ActivateItemByRow(0); SetDefaultSelections(); UpdateDialog(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFStatsSummaryDialog::PerformLayout() { BaseClass::PerformLayout(); } //----------------------------------------------------------------------------- // Purpose: Shows this dialog as a modal dialog //----------------------------------------------------------------------------- void CTFStatsSummaryDialog::Show() { BaseClass::Show(); GetStatPanel()->UpdateMainMenuDialog(); UpdateDialog(); } //----------------------------------------------------------------------------- // Purpose: Command handler //----------------------------------------------------------------------------- void CTFStatsSummaryDialog::OnCommand(const char *command) { if (0 == Q_stricmp(command, "vguicancel")) { UpdateDialog(); Hide(); SetDefaultSelections(); } BaseClass::OnCommand(command); } //----------------------------------------------------------------------------- // Purpose: Resets the dialog //----------------------------------------------------------------------------- void CTFStatsSummaryDialog::Reset() { m_aClassStats.RemoveAll(); SetDefaultSelections(); } //----------------------------------------------------------------------------- // Purpose: Sets all user-controllable dialog settings to default values //----------------------------------------------------------------------------- void CTFStatsSummaryDialog::SetDefaultSelections() { m_iSelectedClass = TF_CLASS_UNDEFINED; m_statBarGraph[0] = TFSTAT_POINTSSCORED; m_displayBarGraph[0] = SHOW_MAX; m_statBarGraph[1] = TFSTAT_PLAYTIME; m_displayBarGraph[1] = SHOW_TOTAL; m_pBarChartComboBoxA->ActivateItemByRow(0); m_pBarChartComboBoxB->ActivateItemByRow(10); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFStatsSummaryDialog::OnKeyCodePressed(KeyCode code) { } //----------------------------------------------------------------------------- // Purpose: Sets stats to use //----------------------------------------------------------------------------- void CTFStatsSummaryDialog::SetStats(CUtlVector<ClassStats_t> &vecClassStats) { m_aClassStats = vecClassStats; if (m_bControlsLoaded) { UpdateDialog(); } } //----------------------------------------------------------------------------- // Purpose: Updates the dialog //----------------------------------------------------------------------------- void CTFStatsSummaryDialog::UpdateDialog() { RandomSeed(Plat_MSTime()); m_iTotalSpawns = 0; // if we don't have stats for any class, add empty stat entries for them for (int iClass = TF_FIRST_NORMAL_CLASS; iClass <= TF_CLASS_COUNT; iClass++) { int j; for (j = 0; j < m_aClassStats.Count(); j++) { if (m_aClassStats[j].iPlayerClass == iClass) { m_iTotalSpawns += m_aClassStats[j].iNumberOfRounds; break; } } if (j == m_aClassStats.Count()) { ClassStats_t stats; stats.iPlayerClass = iClass; m_aClassStats.AddToTail(stats); } } // fill out bar charts UpdateBarCharts(); // fill out class details UpdateClassDetails(); // show or hide controls depending on if we're interactive or not UpdateControls(); } //----------------------------------------------------------------------------- // Purpose: Shows or hides controls //----------------------------------------------------------------------------- void CTFStatsSummaryDialog::UpdateControls() { m_pPlayerData->SetVisible(true); m_pPlayerData->SetVisible(true); } //----------------------------------------------------------------------------- // Purpose: Updates bar charts //----------------------------------------------------------------------------- void CTFStatsSummaryDialog::UpdateBarCharts() { // sort the class stats by the selected stat for right-hand bar chart m_aClassStats.Sort(&CTFStatsSummaryDialog::CompareClassStats); // loop for left & right hand charts for (int iChart = 0; iChart < 2; iChart++) { float flMax = 0; for (int i = 0; i < m_aClassStats.Count(); i++) { // get max value of stat being charted so we know how to scale the graph float flVal = GetDisplayValue(m_aClassStats[i], m_statBarGraph[iChart], m_displayBarGraph[iChart]); flMax = max(flVal, flMax); } // draw the bar chart value for each player class for (int i = 0; i < m_aClassStats.Count(); i++) { if (0 == iChart) { // if this is the first chart, set the class label for each class int iClass = m_aClassStats[i].iPlayerClass; m_pPlayerData->SetDialogVariable(CFmtStr("class%d", i + 1), g_pVGuiLocalize->Find(g_aPlayerClassNames[iClass])); } // draw the bar for this class DisplayBarValue(iChart, i, m_aClassStats[i], m_statBarGraph[iChart], m_displayBarGraph[iChart], flMax); } } } #define MAKEFLAG(x) ( 1 << x ) #define ALL_CLASSES 0xFFFFFFFF //----------------------------------------------------------------------------- // Purpose: Updates class details //----------------------------------------------------------------------------- void CTFStatsSummaryDialog::UpdateClassDetails() { struct ClassDetails_t { TFStatType_t statType; // type of stat int iFlagsClass; // bit mask of classes to show this stat for const char * szResourceName; // name of label resource }; ClassDetails_t classDetails[] = { { TFSTAT_POINTSSCORED, ALL_CLASSES, "#TF_ClassRecord_MostPoints" }, { TFSTAT_KILLS, ALL_CLASSES, "#TF_ClassRecord_MostKills" }, { TFSTAT_KILLASSISTS, ALL_CLASSES, "#TF_ClassRecord_MostAssists" }, { TFSTAT_CAPTURES, ALL_CLASSES, "#TF_ClassRecord_MostCaptures" }, { TFSTAT_DEFENSES, ALL_CLASSES, "#TF_ClassRecord_MostDefenses" }, { TFSTAT_DAMAGE, ALL_CLASSES, "#TF_ClassRecord_MostDamage" }, { TFSTAT_BUILDINGSDESTROYED, ALL_CLASSES, "#TF_ClassRecord_MostDestruction" }, { TFSTAT_DOMINATIONS, ALL_CLASSES, "#TF_ClassRecord_MostDominations" }, { TFSTAT_PLAYTIME, ALL_CLASSES, "#TF_ClassRecord_LongestLife" }, { TFSTAT_HEALING, MAKEFLAG(TF_CLASS_MEDIC) | MAKEFLAG(TF_CLASS_ENGINEER), "#TF_ClassRecord_MostHealing" }, { TFSTAT_INVULNS, MAKEFLAG(TF_CLASS_MEDIC), "#TF_ClassRecord_MostInvulns" }, { TFSTAT_MAXSENTRYKILLS, MAKEFLAG(TF_CLASS_ENGINEER), "#TF_ClassRecord_MostSentryKills" }, { TFSTAT_TELEPORTS, MAKEFLAG(TF_CLASS_ENGINEER), "#TF_ClassRecord_MostTeleports" }, { TFSTAT_HEADSHOTS, MAKEFLAG(TF_CLASS_SNIPER), "#TF_ClassRecord_MostHeadshots" }, { TFSTAT_BACKSTABS, MAKEFLAG(TF_CLASS_SPY), "#TF_ClassRecord_MostBackstabs" }, }; wchar_t *wzWithClassFmt = g_pVGuiLocalize->Find("#StatSummary_ScoreAsClassFmt"); wchar_t *wzWithoutClassFmt = L"%s1"; // display the record for each stat int iRow = 0; for (int i = 0; i < ARRAYSIZE(classDetails); i++) { TFStatType_t statType = classDetails[i].statType; int iClass = TF_CLASS_UNDEFINED; int iMaxVal = 0; // if there is a selected class, and if this stat should not be shown for this class, skip this stat if (m_iSelectedClass != TF_CLASS_UNDEFINED && (0 == (classDetails[i].iFlagsClass & MAKEFLAG(m_iSelectedClass)))) continue; if (m_iSelectedClass == TF_CLASS_UNDEFINED) { // if showing best from any class, look through all player classes to determine the max value of this stat for (int j = 0; j < m_aClassStats.Count(); j++) { if (m_aClassStats[j].max.m_iStat[statType] > iMaxVal) { // remember max value and class that has max value iMaxVal = m_aClassStats[j].max.m_iStat[statType]; iClass = m_aClassStats[j].iPlayerClass; } } } else { // show best from selected class iClass = m_iSelectedClass; for (int j = 0; j < m_aClassStats.Count(); j++) { if (m_aClassStats[j].iPlayerClass == iClass) { iMaxVal = m_aClassStats[j].max.m_iStat[statType]; break; } } } wchar_t wzStatNum[32]; wchar_t wzStatVal[128]; if (TFSTAT_PLAYTIME == statType) { // playtime gets displayed as a time string g_pVGuiLocalize->ConvertANSIToUnicode(FormatSeconds(iMaxVal), wzStatNum, sizeof(wzStatNum)); } else { // all other stats are just shown as a # swprintf_s(wzStatNum, ARRAYSIZE(wzStatNum), L"%d", iMaxVal); } if (TF_CLASS_UNDEFINED == m_iSelectedClass && iMaxVal > 0) { // if we are doing a cross-class view (no single selected class) and the max value is non-zero, show "# (as <class>)" wchar_t *wzLocalizedClassName = g_pVGuiLocalize->Find(g_aPlayerClassNames[iClass]); g_pVGuiLocalize->ConstructString(wzStatVal, sizeof(wzStatVal), wzWithClassFmt, 2, wzStatNum, wzLocalizedClassName); } else { // just show the value g_pVGuiLocalize->ConstructString(wzStatVal, sizeof(wzStatVal), wzWithoutClassFmt, 1, wzStatNum); } // set the label m_pPlayerData->SetDialogVariable(CFmtStr("classrecord%dlabel", iRow + 1), g_pVGuiLocalize->Find(classDetails[i].szResourceName)); // set the value m_pPlayerData->SetDialogVariable(CFmtStr("classrecord%dvalue", iRow + 1), wzStatVal); iRow++; } // if there are any leftover rows for the selected class, fill out the remaining rows with blank labels and values for (; iRow < 15; iRow++) { m_pPlayerData->SetDialogVariable(CFmtStr("classrecord%dlabel", iRow + 1), ""); m_pPlayerData->SetDialogVariable(CFmtStr("classrecord%dvalue", iRow + 1), ""); } } //----------------------------------------------------------------------------- // Purpose: Initializes a bar chart combo box //----------------------------------------------------------------------------- void CTFStatsSummaryDialog::InitBarChartComboBox(ComboBox *pComboBox) { struct BarChartComboInit_t { TFStatType_t statType; StatDisplay_t statDisplay; const char *szName; }; BarChartComboInit_t initData[] = { { TFSTAT_POINTSSCORED, SHOW_MAX, "#StatSummary_StatTitle_MostPoints" }, { TFSTAT_POINTSSCORED, SHOW_AVG, "#StatSummary_StatTitle_AvgPoints" }, { TFSTAT_KILLS, SHOW_MAX, "#StatSummary_StatTitle_MostKills" }, { TFSTAT_KILLS, SHOW_AVG, "#StatSummary_StatTitle_AvgKills" }, { TFSTAT_CAPTURES, SHOW_MAX, "#StatSummary_StatTitle_MostCaptures" }, { TFSTAT_CAPTURES, SHOW_AVG, "#StatSummary_StatTitle_AvgCaptures" }, { TFSTAT_KILLASSISTS, SHOW_MAX, "#StatSummary_StatTitle_MostAssists" }, { TFSTAT_KILLASSISTS, SHOW_AVG, "#StatSummary_StatTitle_AvgAssists" }, { TFSTAT_DAMAGE, SHOW_MAX, "#StatSummary_StatTitle_MostDamage" }, { TFSTAT_DAMAGE, SHOW_AVG, "#StatSummary_StatTitle_AvgDamage" }, { TFSTAT_PLAYTIME, SHOW_TOTAL, "#StatSummary_StatTitle_TotalPlaytime" }, { TFSTAT_PLAYTIME, SHOW_MAX, "#StatSummary_StatTitle_LongestLife" }, }; // set the font HFont hFont = scheme()->GetIScheme(GetScheme())->GetFont("ScoreboardVerySmall", true); pComboBox->SetFont(hFont); pComboBox->RemoveAll(); // add all the options to the combo box for (int i = 0; i < ARRAYSIZE(initData); i++) { KeyValues *pKeyValues = new KeyValues("data"); pKeyValues->SetInt("stattype", initData[i].statType); pKeyValues->SetInt("statdisplay", initData[i].statDisplay); pComboBox->AddItem(g_pVGuiLocalize->Find(initData[i].szName), pKeyValues); } pComboBox->SetNumberOfEditLines(ARRAYSIZE(initData)); } //----------------------------------------------------------------------------- // Purpose: Helper function that sets the specified dialog variable to // "<value> (as <localized class name>)" //----------------------------------------------------------------------------- void CTFStatsSummaryDialog::SetValueAsClass(const char *pDialogVariable, int iValue, int iPlayerClass) { if (iValue > 0) { wchar_t *wzScoreAsClassFmt = g_pVGuiLocalize->Find("#StatSummary_ScoreAsClassFmt"); wchar_t *wzLocalizedClassName = g_pVGuiLocalize->Find(g_aPlayerClassNames[iPlayerClass]); wchar_t wzVal[16]; wchar_t wzMsg[128]; #ifdef _WIN32 // TODO: Find a posix equivelant to _itow_s _itow_s(iValue, wzVal, ARRAYSIZE(wzVal), 10); #endif g_pVGuiLocalize->ConstructString(wzMsg, sizeof(wzMsg), wzScoreAsClassFmt, 2, wzVal, wzLocalizedClassName); m_pPlayerData->SetDialogVariable(pDialogVariable, wzMsg); } else { m_pPlayerData->SetDialogVariable(pDialogVariable, "0"); } } //----------------------------------------------------------------------------- // Purpose: Sets the specified bar chart item to the specified value, in range 0->1 //----------------------------------------------------------------------------- void CTFStatsSummaryDialog::DisplayBarValue(int iChart, int iBar, ClassStats_t &stats, TFStatType_t statType, StatDisplay_t statDisplay, float flMaxValue) { const char *szControlSuffix = (0 == iChart ? "A" : "B"); Panel *pBar = m_pPlayerData->FindChildByName(CFmtStr("ClassBar%d%s", iBar + 1, szControlSuffix)); Label *pLabel = dynamic_cast<Label*>(m_pPlayerData->FindChildByName(CFmtStr("classbarlabel%d%s", iBar + 1, szControlSuffix))); if (!pBar || !pLabel) return; // get the stat value float flValue = GetDisplayValue(stats, statType, statDisplay); // calculate the bar size to draw, in the range of 0.0->1.0 float flBarRange = SafeCalcFraction(flValue, flMaxValue); // calculate the # of pixels of bar width to draw int iBarWidth = max((int)(flBarRange * (float)m_iBarMaxWidth), 1); // Get the text label to draw for this bar. For values of 0, draw nothing, to minimize clutter const char *szLabel = (flValue > 0 ? RenderValue(flValue, statType, statDisplay) : ""); // draw the label outside the bar if there's room bool bLabelOutsideBar = true; const int iLabelSpacing = 4; HFont hFont = pLabel->GetFont(); int iLabelWidth = UTIL_ComputeStringWidth(hFont, szLabel); if (iBarWidth + iLabelWidth + iLabelSpacing > m_iBarMaxWidth) { // if there's not room outside the bar for the label, draw it inside the bar bLabelOutsideBar = false; } int xBar, yBar, xLabel, yLabel; pBar->GetPos(xBar, yBar); pLabel->GetPos(xLabel, yLabel); m_pPlayerData->SetDialogVariable(CFmtStr("classbarlabel%d%s", iBar + 1, szControlSuffix), szLabel); if (1 == iChart) { // drawing code for RH bar chart xBar = m_xStartRHBar; pBar->SetBounds(xBar, yBar, iBarWidth, m_iBarHeight); if (bLabelOutsideBar) { pLabel->SetPos(xBar + iBarWidth + iLabelSpacing, yLabel); } else { pLabel->SetPos(xBar + iBarWidth - (iLabelWidth + iLabelSpacing), yLabel); } } else { // drawing code for LH bar chart xBar = m_xStartLHBar + m_iBarMaxWidth - iBarWidth; pBar->SetBounds(xBar, yBar, iBarWidth, m_iBarHeight); if (bLabelOutsideBar) { pLabel->SetPos(xBar - (iLabelWidth + iLabelSpacing), yLabel); } else { pLabel->SetPos(xBar + iLabelSpacing, yLabel); } } } //----------------------------------------------------------------------------- // Purpose: Calculates a fraction and guards from divide by 0. (Returns 0 if // denominator is 0.) //----------------------------------------------------------------------------- float CTFStatsSummaryDialog::SafeCalcFraction(float flNumerator, float flDemoninator) { if (0 == flDemoninator) return 0; return flNumerator / flDemoninator; } //----------------------------------------------------------------------------- // Purpose: Formats # of seconds into a string //----------------------------------------------------------------------------- char *CTFStatsSummaryDialog::FormatSeconds(int seconds) { static char string[64]; int hours = 0; int minutes = seconds / 60; if (minutes > 0) { seconds -= (minutes * 60); hours = minutes / 60; if (hours > 0) { minutes -= (hours * 60); } } if (hours > 0) { Q_snprintf(string, sizeof(string), "%2i:%02i:%02i", hours, minutes, seconds); } else { Q_snprintf(string, sizeof(string), "%02i:%02i", minutes, seconds); } return string; } //----------------------------------------------------------------------------- // Purpose: Static sort function that sorts in descending order by play time //----------------------------------------------------------------------------- int __cdecl CTFStatsSummaryDialog::CompareClassStats(const ClassStats_t *pStats0, const ClassStats_t *pStats1) { // sort stats first by right-hand bar graph TFStatType_t statTypePrimary = GET_MAINMENUPANEL(CTFStatsSummaryDialog)->m_statBarGraph[1]; StatDisplay_t statDisplayPrimary = GET_MAINMENUPANEL(CTFStatsSummaryDialog)->m_displayBarGraph[1]; // then by left-hand bar graph TFStatType_t statTypeSecondary = GET_MAINMENUPANEL(CTFStatsSummaryDialog)->m_statBarGraph[0]; StatDisplay_t statDisplaySecondary = GET_MAINMENUPANEL(CTFStatsSummaryDialog)->m_displayBarGraph[0]; float flValPrimary0 = GetDisplayValue((ClassStats_t &)*pStats0, statTypePrimary, statDisplayPrimary); float flValPrimary1 = GetDisplayValue((ClassStats_t &)*pStats1, statTypePrimary, statDisplayPrimary); float flValSecondary0 = GetDisplayValue((ClassStats_t &)*pStats0, statTypeSecondary, statDisplaySecondary); float flValSecondary1 = GetDisplayValue((ClassStats_t &)*pStats1, statTypeSecondary, statDisplaySecondary); // sort in descending order by primary stat value if (flValPrimary1 > flValPrimary0) return 1; if (flValPrimary1 < flValPrimary0) return -1; // if primary stat values are equal, sort in descending order by secondary stat value if (flValSecondary1 > flValSecondary0) return 1; if (flValSecondary1 < flValSecondary0) return -1; // if primary & secondary stats are equal, sort by class for consistent sort order return (pStats1->iPlayerClass - pStats0->iPlayerClass); } //----------------------------------------------------------------------------- // Purpose: Called when text changes in combo box //----------------------------------------------------------------------------- void CTFStatsSummaryDialog::OnTextChanged(KeyValues *data) { Panel *pPanel = reinterpret_cast<vgui::Panel *>(data->GetPtr("panel")); vgui::ComboBox *pComboBox = dynamic_cast<vgui::ComboBox *>(pPanel); if (m_pBarChartComboBoxA == pComboBox || m_pBarChartComboBoxB == pComboBox) { // a bar chart combo box changed, update the bar charts KeyValues *pUserDataA = m_pBarChartComboBoxA->GetActiveItemUserData(); KeyValues *pUserDataB = m_pBarChartComboBoxB->GetActiveItemUserData(); if (!pUserDataA || !pUserDataB) return; m_statBarGraph[0] = (TFStatType_t)pUserDataA->GetInt("stattype"); m_displayBarGraph[0] = (StatDisplay_t)pUserDataA->GetInt("statdisplay"); m_statBarGraph[1] = (TFStatType_t)pUserDataB->GetInt("stattype"); m_displayBarGraph[1] = (StatDisplay_t)pUserDataB->GetInt("statdisplay"); UpdateBarCharts(); } else if (m_pClassComboBox == pComboBox) { // the class selection combo box changed, update class details KeyValues *pUserData = m_pClassComboBox->GetActiveItemUserData(); if (!pUserData) return; m_iSelectedClass = pUserData->GetInt("class", TF_CLASS_UNDEFINED); UpdateClassDetails(); } } //----------------------------------------------------------------------------- // Purpose: Returns the stat value for specified display type //----------------------------------------------------------------------------- float CTFStatsSummaryDialog::GetDisplayValue(ClassStats_t &stats, TFStatType_t statType, StatDisplay_t statDisplay) { switch (statDisplay) { case SHOW_MAX: return stats.max.m_iStat[statType]; break; case SHOW_TOTAL: return stats.accumulated.m_iStat[statType]; break; case SHOW_AVG: return SafeCalcFraction(stats.accumulated.m_iStat[statType], stats.iNumberOfRounds); break; default: AssertOnce(false); return 0; } } //----------------------------------------------------------------------------- // Purpose: Gets the text representation of this value //----------------------------------------------------------------------------- const char *CTFStatsSummaryDialog::RenderValue(float flValue, TFStatType_t statType, StatDisplay_t statDisplay) { static char szValue[64]; if (TFSTAT_PLAYTIME == statType) { // the playtime stat is shown in seconds return FormatSeconds((int)flValue); } else if (SHOW_AVG == statDisplay) { // if it's an average, render as a float w/2 decimal places Q_snprintf(szValue, ARRAYSIZE(szValue), "%.2f", flValue); } else { // otherwise, render as an integer Q_snprintf(szValue, ARRAYSIZE(szValue), "%d", (int)flValue); } return szValue; } <|start_filename|>src/game/shared/econ/econ_item_system.h<|end_filename|> #ifndef ECON_ITEM_SYSTEM_H #define ECON_ITEM_SYSTEM_H #ifdef _WIN32 #pragma once #endif #include "econ_item_schema.h" class CEconSchemaParser; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- class CEconItemSchema { friend class CEconSchemaParser; friend class CTFInventory; public: CEconItemSchema(); ~CEconItemSchema(); bool Init( void ); void Precache( void ); CEconItemDefinition* GetItemDefinition( int id ); EconAttributeDefinition *GetAttributeDefinition( int id ); EconAttributeDefinition *GetAttributeDefinitionByName( const char* name ); EconAttributeDefinition *GetAttributeDefinitionByClass( const char* name ); int GetAttributeIndex( const char *classname ); protected: CUtlDict< int, unsigned short > m_GameInfo; CUtlDict< EconQuality, unsigned short > m_Qualities; CUtlDict< EconColor, unsigned short > m_Colors; CUtlDict< KeyValues *, unsigned short > m_PrefabsValues; CUtlMap< int, CEconItemDefinition * > m_Items; CUtlMap< int, EconAttributeDefinition * > m_Attributes; private: bool m_bInited; }; CEconItemSchema *GetItemSchema(); #endif // ECON_ITEM_SYSTEM_H <|start_filename|>src/game/server/tf/tf_obj.cpp<|end_filename|> //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: Base Object built by players // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "tf_player.h" #include "tf_team.h" #include "tf_obj.h" #include "tf_weapon_wrench.h" #include "tf_weaponbase.h" #include "rope.h" #include "rope_shared.h" #include "bone_setup.h" #include "ndebugoverlay.h" #include "rope_helpers.h" #include "IEffects.h" #include "vstdlib/random.h" #include "tier1/strtools.h" #include "basegrenade_shared.h" #include "tf_gamerules.h" #include "engine/IEngineSound.h" #include "tf_shareddefs.h" #include "vguiscreen.h" #include "hierarchy.h" #include "func_no_build.h" #include "func_respawnroom.h" #include <KeyValues.h> #include "ihasbuildpoints.h" #include "utldict.h" #include "filesystem.h" #include "npcevent.h" #include "tf_shareddefs.h" #include "animation.h" #include "effect_dispatch_data.h" #include "te_effect_dispatch.h" #include "tf_gamestats.h" #include "tf_ammo_pack.h" #include "tf_obj_sapper.h" #include "particle_parse.h" #include "tf_fx.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" // Control panels #define SCREEN_OVERLAY_MATERIAL "vgui/screens/vgui_overlay" #define ROPE_HANG_DIST 150 ConVar tf_obj_gib_velocity_min( "tf_obj_gib_velocity_min", "100", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY ); ConVar tf_obj_gib_velocity_max( "tf_obj_gib_velocity_max", "450", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY ); ConVar tf_obj_gib_maxspeed( "tf_obj_gib_maxspeed", "800", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY ); ConVar object_verbose( "object_verbose", "0", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY, "Debug object system." ); ConVar obj_damage_factor( "obj_damage_factor","0", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY, "Factor applied to all damage done to objects" ); ConVar obj_child_damage_factor( "obj_child_damage_factor","0.25", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY, "Factor applied to damage done to objects that are built on a buildpoint" ); ConVar tf_fastbuild("tf_fastbuild", "0", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY ); ConVar tf_obj_ground_clearance( "tf_obj_ground_clearance", "32", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY, "Object corners can be this high above the ground" ); ConVar tf2c_building_upgrades( "tf2c_building_upgrades", "1", FCVAR_REPLICATED, "Toggles the ability to upgrade buildings other than the sentrygun" ); extern short g_sModelIndexFireball; // Minimum distance between 2 objects to ensure player movement between them #define MINIMUM_OBJECT_SAFE_DISTANCE 100 // Maximum number of a type of objects on a single resource zone #define MAX_OBJECTS_PER_ZONE 1 // Time it takes a fully healed object to deteriorate ConVar object_deterioration_time( "object_deterioration_time", "30", 0, "Time it takes for a fully-healed object to deteriorate." ); // Time after taking damage that an object will still drop resources on death #define MAX_DROP_TIME_AFTER_DAMAGE 5 #define OBJ_BASE_THINK_CONTEXT "BaseObjectThink" BEGIN_DATADESC( CBaseObject ) // keys DEFINE_KEYFIELD_NOT_SAVED( m_SolidToPlayers, FIELD_INTEGER, "SolidToPlayer" ), DEFINE_KEYFIELD( m_iDefaultUpgrade, FIELD_INTEGER, "defaultupgrade" ), // Inputs DEFINE_INPUTFUNC( FIELD_INTEGER, "Show", InputShow ), DEFINE_INPUTFUNC( FIELD_INTEGER, "Hide", InputHide ), DEFINE_INPUTFUNC( FIELD_INTEGER, "Enable", InputEnable ), DEFINE_INPUTFUNC( FIELD_INTEGER, "Disable", InputDisable ), DEFINE_INPUTFUNC( FIELD_INTEGER, "SetHealth", InputSetHealth ), DEFINE_INPUTFUNC( FIELD_INTEGER, "AddHealth", InputAddHealth ), DEFINE_INPUTFUNC( FIELD_INTEGER, "RemoveHealth", InputRemoveHealth ), DEFINE_INPUTFUNC( FIELD_INTEGER, "SetSolidToPlayer", InputSetSolidToPlayer ), // Outputs DEFINE_OUTPUT( m_OnDestroyed, "OnDestroyed" ), DEFINE_OUTPUT( m_OnDamaged, "OnDamaged" ), DEFINE_OUTPUT( m_OnRepaired, "OnRepaired" ), DEFINE_OUTPUT( m_OnBecomingDisabled, "OnDisabled" ), DEFINE_OUTPUT( m_OnBecomingReenabled, "OnReenabled" ), DEFINE_OUTPUT( m_OnObjectHealthChanged, "OnObjectHealthChanged" ) END_DATADESC() IMPLEMENT_SERVERCLASS_ST( CBaseObject, DT_BaseObject ) SendPropInt( SENDINFO( m_iHealth ), 13 ), SendPropInt( SENDINFO( m_iMaxHealth ), 13 ), SendPropBool( SENDINFO( m_bHasSapper ) ), SendPropInt( SENDINFO( m_iObjectType ), Q_log2( OBJ_LAST ) + 1, SPROP_UNSIGNED ), SendPropBool( SENDINFO( m_bBuilding ) ), SendPropBool( SENDINFO( m_bPlacing ) ), SendPropBool( SENDINFO( m_bCarried ) ), SendPropBool( SENDINFO( m_bCarryDeploy ) ), SendPropBool( SENDINFO( m_bMiniBuilding ) ), SendPropFloat( SENDINFO( m_flPercentageConstructed ), 8, 0, 0.0, 1.0f ), SendPropInt( SENDINFO( m_fObjectFlags ), OF_BIT_COUNT, SPROP_UNSIGNED ), SendPropEHandle( SENDINFO( m_hBuiltOnEntity ) ), SendPropBool( SENDINFO( m_bDisabled ) ), SendPropEHandle( SENDINFO( m_hBuilder ) ), SendPropVector( SENDINFO( m_vecBuildMaxs ), -1, SPROP_COORD ), SendPropVector( SENDINFO( m_vecBuildMins ), -1, SPROP_COORD ), SendPropInt( SENDINFO( m_iDesiredBuildRotations ), 2, SPROP_UNSIGNED ), SendPropBool( SENDINFO( m_bServerOverridePlacement ) ), SendPropInt( SENDINFO( m_iUpgradeLevel ), 3 ), SendPropInt( SENDINFO( m_iUpgradeMetal ), 10 ), SendPropInt( SENDINFO( m_iUpgradeMetalRequired ), 10 ), SendPropInt( SENDINFO( m_iHighestUpgradeLevel ), 3 ), SendPropInt( SENDINFO( m_iObjectMode ), 2 ), SendPropBool( SENDINFO( m_bDisposableBuilding ) ), SendPropBool( SENDINFO( m_bWasMapPlaced ) ) END_SEND_TABLE(); bool PlayerIndexLessFunc( const int &lhs, const int &rhs ) { return lhs < rhs; } ConVar tf_obj_upgrade_per_hit( "tf_obj_upgrade_per_hit", "25", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY ); extern ConVar tf_cheapobjects; // This controls whether ropes attached to objects are transmitted or not. It's important that // ropes aren't transmitted to guys who don't own them. class CObjectRopeTransmitProxy : public CBaseTransmitProxy { public: CObjectRopeTransmitProxy( CBaseEntity *pRope ) : CBaseTransmitProxy( pRope ) { } virtual int ShouldTransmit( const CCheckTransmitInfo *pInfo, int nPrevShouldTransmitResult ) { // Don't transmit the rope if it's not even visible. if ( !nPrevShouldTransmitResult ) return FL_EDICT_DONTSEND; // This proxy only wants to be active while one of the two objects is being placed. // When they're done being placed, the proxy goes away and the rope draws like normal. bool bAnyObjectPlacing = (m_hObj1 && m_hObj1->IsPlacing()) || (m_hObj2 && m_hObj2->IsPlacing()); if ( !bAnyObjectPlacing ) { Release(); return nPrevShouldTransmitResult; } // Give control to whichever object is being placed. if ( m_hObj1 && m_hObj1->IsPlacing() ) return m_hObj1->ShouldTransmit( pInfo ); else if ( m_hObj2 && m_hObj2->IsPlacing() ) return m_hObj2->ShouldTransmit( pInfo ); else return FL_EDICT_ALWAYS; } CHandle<CBaseObject> m_hObj1; CHandle<CBaseObject> m_hObj2; }; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CBaseObject::CBaseObject() { m_iHealth = m_iMaxHealth = m_flHealth = m_iGoalHealth = 0; m_flPercentageConstructed = 0; m_bPlacing = false; m_bBuilding = false; m_bCarried = false; m_bCarryDeploy = false; m_Activity = ACT_INVALID; m_bDisabled = false; m_SolidToPlayers = SOLID_TO_PLAYER_USE_DEFAULT; m_bPlacementOK = false; m_aGibs.Purge(); m_iObjectMode = 0; m_iDefaultUpgrade = 0; m_bMiniBuilding = false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseObject::UpdateOnRemove( void ) { m_bDying = true; /* // Remove anything left on me IHasBuildPoints *pBPInterface = dynamic_cast<IHasBuildPoints*>(this); if ( pBPInterface && pBPInterface->GetNumObjectsOnMe() ) { pBPInterface->RemoveAllObjects(); } */ DestroyObject(); if ( GetTeam() ) { ((CTFTeam*)GetTeam())->RemoveObject( this ); } DetachObjectFromObject(); // Make sure the object isn't in either team's list of objects... //Assert( !GetGlobalTFTeam(1)->IsObjectOnTeam( this ) ); //Assert( !GetGlobalTFTeam(2)->IsObjectOnTeam( this ) ); // Chain at end to mimic destructor unwind order BaseClass::UpdateOnRemove(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CBaseObject::UpdateTransmitState() { return SetTransmitState( FL_EDICT_FULLCHECK ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CBaseObject::ShouldTransmit( const CCheckTransmitInfo *pInfo ) { // Always transmit to owner if ( GetBuilder() && pInfo->m_pClientEnt == GetBuilder()->edict() ) return FL_EDICT_ALWAYS; // Placement models only transmit to owners if ( IsPlacing() ) return FL_EDICT_DONTSEND; return BaseClass::ShouldTransmit( pInfo ); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- bool CBaseObject::CanBeUpgraded( CTFPlayer *pPlayer ) { // only engineers if ( !ClassCanBuild( pPlayer->GetPlayerClass()->GetClassIndex(), GetType() ) ) { return false; } // max upgraded if ( GetUpgradeLevel() >= GetMaxUpgradeLevel() ) { return false; } if ( IsPlacing() ) { return false; } if ( IsBuilding() ) { return false; } if ( IsUpgrading() ) { return false; } if ( IsRedeploying() ) { return false; } if ( IsMiniBuilding() ) { return false; } if ( !tf2c_building_upgrades.GetBool() && GetType() != OBJ_SENTRYGUN ) return false; return true; } void CBaseObject::SetTransmit( CCheckTransmitInfo *pInfo, bool bAlways ) { // Are we already marked for transmission? if ( pInfo->m_pTransmitEdict->Get( entindex() ) ) return; BaseClass::SetTransmit( pInfo, bAlways ); // Force our screens to be sent too. int nTeam = CBaseEntity::Instance( pInfo->m_pClientEnt )->GetTeamNumber(); for ( int i=0; i < m_hScreens.Count(); i++ ) { CVGuiScreen *pScreen = m_hScreens[i].Get(); if ( pScreen && pScreen->IsVisibleToTeam( nTeam ) ) pScreen->SetTransmit( pInfo, bAlways ); } } void CBaseObject::DoWrenchHitEffect( Vector vecHitPos, bool bRepair, bool bUpgrade ) { CPVSFilter filter( vecHitPos ); if ( bRepair ) { TE_TFParticleEffect( filter, 0.0f, "nutsnbolts_repair", vecHitPos, QAngle( 0, 0, 0 ) ); } else if ( bUpgrade ) { TE_TFParticleEffect( filter, 0.0f, "nutsnbolts_upgrade", vecHitPos, QAngle( 0, 0, 0 ) ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseObject::Precache() { PrecacheMaterial( SCREEN_OVERLAY_MATERIAL ); PrecacheScriptSound( GetObjectInfo( ObjectType() )->m_pExplodeSound ); const char *pEffect = GetObjectInfo( ObjectType() )->m_pExplosionParticleEffect; if ( pEffect && pEffect[0] != '\0' ) { PrecacheParticleSystem( pEffect ); } PrecacheParticleSystem( "nutsnbolts_build" ); PrecacheParticleSystem( "nutsnbolts_upgrade" ); PrecacheParticleSystem( "nutsnbolts_repair" ); CBaseEntity::PrecacheModel( "models/weapons/w_models/w_toolbox.mdl" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseObject::Spawn( void ) { Precache(); CollisionProp()->SetSurroundingBoundsType( USE_BEST_COLLISION_BOUNDS ); SetSolidToPlayers( m_SolidToPlayers, true ); m_bHasSapper = false; m_takedamage = DAMAGE_YES; m_flHealth = m_iMaxHealth = m_iHealth; m_iKills = 0; m_iUpgradeLevel = 1; m_iGoalUpgradeLevel = 1; m_iUpgradeMetal = 0; m_iUpgradeMetalRequired = GetObjectInfo( ObjectType() )->m_UpgradeCost; m_iHighestUpgradeLevel = GetMaxUpgradeLevel(); //m_iHighestUpgradeLevel = GetObjectInfo(ObjectType())->m_MaxUpgradeLevel; SetContextThink( &CBaseObject::BaseObjectThink, gpGlobals->curtime + 0.1, OBJ_BASE_THINK_CONTEXT ); AddFlag( FL_OBJECT ); // So NPCs will notice it SetViewOffset( WorldSpaceCenter() - GetAbsOrigin() ); if ( !VPhysicsGetObject() ) { VPhysicsInitStatic(); } m_RepairerList.SetLessFunc( PlayerIndexLessFunc ); m_iDesiredBuildRotations = 0; m_flCurrentBuildRotation = 0; if ( MustBeBuiltOnAttachmentPoint() ) { AddEffects( EF_NODRAW ); } // assume valid placement m_bServerOverridePlacement = true; } //----------------------------------------------------------------------------- // Purpose: Gunslinger's Buildings //----------------------------------------------------------------------------- void CBaseObject::MakeMiniBuilding( void ) { m_bMiniBuilding = true; // Set the skin switch ( GetTeamNumber() ) { case TF_TEAM_RED: m_nSkin = 2; break; case TF_TEAM_BLUE: m_nSkin = 3; break; default: m_nSkin = 2; break; } // Make the model small SetModelScale( 0.75f ); } void CBaseObject::MakeCarriedObject( CTFPlayer *pPlayer ) { if ( pPlayer ) { m_bCarried = true; m_bCarryDeploy = false; DestroyScreens(); //FollowEntity( pPlayer, true ); // Save health amount building had before getting picked up. It will only heal back up to it. m_iGoalHealth = GetHealth(); // Save current upgrade level and reset it. Building will automatically upgrade back once re-deployed. m_iGoalUpgradeLevel = GetUpgradeLevel(); m_iUpgradeLevel = 1; // Reset placement rotation. m_iDesiredBuildRotations = 0; SetModel( GetPlacementModel() ); pPlayer->m_Shared.SetCarriedObject( this ); //AddEffects( EF_NODRAW ); // StartPlacement already does this but better safe than sorry. AddSolidFlags( FSOLID_NOT_SOLID ); IGameEvent * event = gameeventmanager->CreateEvent( "player_carryobject" ); if ( event ) { event->SetInt( "userid", pPlayer->GetUserID() ); event->SetInt( "object", ObjectType() ); event->SetInt( "index", entindex() ); // object entity index gameeventmanager->FireEvent( event, true ); // don't send to clients } } } void CBaseObject::DropCarriedObject( CTFPlayer *pPlayer ) { m_bCarried = false; m_bCarryDeploy = true; if ( pPlayer ) { pPlayer->m_Shared.SetCarriedObject( NULL ); } //StopFollowingEntity(); } //----------------------------------------------------------------------------- // Returns information about the various control panels //----------------------------------------------------------------------------- void CBaseObject::GetControlPanelInfo( int nPanelIndex, const char *&pPanelName ) { pPanelName = NULL; } //----------------------------------------------------------------------------- // Returns information about the various control panels //----------------------------------------------------------------------------- void CBaseObject::GetControlPanelClassName( int nPanelIndex, const char *&pPanelName ) { pPanelName = "vgui_screen"; } //----------------------------------------------------------------------------- // This is called by the base object when it's time to spawn the control panels //----------------------------------------------------------------------------- void CBaseObject::SpawnControlPanels() { char buf[64]; // FIXME: Deal with dynamically resizing control panels? // If we're attached to an entity, spawn control panels on it instead of use CBaseAnimating *pEntityToSpawnOn = this; char *pOrgLL = "controlpanel%d_ll"; char *pOrgUR = "controlpanel%d_ur"; char *pAttachmentNameLL = pOrgLL; char *pAttachmentNameUR = pOrgUR; if ( IsBuiltOnAttachment() ) { pEntityToSpawnOn = dynamic_cast<CBaseAnimating*>((CBaseEntity*)m_hBuiltOnEntity.Get()); if ( pEntityToSpawnOn ) { char sBuildPointLL[64]; char sBuildPointUR[64]; Q_snprintf( sBuildPointLL, sizeof( sBuildPointLL ), "bp%d_controlpanel%%d_ll", m_iBuiltOnPoint ); Q_snprintf( sBuildPointUR, sizeof( sBuildPointUR ), "bp%d_controlpanel%%d_ur", m_iBuiltOnPoint ); pAttachmentNameLL = sBuildPointLL; pAttachmentNameUR = sBuildPointUR; } else { pEntityToSpawnOn = this; } } Assert( pEntityToSpawnOn ); // Lookup the attachment point... int nPanel; for ( nPanel = 0; true; ++nPanel ) { Q_snprintf( buf, sizeof( buf ), pAttachmentNameLL, nPanel ); int nLLAttachmentIndex = pEntityToSpawnOn->LookupAttachment(buf); if (nLLAttachmentIndex <= 0) { // Try and use my panels then pEntityToSpawnOn = this; Q_snprintf( buf, sizeof( buf ), pOrgLL, nPanel ); nLLAttachmentIndex = pEntityToSpawnOn->LookupAttachment(buf); if (nLLAttachmentIndex <= 0) return; } Q_snprintf( buf, sizeof( buf ), pAttachmentNameUR, nPanel ); int nURAttachmentIndex = pEntityToSpawnOn->LookupAttachment(buf); if (nURAttachmentIndex <= 0) { // Try and use my panels then Q_snprintf( buf, sizeof( buf ), pOrgUR, nPanel ); nURAttachmentIndex = pEntityToSpawnOn->LookupAttachment(buf); if (nURAttachmentIndex <= 0) return; } const char *pScreenName = NULL; GetControlPanelInfo( nPanel, pScreenName ); if (!pScreenName) continue; const char *pScreenClassname; GetControlPanelClassName( nPanel, pScreenClassname ); if ( !pScreenClassname ) continue; // Compute the screen size from the attachment points... matrix3x4_t panelToWorld; pEntityToSpawnOn->GetAttachment( nLLAttachmentIndex, panelToWorld ); matrix3x4_t worldToPanel; MatrixInvert( panelToWorld, worldToPanel ); // Now get the lower right position + transform into panel space Vector lr, lrlocal; pEntityToSpawnOn->GetAttachment( nURAttachmentIndex, panelToWorld ); MatrixGetColumn( panelToWorld, 3, lr ); VectorTransform( lr, worldToPanel, lrlocal ); float flWidth = lrlocal.x; float flHeight = lrlocal.y; CVGuiScreen *pScreen = CreateVGuiScreen( pScreenClassname, pScreenName, pEntityToSpawnOn, this, nLLAttachmentIndex ); pScreen->ChangeTeam( GetTeamNumber() ); pScreen->SetActualSize( flWidth, flHeight ); pScreen->SetActive( false ); pScreen->MakeVisibleOnlyToTeammates( true ); pScreen->SetOverlayMaterial( SCREEN_OVERLAY_MATERIAL ); pScreen->SetTransparency( true ); // for now, only input by the owning player pScreen->SetPlayerOwner( GetBuilder(), true ); int nScreen = m_hScreens.AddToTail( ); m_hScreens[nScreen].Set( pScreen ); } } //----------------------------------------------------------------------------- // Purpose: Called in case was not built by a player but placed by a mapper. //----------------------------------------------------------------------------- void CBaseObject::InitializeMapPlacedObject( void ) { m_bWasMapPlaced = true; if ( ( GetObjectFlags() & OF_IS_CART_OBJECT ) == 0 ) SpawnControlPanels(); // Spawn with full health. SetHealth( GetMaxHealth() ); // Go active. FinishedBuilding(); // Add it to team. CTFTeam *pTFTeam = GetGlobalTFTeam( GetTeamNumber() ); if ( pTFTeam && !pTFTeam->IsObjectOnTeam( this ) ) { pTFTeam->AddObject( this ); } // Set the skin switch ( GetTeamNumber() ) { case TF_TEAM_RED: m_nSkin = 0; break; case TF_TEAM_BLUE: m_nSkin = 1; break; default: m_nSkin = 1; break; } } //----------------------------------------------------------------------------- // Handle commands sent from vgui panels on the client //----------------------------------------------------------------------------- bool CBaseObject::ClientCommand( CTFPlayer *pSender, const CCommand &args ) { //const char *pCmd = args[0]; return false; } #define BASE_OBJECT_THINK_DELAY 0.1 //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseObject::BaseObjectThink( void ) { SetNextThink( gpGlobals->curtime + BASE_OBJECT_THINK_DELAY, OBJ_BASE_THINK_CONTEXT ); // Make sure animation is up to date DetermineAnimation(); DeterminePlaybackRate(); // Do nothing while we're being placed if ( IsPlacing() ) { if ( MustBeBuiltOnAttachmentPoint() ) { UpdateAttachmentPlacement(); m_bServerOverridePlacement = true; } else { m_bServerOverridePlacement = EstimateValidBuildPos(); UpdateDesiredBuildRotation( BASE_OBJECT_THINK_DELAY ); } return; } // If we're building, keep going if ( IsBuilding() ) { BuildingThink(); return; } else if ( IsUpgrading() ) { UpgradeThink(); return; } if ( m_bCarryDeploy ) { if ( m_iUpgradeLevel < m_iGoalUpgradeLevel ) { // Keep upgrading until we hit our previous upgrade level. StartUpgrading(); } else { // Finished. m_bCarryDeploy = false; } if ( IsMiniBuilding() ) { MakeMiniBuilding(); return; } } } bool CBaseObject::UpdateAttachmentPlacement( CBaseObject *pObject /*= NULL*/ ) { // See if we should snap to a build position // finding one implies it is a valid position if ( FindSnapToBuildPos( pObject ) ) { m_bPlacementOK = true; Teleport( &m_vecBuildOrigin, &GetLocalAngles(), NULL ); } else { m_bPlacementOK = false; // Clear out previous parent if ( m_hBuiltOnEntity.Get() ) { m_hBuiltOnEntity = NULL; m_iBuiltOnPoint = 0; SetParent( NULL ); } // teleport to builder's origin CTFPlayer *pPlayer = GetOwner(); if ( pPlayer ) { Teleport( &pPlayer->WorldSpaceCenter(), &GetLocalAngles(), NULL ); } } return m_bPlacementOK; } //----------------------------------------------------------------------------- // Purpose: Cheap check to see if we are in any server-defined No-build areas. //----------------------------------------------------------------------------- bool CBaseObject::EstimateValidBuildPos( void ) { CTFPlayer *pPlayer = GetOwner(); if ( !pPlayer ) return false; // Calculate build angles Vector forward; QAngle vecAngles = vec3_angle; vecAngles.y = pPlayer->EyeAngles().y; QAngle objAngles = vecAngles; //SetAbsAngles( objAngles ); //SetLocalAngles( objAngles ); AngleVectors(vecAngles, &forward ); // Adjust build distance based upon object size Vector2D vecObjectRadius; vecObjectRadius.x = max( fabs( m_vecBuildMins.m_Value.x ), fabs( m_vecBuildMaxs.m_Value.x ) ); vecObjectRadius.y = max( fabs( m_vecBuildMins.m_Value.y ), fabs( m_vecBuildMaxs.m_Value.y ) ); Vector2D vecPlayerRadius; Vector vecPlayerMins = pPlayer->WorldAlignMins(); Vector vecPlayerMaxs = pPlayer->WorldAlignMaxs(); vecPlayerRadius.x = max( fabs( vecPlayerMins.x ), fabs( vecPlayerMaxs.x ) ); vecPlayerRadius.y = max( fabs( vecPlayerMins.y ), fabs( vecPlayerMaxs.y ) ); float flDistance = vecObjectRadius.Length() + vecPlayerRadius.Length() + 4; // small safety buffer Vector vecBuildOrigin = pPlayer->WorldSpaceCenter() + forward * flDistance; //NDebugOverlay::Cross3D( vecBuildOrigin, 10, 255, 0, 0, false, 0.1 ); // Cannot build inside a nobuild brush if ( PointInNoBuild( vecBuildOrigin, this ) ) return false; if ( PointInRespawnRoom( NULL, vecBuildOrigin ) ) return false; Vector vecBuildFarEdge = vecBuildOrigin + forward * ( flDistance + 8.0f ); if ( TestAgainstRespawnRoomVisualizer( pPlayer, vecBuildFarEdge ) ) return false; return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CBaseObject::TestAgainstRespawnRoomVisualizer( CTFPlayer *pPlayer, const Vector &vecEnd ) { // Setup the ray. Ray_t ray; ray.Init( pPlayer->WorldSpaceCenter(), vecEnd ); CBaseEntity *pEntity = NULL; while ( ( pEntity = gEntList.FindEntityByClassnameWithin( pEntity, "func_respawnroomvisualizer", pPlayer->WorldSpaceCenter(), ray.m_Delta.Length() ) ) != NULL ) { trace_t trace; enginetrace->ClipRayToEntity( ray, MASK_ALL, pEntity, &trace ); if ( trace.fraction < 1.0f ) return true; } return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseObject::DeterminePlaybackRate( void ) { if ( IsBuilding() ) { // Default half rate, author build anim as if one player is building SetPlaybackRate( GetConstructionMultiplier() * 0.5 ); } else { SetPlaybackRate( 1.0 ); } StudioFrameAdvance(); } #define OBJ_UPGRADE_DURATION 1.5f //----------------------------------------------------------------------------- // Raises the Sentrygun one level //----------------------------------------------------------------------------- void CBaseObject::StartUpgrading(void) { // Increase level m_iUpgradeLevel++; // more health if ( !IsRedeploying() ) { int iMaxHealth = GetMaxHealth(); SetMaxHealth( iMaxHealth * 1.2 ); SetHealth( iMaxHealth * 1.2 ); } // No ear raping for map placed buildings. if ( !m_iDefaultUpgrade ) { EmitSound( GetObjectInfo( ObjectType() )->m_pUpgradeSound ); } m_flUpgradeCompleteTime = gpGlobals->curtime + GetObjectInfo( ObjectType() )->m_flUpgradeDuration; } void CBaseObject::FinishUpgrading( void ) { // No ear raping for map placed buildings. if ( !m_iDefaultUpgrade ) { EmitSound( GetObjectInfo( ObjectType() )->m_pUpgradeSound ); } } //----------------------------------------------------------------------------- // Playing the upgrade animation //----------------------------------------------------------------------------- void CBaseObject::UpgradeThink(void) { if ( gpGlobals->curtime > m_flUpgradeCompleteTime ) { FinishUpgrading(); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CTFPlayer *CBaseObject::GetOwner() { return m_hBuilder; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseObject::Activate( void ) { BaseClass::Activate(); if ( GetBuilder() == NULL ) InitializeMapPlacedObject(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseObject::SetBuilder( CTFPlayer *pBuilder ) { TRACE_OBJECT( UTIL_VarArgs( "%0.2f CBaseObject::SetBuilder builder %s\n", gpGlobals->curtime, pBuilder ? pBuilder->GetPlayerName() : "NULL" ) ); m_hBuilder = pBuilder; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CBaseObject::ObjectType( ) const { return m_iObjectType; } //----------------------------------------------------------------------------- // Purpose: Destroys the object, gives a chance to spawn an explosion //----------------------------------------------------------------------------- void CBaseObject::DetonateObject( void ) { CTakeDamageInfo info( this, this, vec3_origin, GetAbsOrigin(), 0, DMG_GENERIC ); Killed( info ); } //----------------------------------------------------------------------------- // Purpose: Remove this object from it's team and mark for deletion //----------------------------------------------------------------------------- void CBaseObject::DestroyObject( void ) { TRACE_OBJECT( UTIL_VarArgs( "%0.2f CBaseObject::DestroyObject %p:%s\n", gpGlobals->curtime, this, GetClassname() ) ); if ( m_bCarried ) { DropCarriedObject( GetBuilder() ); } if ( GetBuilder() ) { GetBuilder()->OwnedObjectDestroyed( this ); } UTIL_Remove( this ); DestroyScreens(); } //----------------------------------------------------------------------------- // Purpose: Remove any screens that are active on this object //----------------------------------------------------------------------------- void CBaseObject::DestroyScreens( void ) { // Kill the control panels int i; for ( i = m_hScreens.Count(); --i >= 0; ) { DestroyVGuiScreen( m_hScreens[i].Get() ); } m_hScreens.RemoveAll(); } //----------------------------------------------------------------------------- // Purpose: Get the total time it will take to build this object //----------------------------------------------------------------------------- float CBaseObject::GetTotalTime( void ) { float flBuildTime = GetObjectInfo( ObjectType() )->m_flBuildTime; if ( tf_fastbuild.GetInt() ) return ( min( 2.f, flBuildTime ) ); return flBuildTime; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CBaseObject::GetMaxHealthForCurrentLevel( void ) { return GetBaseHealth() * pow( 1.2, GetUpgradeLevel() - 1 ); } //----------------------------------------------------------------------------- // Purpose: Start placing the object //----------------------------------------------------------------------------- void CBaseObject::StartPlacement( CTFPlayer *pPlayer ) { AddSolidFlags( FSOLID_NOT_SOLID ); m_bPlacing = true; m_bBuilding = false; if ( pPlayer ) { SetBuilder( pPlayer ); ChangeTeam( pPlayer->GetTeamNumber() ); } // needed? m_nRenderMode = kRenderNormal; // Set my build size CollisionProp()->WorldSpaceAABB( &m_vecBuildMins.GetForModify(), &m_vecBuildMaxs.GetForModify() ); m_vecBuildMins -= Vector( 4,4,0 ); m_vecBuildMaxs += Vector( 4,4,0 ); m_vecBuildMins -= GetAbsOrigin(); m_vecBuildMaxs -= GetAbsOrigin(); // Set the skin switch ( GetTeamNumber() ) { case TF_TEAM_RED: m_nSkin = 0; break; case TF_TEAM_BLUE: m_nSkin = 1; break; default: m_nSkin = 1; break; } if ( IsMiniBuilding() ) { MakeMiniBuilding(); } } //----------------------------------------------------------------------------- // Purpose: Stop placing the object //----------------------------------------------------------------------------- void CBaseObject::StopPlacement( void ) { UTIL_Remove( this ); } //----------------------------------------------------------------------------- // Purpose: Find the nearest buildpoint on the specified entity //----------------------------------------------------------------------------- bool CBaseObject::FindNearestBuildPoint( CBaseEntity *pEntity, CBasePlayer *pBuilder, float &flNearestPoint, Vector &vecNearestBuildPoint, bool bIgnoreLOS /*= false*/ ) { bool bFoundPoint = false; IHasBuildPoints *pBPInterface = dynamic_cast<IHasBuildPoints*>(pEntity); Assert( pBPInterface ); // Any empty buildpoints? for ( int i = 0; i < pBPInterface->GetNumBuildPoints(); i++ ) { // Can this object build on this point? if ( pBPInterface->CanBuildObjectOnBuildPoint( i, GetType() ) ) { // Close to this point? Vector vecBPOrigin; QAngle vecBPAngles; if ( pBPInterface->GetBuildPoint(i, vecBPOrigin, vecBPAngles) ) { // If set to ignore LOS, distance, etc, just pick the first point available. if ( !bIgnoreLOS ) { // ignore build points outside our view if ( !pBuilder->FInViewCone( vecBPOrigin ) ) continue; // Do a trace to make sure we don't place attachments through things (players, world, etc...) Vector vecStart = pBuilder->EyePosition(); trace_t trace; UTIL_TraceLine( vecStart, vecBPOrigin, MASK_SOLID, pBuilder, COLLISION_GROUP_NONE, &trace ); if ( trace.m_pEnt != pEntity && trace.fraction != 1.0 ) continue; } float flDist = (vecBPOrigin - pBuilder->GetAbsOrigin()).Length(); // if this is closer, or is the first one in our view, check it out if ( bIgnoreLOS || flDist < min(flNearestPoint, pBPInterface->GetMaxSnapDistance( i )) ) { flNearestPoint = flDist; vecNearestBuildPoint = vecBPOrigin; m_hBuiltOnEntity = pEntity; m_iBuiltOnPoint = i; // Set our angles to the buildpoint's angles SetAbsAngles( vecBPAngles ); bFoundPoint = true; if ( bIgnoreLOS ) break; } } } } return bFoundPoint; } /* class CTraceFilterIgnorePlayers : public CTraceFilterSimple { public: // It does have a base, but we'll never network anything below here.. DECLARE_CLASS( CTraceFilterIgnorePlayers, CTraceFilterSimple ); CTraceFilterIgnorePlayers( const IHandleEntity *passentity, int collisionGroup ) : CTraceFilterSimple( passentity, collisionGroup ) { } virtual bool ShouldHitEntity( IHandleEntity *pServerEntity, int contentsMask ) { CBaseEntity *pEntity = EntityFromEntityHandle( pServerEntity ); if ( pEntity->IsPlayer() ) { return false; } return true; } }; //----------------------------------------------------------------------------- // Purpose: Test around this build position to make sure it does not block a path //----------------------------------------------------------------------------- bool CBaseObject::TestPositionForPlayerBlock( Vector vecBuildOrigin, CBasePlayer *pPlayer ) { // find out the status of the 8 regions around this position int i; bool bNodeVisited[8]; bool bNodeClear[8]; // The first zone that is clear of obstructions int iFirstClear = -1; Vector vHalfPlayerDims = (VEC_HULL_MAX - VEC_HULL_MIN) * 0.5f; Vector vBuildDims = m_vecBuildMaxs - m_vecBuildMins; Vector vHalfBuildDims = vBuildDims * 0.5; // the locations of the 8 test positions // boxes are adjacent to the object box and are at least as large as // a player to ensure that a player can pass this location // 0 1 2 // 7 X 3 // 6 5 4 static int iPositions[8][2] = { { -1, -1 }, { 0, -1 }, { 1, -1 }, { 1, 0 }, { 1, 1 }, { 0, 1 }, { -1, 1 }, { -1, 0 } }; CTraceFilterIgnorePlayers traceFilter( this, COLLISION_GROUP_NONE ); for ( i=0;i<8;i++ ) { // mark them all as unvisited bNodeVisited[i] = false; Vector vecTest = vecBuildOrigin; vecTest.x += ( iPositions[i][0] * ( vHalfBuildDims.x + vHalfPlayerDims.x ) ); vecTest.y += ( iPositions[i][1] * ( vHalfBuildDims.y + vHalfPlayerDims.y ) ); trace_t trace; UTIL_TraceHull( vecTest, vecTest, VEC_HULL_MIN, VEC_HULL_MAX, MASK_SOLID_BRUSHONLY, &traceFilter, &trace ); bNodeClear[i] = ( trace.fraction == 1 && trace.allsolid != 1 && (trace.startsolid != 1) ); // NDebugOverlay::Box( vecTest, VEC_HULL_MIN, VEC_HULL_MAX, bNodeClear[i] ? 0 : 255, bNodeClear[i] ? 255 : 0, 0, 20, 0.1 ); // Store off the first clear location if ( iFirstClear < 0 && bNodeClear[i] ) { iFirstClear = i; } } if ( iFirstClear < 0 ) { // no clear space return false; } // visit all nodes that are adjacent RecursiveTestBuildSpace( iFirstClear, bNodeClear, bNodeVisited ); // if we still have unvisited nodes, return false // unvisited nodes means that one or more nodes was unreachable from our start position // ie, two places the player might want to traverse but would not be able to if we built here for ( i=0;i<8;i++ ) { if ( bNodeVisited[i] == false && bNodeClear[i] == true ) { return false; } } return true; } //----------------------------------------------------------------------------- // Purpose: Test around the build position, one quadrant at a time //----------------------------------------------------------------------------- void CBaseObject::RecursiveTestBuildSpace( int iNode, bool *bNodeClear, bool *bNodeVisited ) { // if the node is visited already if ( bNodeVisited[iNode] == true ) return; // if the test node is blocked if ( bNodeClear[iNode] == false ) return; bNodeVisited[iNode] = true; int iLeftNode = iNode - 1; if ( iLeftNode < 0 ) iLeftNode = 7; RecursiveTestBuildSpace( iLeftNode, bNodeClear, bNodeVisited ); int iRightNode = ( iNode + 1 ) % 8; RecursiveTestBuildSpace( iRightNode, bNodeClear, bNodeVisited ); } */ //----------------------------------------------------------------------------- // Purpose: Move the placement model to the current position. Return false if it's an invalid position //----------------------------------------------------------------------------- bool CBaseObject::UpdatePlacement( void ) { if ( MustBeBuiltOnAttachmentPoint() ) { return UpdateAttachmentPlacement(); } // Finds bsp-valid place for building to be built // Checks for validity, nearby to other entities, in line of sight m_bPlacementOK = IsPlacementPosValid(); Teleport( &m_vecBuildOrigin, &GetLocalAngles(), NULL ); return m_bPlacementOK; } //----------------------------------------------------------------------------- // Purpose: See if we should be snapping to a build position //----------------------------------------------------------------------------- bool CBaseObject::FindSnapToBuildPos( CBaseObject *pObject /*= NULL*/ ) { if ( !MustBeBuiltOnAttachmentPoint() ) return false; CTFPlayer *pPlayer = GetOwner(); if ( !pPlayer ) { return false; } bool bSnappedToPoint = false; bool bShouldAttachToParent = false; Vector vecNearestBuildPoint = vec3_origin; // See if there are any nearby build positions to snap to float flNearestPoint = 9999; int i; bool bHostileAttachment = IsHostileUpgrade(); int iMyTeam = GetTeamNumber(); // If we have an object specified then use that, don't search. if ( pObject ) { if ( !pObject->IsPlacing() ) { if ( FindNearestBuildPoint( pObject, pPlayer, flNearestPoint, vecNearestBuildPoint, true ) ) { bSnappedToPoint = true; bShouldAttachToParent = true; } } } else { int nTeamCount = TFTeamMgr()->GetTeamCount(); for ( int iTeam = FIRST_GAME_TEAM; iTeam < nTeamCount; ++iTeam ) { // Hostile attachments look for enemy objects only if ( bHostileAttachment ) { if ( iTeam == iMyTeam ) { continue; } } // Friendly attachments look for friendly objects only else if ( iTeam != iMyTeam ) { continue; } CTFTeam *pTeam = (CTFTeam *)GetGlobalTeam( iTeam ); if ( !pTeam ) continue; // look for nearby buildpoints on other objects for ( i = 0; i < pTeam->GetNumObjects(); i++ ) { CBaseObject *pTempObject = pTeam->GetObject( i ); Assert( pTempObject ); if ( pTempObject && !pTempObject->IsPlacing() ) { if ( FindNearestBuildPoint( pTempObject, pPlayer, flNearestPoint, vecNearestBuildPoint ) ) { bSnappedToPoint = true; bShouldAttachToParent = true; } } } } } if ( !bSnappedToPoint ) { AddEffects( EF_NODRAW ); } else { RemoveEffects( EF_NODRAW ); if ( bShouldAttachToParent ) { AttachObjectToObject( m_hBuiltOnEntity.Get(), m_iBuiltOnPoint, vecNearestBuildPoint ); } m_vecBuildOrigin = vecNearestBuildPoint; } return bSnappedToPoint; } //----------------------------------------------------------------------------- // Purpose: Are we currently in a buildable position //----------------------------------------------------------------------------- bool CBaseObject::IsValidPlacement( void ) const { return m_bPlacementOK; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- const char *CBaseObject::GetResponseRulesModifier( void ) { switch ( GetType() ) { case OBJ_DISPENSER: return "objtype:dispenser"; break; case OBJ_TELEPORTER: return "objtype:teleporter"; break; case OBJ_SENTRYGUN: return "objtype:sentrygun"; break; case OBJ_ATTACHMENT_SAPPER: return "objtype:sapper"; break; default: break; } return NULL; } //----------------------------------------------------------------------------- // Purpose: Start building the object //----------------------------------------------------------------------------- bool CBaseObject::StartBuilding( CBaseEntity *pBuilder ) { /* // find any tf_ammo_boxes that we are colliding with and destroy them ? // enable if we need to do this CBaseEntity *pList[8]; Vector vecMins = m_vecBuildOrigin + m_vecBuildMins; Vector vecMaxs = m_vecBuildOrigin + m_vecBuildMaxs; int count = UTIL_EntitiesInBox( pList, ARRAYSIZE(pList), vecMins, vecMaxs, 0 ); for ( int i = 0; i < count; i++ ) { if ( pList[i] == this ) continue; // if its a tf_ammo_box, remove it CTFAmmoPack *pAmmo = dynamic_cast< CTFAmmoPack * >( pList[i] ); if ( pAmmo ) { UTIL_Remove( pAmmo ); } } */ // Need to add the object to the team now... CTFTeam *pTFTeam = ( CTFTeam * )GetGlobalTeam( GetTeamNumber() ); // Deduct the cost from the player if ( pBuilder && pBuilder->IsPlayer() ) { CTFPlayer *pTFBuilder = ToTFPlayer( pBuilder ); if ( IsRedeploying() ) { pTFBuilder->SpeakConceptIfAllowed( MP_CONCEPT_REDEPLOY_BUILDING, GetResponseRulesModifier() ); } else { /* if ( ((CTFPlayer*)pBuilder)->IsPlayerClass( TF_CLASS_ENGINEER ) ) { ((CTFPlayer*)pBuilder)->HintMessage( HINT_ENGINEER_USE_WRENCH_ONOWN ); } */ int iAmountPlayerPaidForMe = pTFBuilder->StartedBuildingObject( m_iObjectType ); if ( !iAmountPlayerPaidForMe ) { // Player couldn't afford to pay for me, so abort ClientPrint( pTFBuilder, HUD_PRINTCENTER, "Not enough resources.\n" ); StopPlacement(); return false; } pTFBuilder->SpeakConceptIfAllowed( MP_CONCEPT_BUILDING_OBJECT, GetResponseRulesModifier() ); } } // Add this object to the team's list (because we couldn't add it during // placement mode) if ( pTFTeam && !pTFTeam->IsObjectOnTeam( this ) ) { pTFTeam->AddObject( this ); } m_bPlacing = false; m_bBuilding = true; if ( !IsRedeploying() ) { SetHealth( OBJECT_CONSTRUCTION_STARTINGHEALTH ); } m_flPercentageConstructed = 0; m_nRenderMode = kRenderNormal; RemoveSolidFlags( FSOLID_NOT_SOLID ); // NOTE: We must spawn the control panels now, instead of during // Spawn, because until placement is started, we don't actually know // the position of the control panel because we don't know what it's // been attached to (could be a vehicle which supplies a different // place for the control panel) // NOTE: We must also spawn it before FinishedBuilding can be called SpawnControlPanels(); // Tell the object we've been built on that we exist if ( IsBuiltOnAttachment() ) { IHasBuildPoints *pBPInterface = dynamic_cast<IHasBuildPoints*>((CBaseEntity*)m_hBuiltOnEntity.Get()); Assert( pBPInterface ); pBPInterface->SetObjectOnBuildPoint( m_iBuiltOnPoint, this ); } // Start the build animations m_flTotalConstructionTime = m_flConstructionTimeLeft = GetTotalTime(); if ( !IsRedeploying() && pBuilder && pBuilder->IsPlayer() ) { CTFPlayer *pTFBuilder = ToTFPlayer( pBuilder ); pTFBuilder->FinishedObject( this ); IGameEvent * event = gameeventmanager->CreateEvent( "player_builtobject" ); if ( event ) { event->SetInt( "userid", pTFBuilder->GetUserID() ); event->SetInt( "object", ObjectType() ); event->SetInt( "index", entindex() ); // object entity index gameeventmanager->FireEvent( event, true ); // don't send to clients } } m_vecBuildOrigin = GetAbsOrigin(); int contents = UTIL_PointContents( m_vecBuildOrigin ); if ( contents & MASK_WATER ) { SetWaterLevel( 3 ); } // instantly play the build anim DetermineAnimation(); return true; } //----------------------------------------------------------------------------- // Purpose: Continue construction of this object //----------------------------------------------------------------------------- void CBaseObject::BuildingThink( void ) { // Continue construction Repair( (GetMaxHealth() - OBJECT_CONSTRUCTION_STARTINGHEALTH) / m_flTotalConstructionTime * OBJECT_CONSTRUCTION_INTERVAL ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseObject::SetControlPanelsActive( bool bState ) { // Activate control panel screens for ( int i = m_hScreens.Count(); --i >= 0; ) { if (m_hScreens[i].Get()) { m_hScreens[i]->SetActive( bState ); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseObject::FinishedBuilding( void ) { SetControlPanelsActive( true ); // Only make a shadow if the object doesn't use vphysics if (!VPhysicsGetObject()) { VPhysicsInitStatic(); } m_bBuilding = false; AttemptToGoActive(); // We're done building, add in the stat... ////TFStats()->IncrementStat( (TFStatId_t)(TF_STAT_FIRST_OBJECT_BUILT + ObjectType()), 1 ); // Spawn any objects on this one SpawnObjectPoints(); } //----------------------------------------------------------------------------- // Purpose: Objects store health in hacky ways //----------------------------------------------------------------------------- void CBaseObject::SetHealth( float flHealth ) { bool changed = m_flHealth != flHealth; m_flHealth = flHealth; m_iHealth = ceil(m_flHealth); /* // If we a pose parameter, set the pose parameter to reflect our health if ( LookupPoseParameter( "object_health") >= 0 && GetMaxHealth() > 0 ) { SetPoseParameter( "object_health", 100 * ( GetHealth() / (float)GetMaxHealth() ) ); } */ if ( changed ) { // Set value and fire output m_OnObjectHealthChanged.Set( m_flHealth, this, this ); } } //----------------------------------------------------------------------------- // Purpose: Override base traceattack to prevent visible effects from team members shooting me //----------------------------------------------------------------------------- void CBaseObject::TraceAttack( const CTakeDamageInfo &inputInfo, const Vector &vecDir, trace_t *ptr ) { // Prevent team damage here so blood doesn't appear if ( inputInfo.GetAttacker() ) { if ( InSameTeam(inputInfo.GetAttacker()) ) { // Pass Damage to enemy attachments int iNumObjects = GetNumObjectsOnMe(); for ( int iPoint=iNumObjects-1;iPoint >= 0; --iPoint ) { CBaseObject *pObject = GetBuildPointObject( iPoint ); if ( pObject && pObject->IsHostileUpgrade() ) { pObject->TraceAttack(inputInfo, vecDir, ptr ); } } return; } } SpawnBlood( ptr->endpos, vecDir, BloodColor(), inputInfo.GetDamage() ); AddMultiDamage( inputInfo, this ); } //----------------------------------------------------------------------------- // Purpose: Prevent Team Damage //----------------------------------------------------------------------------- ConVar object_show_damage( "obj_show_damage", "0", 0, "Show all damage taken by objects." ); ConVar object_capture_damage( "obj_capture_damage", "0", 0, "Captures all damage taken by objects for dumping later." ); CUtlDict<int,int> g_DamageMap; void Cmd_DamageDump_f(void) { CUtlDict<bool,int> g_UniqueColumns; int idx; // Build the unique columns: for( idx = g_DamageMap.First(); idx != g_DamageMap.InvalidIndex(); idx = g_DamageMap.Next(idx) ) { char* szColumnName = strchr(g_DamageMap.GetElementName(idx),',') + 1; int ColumnIdx = g_UniqueColumns.Find( szColumnName ); if( ColumnIdx == g_UniqueColumns.InvalidIndex() ) { g_UniqueColumns.Insert( szColumnName, false ); } } // Dump the column names: FileHandle_t f = filesystem->Open("damage.txt","wt+"); for( idx = g_UniqueColumns.First(); idx != g_UniqueColumns.InvalidIndex(); idx = g_UniqueColumns.Next(idx) ) { filesystem->FPrintf(f,"\t%s",g_UniqueColumns.GetElementName(idx)); } filesystem->FPrintf(f,"\n"); CUtlDict<bool,int> g_CompletedRows; // Dump each row: bool bDidRow; do { bDidRow = false; for( idx = g_DamageMap.First(); idx != g_DamageMap.InvalidIndex(); idx = g_DamageMap.Next(idx) ) { char szRowName[256]; // Check the Row name of each entry to see if I've done this row yet. Q_strncpy(szRowName, g_DamageMap.GetElementName(idx), sizeof( szRowName ) ); *strchr(szRowName,',') = '\0'; char szRowNameComma[256]; Q_snprintf( szRowNameComma, sizeof( szRowNameComma ), "%s,", szRowName ); if( g_CompletedRows.Find(szRowName) == g_CompletedRows.InvalidIndex() ) { bDidRow = true; g_CompletedRows.Insert(szRowName,false); // Output the row name: filesystem->FPrintf(f,szRowName); for( int ColumnIdx = g_UniqueColumns.First(); ColumnIdx != g_UniqueColumns.InvalidIndex(); ColumnIdx = g_UniqueColumns.Next( ColumnIdx ) ) { char szRowNameCommaColumn[256]; Q_strncpy( szRowNameCommaColumn, szRowNameComma, sizeof( szRowNameCommaColumn ) ); Q_strncat( szRowNameCommaColumn, g_UniqueColumns.GetElementName( ColumnIdx ), sizeof( szRowNameCommaColumn ), COPY_ALL_CHARACTERS ); int nDamageAmount = 0; // Fine to reuse idx since we are going to break anyways. for( idx = g_DamageMap.First(); idx != g_DamageMap.InvalidIndex(); idx = g_DamageMap.Next(idx) ) { if( !stricmp( g_DamageMap.GetElementName(idx), szRowNameCommaColumn ) ) { nDamageAmount = g_DamageMap[idx]; break; } } filesystem->FPrintf(f,"\t%i",nDamageAmount); } filesystem->FPrintf(f,"\n"); break; } } // Grab the row name: } while(bDidRow); // close the file: filesystem->Close(f); } static ConCommand obj_dump_damage( "obj_dump_damage", Cmd_DamageDump_f ); //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void ReportDamage( const char* szInflictor, const char* szVictim, float fAmount, int nCurrent, int nMax ) { int iAmount = (int)fAmount; if( object_show_damage.GetBool() && iAmount ) { Msg( "ShowDamage: Object %s taking %0.1f damage from %s ( %i / %i )\n", szVictim, fAmount, szInflictor, nCurrent, nMax ); } if( object_capture_damage.GetBool() ) { char szMangledKey[256]; Q_snprintf(szMangledKey,sizeof(szMangledKey)/sizeof(szMangledKey[0]),"%s,%s",szInflictor,szVictim); int idx = g_DamageMap.Find( szMangledKey ); if( idx == g_DamageMap.InvalidIndex() ) { g_DamageMap.Insert( szMangledKey, iAmount ); } else { g_DamageMap[idx] += iAmount; } } } //----------------------------------------------------------------------------- // Purpose: Return the first non-hostile object build on this object //----------------------------------------------------------------------------- CBaseEntity *CBaseObject::GetFirstFriendlyObjectOnMe( void ) { CBaseObject *pFirstObject = NULL; IHasBuildPoints *pBPInterface = dynamic_cast<IHasBuildPoints*>(this); int iNumObjects = pBPInterface->GetNumObjectsOnMe(); for ( int iPoint=0;iPoint<iNumObjects;iPoint++ ) { CBaseObject *pObject = GetBuildPointObject( iPoint ); if ( pObject && !pObject->IsHostileUpgrade() ) { pFirstObject = pObject; break; } } return pFirstObject; } //----------------------------------------------------------------------------- // Purpose: Pass the specified amount of damage through to any objects I have built on me //----------------------------------------------------------------------------- bool CBaseObject::PassDamageOntoChildren( const CTakeDamageInfo &info, float *flDamageLeftOver ) { float flDamage = info.GetDamage(); // Double the amount of damage done (and get around the child damage modifier) flDamage *= 2; if ( obj_child_damage_factor.GetFloat() ) { flDamage *= (1 / obj_child_damage_factor.GetFloat()); } // Remove blast damage because child objects (well specifically upgrades) // want to ignore direct blast damage but still take damage from parent CTakeDamageInfo childInfo = info; childInfo.SetDamage( flDamage ); childInfo.SetDamageType( info.GetDamageType() & (~DMG_BLAST) ); CBaseEntity *pEntity = GetFirstFriendlyObjectOnMe(); while ( pEntity ) { Assert( pEntity->m_takedamage != DAMAGE_NO ); // Do damage to the next object float flDamageTaken = pEntity->OnTakeDamage( childInfo ); // If we didn't kill it, abort CBaseObject *pObject = dynamic_cast<CBaseObject*>(pEntity); if ( !pObject || !pObject->IsDying() ) { char* szInflictor = "unknown"; if( info.GetInflictor() ) szInflictor = (char*)info.GetInflictor()->GetClassname(); ReportDamage( szInflictor, GetClassname(), flDamageTaken, GetHealth(), GetMaxHealth() ); *flDamageLeftOver = flDamage; return true; } // Reduce the damage and move on to the next flDamage -= flDamageTaken; pEntity = GetFirstFriendlyObjectOnMe(); } *flDamageLeftOver = flDamage; return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CBaseObject::OnTakeDamage( const CTakeDamageInfo &info ) { if ( !IsAlive() ) return info.GetDamage(); if ( m_takedamage == DAMAGE_NO ) return 0; if ( HasSpawnFlags( SF_OBJ_INVULNERABLE ) ) return 0; if ( IsPlacing() ) return 0; // Check teams if ( info.GetAttacker() ) { if ( InSameTeam(info.GetAttacker()) ) return 0; } IHasBuildPoints *pBPInterface = dynamic_cast<IHasBuildPoints*>(this); float flDamage = info.GetDamage(); // Objects build on other objects take less damage if ( !IsAnUpgrade() && GetParentObject() ) { flDamage *= obj_child_damage_factor.GetFloat(); } if (obj_damage_factor.GetFloat()) { flDamage *= obj_damage_factor.GetFloat(); } bool bFriendlyObjectsAttached = false; int iNumObjects = pBPInterface->GetNumObjectsOnMe(); for ( int iPoint=0;iPoint<iNumObjects;iPoint++ ) { CBaseObject *pObject = GetBuildPointObject( iPoint ); if ( !pObject || pObject->IsHostileUpgrade() ) { continue; } bFriendlyObjectsAttached = true; break; } // If I have objects on me, I can't be destroyed until they're gone. Ditto if I can't be killed. bool bWillDieButCant = ( bFriendlyObjectsAttached ) && (( m_flHealth - flDamage ) < 1); if ( bWillDieButCant ) { // Soak up the damage it would take to drop us to 1 health flDamage = flDamage - m_flHealth; SetHealth( 1 ); // Pass leftover damage if ( flDamage ) { if ( PassDamageOntoChildren( info, &flDamage ) ) return flDamage; } } int iOldHealth = m_iHealth; if ( flDamage ) { // Recheck our death possibility, because our objects may have all been blown off us by now bWillDieButCant = ( bFriendlyObjectsAttached ) && (( m_flHealth - flDamage ) < 1); if ( !bWillDieButCant ) { // Reduce health SetHealth( m_flHealth - flDamage ); } } IGameEvent *event = gameeventmanager->CreateEvent( "npc_hurt" ); if ( event ) { CTFPlayer *pTFAttacker = ToTFPlayer( info.GetAttacker() ); CTFWeaponBase *pTFWeapon = dynamic_cast<CTFWeaponBase *>( info.GetWeapon() ); event->SetInt( "entindex", entindex() ); event->SetInt( "attacker_player", pTFAttacker ? pTFAttacker->GetUserID() : 0 ); event->SetInt( "weaponid", pTFWeapon ? pTFWeapon->GetWeaponID() : TF_WEAPON_NONE ); event->SetInt( "damageamount", iOldHealth - m_iHealth ); event->SetInt( "health", max( 0, m_iHealth ) ); event->SetBool( "crit", false ); event->SetBool( "boss", false ); gameeventmanager->FireEvent( event ); } m_OnDamaged.FireOutput(info.GetAttacker(), this); if ( GetHealth() <= 0 ) { if ( info.GetAttacker() ) { //TFStats()->IncrementTeamStat( info.GetAttacker()->GetTeamNumber(), TF_TEAM_STAT_DESTROYED_OBJECT_COUNT, 1 ); //TFStats()->IncrementPlayerStat( info.GetAttacker(), TF_PLAYER_STAT_DESTROYED_OBJECT_COUNT, 1 ); } m_lifeState = LIFE_DEAD; m_OnDestroyed.FireOutput( info.GetAttacker(), this); Killed( info ); // Tell our builder to speak about it if ( m_hBuilder ) { m_hBuilder->SpeakConceptIfAllowed( MP_CONCEPT_LOST_OBJECT, GetResponseRulesModifier() ); } } char* szInflictor = "unknown"; if( info.GetInflictor() ) szInflictor = (char*)info.GetInflictor()->GetClassname(); ReportDamage( szInflictor, GetClassname(), flDamage, GetHealth(), GetMaxHealth() ); return flDamage; } //----------------------------------------------------------------------------- // Purpose: Repair / Help-Construct this object the specified amount //----------------------------------------------------------------------------- bool CBaseObject::Repair( float flHealth ) { // Multiply it by the repair rate flHealth *= GetConstructionMultiplier(); if ( !flHealth ) return false; if ( IsBuilding() ) { // Reduce the construction time by the correct amount for the health passed in float flConstructionTime = flHealth / ((GetMaxHealth() - OBJECT_CONSTRUCTION_STARTINGHEALTH) / m_flTotalConstructionTime); m_flConstructionTimeLeft = max( 0, m_flConstructionTimeLeft - flConstructionTime); m_flConstructionTimeLeft = clamp( m_flConstructionTimeLeft, 0.0f, m_flTotalConstructionTime ); m_flPercentageConstructed = 1 - (m_flConstructionTimeLeft / m_flTotalConstructionTime); m_flPercentageConstructed = clamp( m_flPercentageConstructed, 0.0f, 1.0f ); // Increase health. // Only regenerate up to previous health while re-deploying. int iMaxHealth = IsRedeploying() ? m_iGoalHealth : GetMaxHealth(); SetHealth( min( iMaxHealth, m_flHealth + flHealth ) ); // Return true if we're constructed now if ( m_flConstructionTimeLeft <= 0.0f ) { FinishedBuilding(); return true; } } else { // Return true if we're already fully healed if ( GetHealth() >= GetMaxHealth() ) return true; // Increase health. SetHealth( min( GetMaxHealth(), m_flHealth + flHealth ) ); m_OnRepaired.FireOutput( this, this); // Return true if we're fully healed now if ( GetHealth() == GetMaxHealth() ) return true; } return false; } void CBaseObject::OnConstructionHit( CTFPlayer *pPlayer, CTFWrench *pWrench, Vector vecHitPos ) { // Get the player index int iPlayerIndex = pPlayer->entindex(); // The time the repair is going to expire float flRepairExpireTime = gpGlobals->curtime + 1.0; // Update or Add the expire time to the list int index = m_RepairerList.Find( iPlayerIndex ); if ( index == m_RepairerList.InvalidIndex() ) { m_RepairerList.Insert( iPlayerIndex, flRepairExpireTime ); } else { m_RepairerList[index] = flRepairExpireTime; } CPVSFilter filter( vecHitPos ); TE_TFParticleEffect( filter, 0.0f, "nutsnbolts_build", vecHitPos, QAngle( 0,0,0 ) ); } float CBaseObject::GetConstructionMultiplier( void ) { float flMultiplier = 1.0f; // Minis deploy faster. if ( IsMiniBuilding() ) flMultiplier *= 1.7f; // Re-deploy twice as fast. if ( IsRedeploying() ) flMultiplier *= 2.0f; // expire all the old int i = m_RepairerList.LastInorder(); while ( i != m_RepairerList.InvalidIndex() ) { int iThis = i; i = m_RepairerList.PrevInorder( i ); if ( m_RepairerList[iThis] < gpGlobals->curtime ) { m_RepairerList.RemoveAt( iThis ); } else { // Each player hitting it builds twice as fast flMultiplier *= 2.0; // Check if this weapon has a build modifier CALL_ATTRIB_HOOK_FLOAT_ON_OTHER( UTIL_PlayerByIndex( m_RepairerList.Key( iThis ) ), flMultiplier, mult_construction_value ); } } return flMultiplier; } //----------------------------------------------------------------------------- // Purpose: Object is exploding because it was killed or detonate //----------------------------------------------------------------------------- void CBaseObject::Explode( void ) { const char *pExplodeSound = GetObjectInfo( ObjectType() )->m_pExplodeSound; if ( pExplodeSound && Q_strlen(pExplodeSound) > 0 ) { EmitSound( pExplodeSound ); } const char *pExplodeEffect = GetObjectInfo( ObjectType() )->m_pExplosionParticleEffect; if ( pExplodeEffect && pExplodeEffect[0] != '\0' ) { // Send to everyone - we're inside prediction for the engy who hit this off, but we // don't predict that the hit will kill this object. CDisablePredictionFiltering disabler; Vector origin = GetAbsOrigin(); QAngle up(-90,0,0); CPVSFilter filter( origin ); TE_TFParticleEffect( filter, 0.0f, pExplodeEffect, origin, up ); } // create some delicious, metal filled gibs CreateObjectGibs(); } void CBaseObject::CreateObjectGibs( void ) { if ( m_aGibs.Count() <= 0 ) { return; } const CObjectInfo *pObjectInfo = GetObjectInfo( ObjectType() ); int nMetalPerGib = pObjectInfo->m_iMetalToDropInGibs / m_aGibs.Count(); int i; for ( i=0; i<m_aGibs.Count(); i++ ) { const char *szGibModel = m_aGibs[i].modelName; CTFAmmoPack *pAmmoPack = CTFAmmoPack::Create( GetAbsOrigin(), GetAbsAngles(), this, szGibModel ); Assert( pAmmoPack ); if ( pAmmoPack ) { pAmmoPack->ActivateWhenAtRest(); // Fill up the ammo pack. // Mini gibs don't give any ammo if ( !IsMiniBuilding() ) pAmmoPack->GiveAmmo( nMetalPerGib, TF_AMMO_METAL ); // Calculate the initial impulse on the weapon. Vector vecImpulse( random->RandomFloat( -0.5, 0.5 ), random->RandomFloat( -0.5, 0.5 ), random->RandomFloat( 0.75, 1.25 ) ); VectorNormalize( vecImpulse ); vecImpulse *= random->RandomFloat( tf_obj_gib_velocity_min.GetFloat(), tf_obj_gib_velocity_max.GetFloat() ); QAngle angImpulse( random->RandomFloat ( -100, -500 ), 0, 0 ); // Cap the impulse. float flSpeed = vecImpulse.Length(); if ( flSpeed > tf_obj_gib_maxspeed.GetFloat() ) { VectorScale( vecImpulse, tf_obj_gib_maxspeed.GetFloat() / flSpeed, vecImpulse ); } if ( pAmmoPack->VPhysicsGetObject() ) { // We can probably remove this when the mass on the weapons is correct! //pAmmoPack->VPhysicsGetObject()->SetMass( 25.0f ); AngularImpulse angImpulse( 0, random->RandomFloat( 0, 100 ), 0 ); pAmmoPack->VPhysicsGetObject()->SetVelocityInstantaneous( &vecImpulse, &angImpulse ); } pAmmoPack->SetInitialVelocity( vecImpulse ); switch (GetTeamNumber()) { case TF_TEAM_RED: pAmmoPack->m_nSkin = 0; break; case TF_TEAM_BLUE: pAmmoPack->m_nSkin = 1; break; default: pAmmoPack->m_nSkin = 1; break; } // Give the ammo pack some health, so that trains can destroy it. pAmmoPack->SetCollisionGroup( COLLISION_GROUP_DEBRIS ); pAmmoPack->m_takedamage = DAMAGE_YES; pAmmoPack->SetHealth( 900 ); if ( IsMiniBuilding() ) { pAmmoPack->SetModelScale( 0.6f ); } } } } //----------------------------------------------------------------------------- // Purpose: Object has been blown up. Drop resource chunks upto the value of my max health. //----------------------------------------------------------------------------- void CBaseObject::Killed( const CTakeDamageInfo &info ) { m_bDying = true; // Find the killer & the scorer CBaseEntity *pInflictor = info.GetInflictor(); CBaseEntity *pKiller = info.GetAttacker(); CTFPlayer *pScorer = ToTFPlayer( TFGameRules()->GetDeathScorer( pKiller, pInflictor, this ) ); CTFPlayer *pAssister = NULL; // if this object has a sapper on it, and was not killed by the sapper (killed by damage other than crush, since sapper does crushing damage), // award an assist to the owner of the sapper since it probably contributed to destroying this object if ( HasSapper() && !( DMG_CRUSH & info.GetDamageType() ) ) { CObjectSapper *pSapper = dynamic_cast<CObjectSapper *>( FirstMoveChild() ); if ( pSapper ) { // give an assist to the sapper's owner pAssister = pSapper->GetOwner(); CTF_GameStats.Event_AssistDestroyBuilding( pAssister, this ); } } // Don't do anything if we were detonated or dismantled if ( pScorer && pInflictor != this ) { IGameEvent * event = gameeventmanager->CreateEvent( "object_destroyed" ); int iWeaponID = TF_WEAPON_NONE; // Work out what killed the player, and send a message to all clients about it const char *killer_weapon_name = TFGameRules()->GetKillingWeaponName( info, NULL, iWeaponID ); const char *killer_weapon_log_name = NULL; if ( iWeaponID && pScorer ) { CTFWeaponBase *pWeapon = pScorer->Weapon_OwnsThisID( iWeaponID ); if ( pWeapon ) { CEconItemDefinition *pItemDef = pWeapon->GetItem()->GetStaticData(); if ( pItemDef ) { if ( pItemDef->item_iconname[0] ) killer_weapon_name = pItemDef->item_iconname; if ( pItemDef->item_logname[0] ) killer_weapon_log_name = pItemDef->item_logname; } } } CTFPlayer *pTFPlayer = GetOwner(); if ( event ) { if ( pTFPlayer ) { event->SetInt( "userid", pTFPlayer->GetUserID() ); } if ( pAssister && ( pAssister != pScorer ) ) { event->SetInt( "assister", pAssister->GetUserID() ); } event->SetInt( "attacker", pScorer->GetUserID() ); // attacker event->SetString( "weapon", killer_weapon_name ); event->SetString( "weapon_logclassname", killer_weapon_log_name ); event->SetInt( "priority", 6 ); // HLTV event priority, not transmitted event->SetInt( "objecttype", GetType() ); event->SetInt( "index", entindex() ); // object entity index gameeventmanager->FireEvent( event ); } CTFPlayer *pPlayerScorer = ToTFPlayer( pScorer ); if ( pPlayerScorer ) { CTF_GameStats.Event_PlayerDestroyedBuilding( pPlayerScorer, this ); pPlayerScorer->Event_KilledOther(this, info); } } // Do an explosion. Explode(); UTIL_Remove( this ); } //----------------------------------------------------------------------------- // Purpose: Indicates this NPC's place in the relationship table. //----------------------------------------------------------------------------- Class_T CBaseObject::Classify( void ) { return CLASS_NONE; } //----------------------------------------------------------------------------- // Purpose: Get the type of this object //----------------------------------------------------------------------------- int CBaseObject::GetType() { return m_iObjectType; } //----------------------------------------------------------------------------- // Purpose: Get the builder of this object //----------------------------------------------------------------------------- CTFPlayer *CBaseObject::GetBuilder( void ) { return m_hBuilder; } //----------------------------------------------------------------------------- // Purpose: Return true if the Owning CTeam should clean this object up automatically //----------------------------------------------------------------------------- bool CBaseObject::ShouldAutoRemove( void ) { return true; } //----------------------------------------------------------------------------- // Purpose: // Input : iTeamNum - //----------------------------------------------------------------------------- void CBaseObject::ChangeTeam( int iTeamNum ) { CTFTeam *pTeam = ( CTFTeam * )GetGlobalTeam( iTeamNum ); CTFTeam *pExisting = ( CTFTeam * )GetTeam(); TRACE_OBJECT( UTIL_VarArgs( "%0.2f CBaseObject::ChangeTeam old %s new %s\n", gpGlobals->curtime, pExisting ? pExisting->GetName() : "NULL", pTeam ? pTeam->GetName() : "NULL" ) ); // Already on this team if ( GetTeamNumber() == iTeamNum ) return; if ( pExisting ) { // Remove it from current team ( if it's in one ) and give it to new team pExisting->RemoveObject( this ); } // Change to new team BaseClass::ChangeTeam( iTeamNum ); // Add this object to the team's list // But only if we're not placing it if ( pTeam && (!m_bPlacing) ) { pTeam->AddObject( this ); } // Setup for our new team's model CreateBuildPoints(); } //----------------------------------------------------------------------------- // Purpose: Return true if I have at least 1 sapper on me //----------------------------------------------------------------------------- bool CBaseObject::HasSapper( void ) { return m_bHasSapper; } void CBaseObject::OnAddSapper( void ) { // Assume we can only build 1 sapper per object Assert( m_bHasSapper == false ); m_bHasSapper = true; CTFPlayer *pPlayer = GetBuilder(); if ( pPlayer ) { //pPlayer->HintMessage( HINT_OBJECT_YOUR_OBJECT_SAPPED, true ); pPlayer->SpeakConceptIfAllowed( MP_CONCEPT_SPY_SAPPER, GetResponseRulesModifier() ); } UpdateDisabledState(); } void CBaseObject::OnRemoveSapper( void ) { m_bHasSapper = false; UpdateDisabledState(); } bool CBaseObject::ShowVGUIScreen( int panelIndex, bool bShow ) { Assert( panelIndex >= 0 && panelIndex < m_hScreens.Count() ); if ( m_hScreens[panelIndex].Get() ) { m_hScreens[panelIndex]->SetActive( bShow ); return true; } else { return false; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseObject::InputShow( inputdata_t &inputdata ) { RemoveFlag( EF_NODRAW ); SetDisabled( false ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseObject::InputHide( inputdata_t &inputdata ) { AddFlag( EF_NODRAW ); SetDisabled( true ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseObject::InputEnable( inputdata_t &inputdata ) { SetDisabled( false ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseObject::InputDisable( inputdata_t &inputdata ) { AddFlag( EF_NODRAW ); SetDisabled( true ); } //----------------------------------------------------------------------------- // Purpose: Set the health of the object //----------------------------------------------------------------------------- void CBaseObject::InputSetHealth( inputdata_t &inputdata ) { m_iMaxHealth = inputdata.value.Int(); SetHealth( m_iMaxHealth ); } //----------------------------------------------------------------------------- // Purpose: Add health to the object //----------------------------------------------------------------------------- void CBaseObject::InputAddHealth( inputdata_t &inputdata ) { int iHealth = inputdata.value.Int(); SetHealth( min( GetMaxHealth(), m_flHealth + iHealth ) ); } //----------------------------------------------------------------------------- // Purpose: Remove health from the object //----------------------------------------------------------------------------- void CBaseObject::InputRemoveHealth( inputdata_t &inputdata ) { int iDamage = inputdata.value.Int(); SetHealth( m_flHealth - iDamage ); if ( GetHealth() <= 0 ) { m_lifeState = LIFE_DEAD; m_OnDestroyed.FireOutput(this, this); CTakeDamageInfo info( inputdata.pCaller, inputdata.pActivator, vec3_origin, GetAbsOrigin(), iDamage, DMG_GENERIC ); Killed( info ); } } //----------------------------------------------------------------------------- // Purpose: // Input : &inputdata - //----------------------------------------------------------------------------- void CBaseObject::InputSetSolidToPlayer( inputdata_t &inputdata ) { int ival = inputdata.value.Int(); ival = clamp( ival, (int)SOLID_TO_PLAYER_USE_DEFAULT, (int)SOLID_TO_PLAYER_NO ); OBJSOLIDTYPE stp = (OBJSOLIDTYPE)ival; SetSolidToPlayers( stp ); } //----------------------------------------------------------------------------- // Purpose: // Input : // Output : did this wrench hit do any work on the object? //----------------------------------------------------------------------------- bool CBaseObject::InputWrenchHit( CTFPlayer *pPlayer, CTFWrench *pWrench, Vector vecHitPos ) { Assert( pPlayer ); if ( !pPlayer ) return false; bool bDidWork = false; if ( HasSapper() ) { // do damage to any attached buildings #define WRENCH_DMG_VS_SAPPER 65 CTakeDamageInfo info( pPlayer, pPlayer, WRENCH_DMG_VS_SAPPER, DMG_CLUB, TF_DMG_WRENCH_FIX ); IHasBuildPoints *pBPInterface = dynamic_cast< IHasBuildPoints * >( this ); int iNumObjects = pBPInterface->GetNumObjectsOnMe(); for ( int iPoint=0;iPoint<iNumObjects;iPoint++ ) { CBaseObject *pObject = GetBuildPointObject( iPoint ); if ( pObject && pObject->IsHostileUpgrade() ) { int iBeforeHealth = pObject->GetHealth(); pObject->TakeDamage( info ); // This should always be true if ( iBeforeHealth != pObject->GetHealth() ) { bDidWork = true; Assert( bDidWork ); } } } } else if ( IsBuilding() ) { OnConstructionHit( pPlayer, pWrench, vecHitPos ); bDidWork = true; } else { // upgrade, refill, repair damage bDidWork = OnWrenchHit( pPlayer, pWrench, vecHitPos ); } return bDidWork; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CBaseObject::OnWrenchHit( CTFPlayer *pPlayer, CTFWrench *pWrench, Vector vecHitPos ) { bool bRepair = false; bool bUpgrade = false; // If the player repairs it at all, we're done bRepair = Command_Repair( pPlayer/*, pWrench->GetRepairValue()*/ ); if ( !bRepair ) { // no building upgrade for minis. if ( !IsMiniBuilding() ) { // Don't put in upgrade metal until the object is fully healed if ( CanBeUpgraded( pPlayer ) ) { bUpgrade = CheckUpgradeOnHit( pPlayer ); } } } DoWrenchHitEffect( vecHitPos, bRepair, bUpgrade ); return ( bRepair || bUpgrade ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CBaseObject::CheckUpgradeOnHit( CTFPlayer *pPlayer ) { bool bUpgrade = false; int iPlayerMetal = pPlayer->GetAmmoCount( TF_AMMO_METAL ); int iAmountToAdd = min( tf_obj_upgrade_per_hit.GetInt(), iPlayerMetal ); if ( iAmountToAdd > ( m_iUpgradeMetalRequired - m_iUpgradeMetal ) ) iAmountToAdd = ( m_iUpgradeMetalRequired - m_iUpgradeMetal ); if ( tf_cheapobjects.GetBool() == false ) { pPlayer->RemoveAmmo( iAmountToAdd, TF_AMMO_METAL ); } m_iUpgradeMetal += iAmountToAdd; if ( iAmountToAdd > 0 ) { bUpgrade = true; } if ( m_iUpgradeMetal >= m_iUpgradeMetalRequired ) { StartUpgrading(); IGameEvent * event = gameeventmanager->CreateEvent( "player_upgradedobject" ); if ( event ) { event->SetInt( "userid", pPlayer->GetUserID() ); event->SetInt( "object", ObjectType() ); event->SetInt( "index", entindex() ); // object entity index event->SetBool( "isbuilder", pPlayer == GetBuilder() ); gameeventmanager->FireEvent( event, true ); // don't send to clients } m_iUpgradeMetal = 0; } return bUpgrade; } //----------------------------------------------------------------------------- // Purpose: Separated so it can be triggered by wrench hit or by vgui screen //----------------------------------------------------------------------------- bool CBaseObject::Command_Repair( CTFPlayer *pActivator ) { if ( GetHealth() < GetMaxHealth() ) { int iAmountToHeal = min( 100, GetMaxHealth() - GetHealth() ); // repair the building int iRepairCost = ceil( (float)( iAmountToHeal ) * 0.2f ); TRACE_OBJECT( UTIL_VarArgs( "%0.2f CObjectDispenser::Command_Repair ( %d / %d ) - cost = %d\n", gpGlobals->curtime, GetHealth(), GetMaxHealth(), iRepairCost ) ); if ( iRepairCost > 0 ) { if ( iRepairCost > pActivator->GetBuildResources() ) { iRepairCost = pActivator->GetBuildResources(); } pActivator->RemoveBuildResources( iRepairCost ); float flNewHealth = min( GetMaxHealth(), m_flHealth + ( iRepairCost * 5 ) ); SetHealth( flNewHealth ); return ( iRepairCost > 0 ); } } return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseObject::PlayStartupAnimation( void ) { SetActivity( ACT_OBJ_STARTUP ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseObject::DetermineAnimation( void ) { Activity desiredActivity = m_Activity; switch ( m_Activity ) { default: { if ( IsUpgrading() ) { desiredActivity = ACT_OBJ_UPGRADING; } else if ( IsPlacing() ) { /* if (1 || m_bPlacementOK ) { desiredActivity = ACT_OBJ_PLACING; } else { desiredActivity = ACT_OBJ_IDLE; } */ } else if ( IsBuilding() ) { desiredActivity = ACT_OBJ_ASSEMBLING; } else { desiredActivity = ACT_OBJ_RUNNING; } } break; case ACT_OBJ_STARTUP: { if ( IsActivityFinished() ) { desiredActivity = ACT_OBJ_RUNNING; } } break; } if ( desiredActivity == m_Activity ) return; SetActivity( desiredActivity ); } //----------------------------------------------------------------------------- // Purpose: Attach this object to the specified object //----------------------------------------------------------------------------- void CBaseObject::AttachObjectToObject( CBaseEntity *pEntity, int iPoint, Vector &vecOrigin ) { m_hBuiltOnEntity = pEntity; m_iBuiltOnPoint = iPoint; if ( m_hBuiltOnEntity.Get() ) { // Parent ourselves to the object CBaseAnimating *pAnimating = dynamic_cast<CBaseAnimating *>( pEntity ); if ( pAnimating && pAnimating->LookupBone( "weapon_bone" ) > 0 ) { FollowEntity( m_hBuiltOnEntity.Get(), true ); } int iAttachment = 0; IHasBuildPoints *pBPInterface = dynamic_cast<IHasBuildPoints*>( pEntity ); Assert( pBPInterface ); if ( pBPInterface ) { iAttachment = pBPInterface->GetBuildPointAttachmentIndex( iPoint ); // re-link to the build points if the sapper is already built if ( !( IsPlacing() || IsBuilding() ) ) { pBPInterface->SetObjectOnBuildPoint( m_iBuiltOnPoint, this ); } } SetParent( m_hBuiltOnEntity.Get(), iAttachment ); if ( iAttachment >= 1 ) { // Stick right onto the attachment point. vecOrigin.Init(); SetLocalOrigin( vecOrigin ); SetLocalAngles( QAngle(0,0,0) ); } else { SetAbsOrigin( vecOrigin ); vecOrigin = GetLocalOrigin(); } SetupAttachedVersion(); } Assert( m_hBuiltOnEntity.Get() == GetMoveParent() ); } //----------------------------------------------------------------------------- // Purpose: Detach this object from its parent, if it has one //----------------------------------------------------------------------------- void CBaseObject::DetachObjectFromObject( void ) { if ( !GetParentObject() ) return; // Clear the build point IHasBuildPoints *pBPInterface = dynamic_cast<IHasBuildPoints*>(GetParentObject() ); Assert( pBPInterface ); pBPInterface->SetObjectOnBuildPoint( m_iBuiltOnPoint, NULL ); SetParent( NULL ); m_hBuiltOnEntity = NULL; m_iBuiltOnPoint = 0; } //----------------------------------------------------------------------------- // Purpose: Spawn any objects specified inside the mdl //----------------------------------------------------------------------------- void CBaseObject::SpawnEntityOnBuildPoint( const char *pEntityName, int iAttachmentNumber ) { // Try and spawn the object CBaseEntity *pEntity = CreateEntityByName( pEntityName ); if ( !pEntity ) return; Vector vecOrigin; QAngle vecAngles; GetAttachment( iAttachmentNumber, vecOrigin, vecAngles ); pEntity->SetAbsOrigin( vecOrigin ); pEntity->SetAbsAngles( vecAngles ); pEntity->Spawn(); // If it's an object, finish setting it up CBaseObject *pObject = dynamic_cast<CBaseObject*>(pEntity); if ( !pObject ) return; // Add a buildpoint here int iPoint = AddBuildPoint( iAttachmentNumber ); AddValidObjectToBuildPoint( iPoint, pObject->GetType() ); pObject->SetBuilder( GetBuilder() ); pObject->ChangeTeam( GetTeamNumber() ); pObject->SpawnControlPanels(); pObject->SetHealth( pObject->GetMaxHealth() ); pObject->FinishedBuilding(); pObject->AttachObjectToObject( this, iPoint, vecOrigin ); //pObject->m_fObjectFlags |= OF_CANNOT_BE_DISMANTLED; IHasBuildPoints *pBPInterface = dynamic_cast<IHasBuildPoints*>(this); Assert( pBPInterface ); pBPInterface->SetObjectOnBuildPoint( iPoint, pObject ); } //----------------------------------------------------------------------------- // Purpose: Spawn any objects specified inside the mdl //----------------------------------------------------------------------------- void CBaseObject::SpawnObjectPoints( void ) { KeyValues *modelKeyValues = new KeyValues(""); if ( !modelKeyValues->LoadFromBuffer( modelinfo->GetModelName( GetModel() ), modelinfo->GetModelKeyValueText( GetModel() ) ) ) { modelKeyValues->deleteThis(); return; } // Do we have a build point section? KeyValues *pkvAllObjectPoints = modelKeyValues->FindKey("object_points"); if ( !pkvAllObjectPoints ) { modelKeyValues->deleteThis(); return; } // Start grabbing the sounds and slotting them in KeyValues *pkvObjectPoint; for ( pkvObjectPoint = pkvAllObjectPoints->GetFirstSubKey(); pkvObjectPoint; pkvObjectPoint = pkvObjectPoint->GetNextKey() ) { // Find the attachment first const char *sAttachment = pkvObjectPoint->GetName(); int iAttachmentNumber = LookupAttachment( sAttachment ); if ( iAttachmentNumber == 0 ) { Msg( "ERROR: Model %s specifies object point %s, but has no attachment named %s.\n", STRING(GetModelName()), pkvObjectPoint->GetString(), pkvObjectPoint->GetString() ); continue; } // Now see what we're supposed to spawn there // The count check is because it seems wrong to emit multiple entities on the same point int nCount = 0; KeyValues *pkvObject; for ( pkvObject = pkvObjectPoint->GetFirstSubKey(); pkvObject; pkvObject = pkvObject->GetNextKey() ) { SpawnEntityOnBuildPoint( pkvObject->GetName(), iAttachmentNumber ); ++nCount; Assert( nCount <= 1 ); } } modelKeyValues->deleteThis(); } bool CBaseObject::IsSolidToPlayers( void ) const { switch ( m_SolidToPlayers ) { default: break; case SOLID_TO_PLAYER_USE_DEFAULT: { if ( GetObjectInfo( ObjectType() ) ) { return GetObjectInfo( ObjectType() )->m_bSolidToPlayerMovement; } } break; case SOLID_TO_PLAYER_YES: return true; case SOLID_TO_PLAYER_NO: return false; } return false; } void CBaseObject::SetSolidToPlayers( OBJSOLIDTYPE stp, bool force ) { bool changed = stp != m_SolidToPlayers; m_SolidToPlayers = stp; if ( changed || force ) { SetCollisionGroup( IsSolidToPlayers() ? TFCOLLISION_GROUP_OBJECT_SOLIDTOPLAYERMOVEMENT : TFCOLLISION_GROUP_OBJECT ); } } int CBaseObject::DrawDebugTextOverlays(void) { int text_offset = BaseClass::DrawDebugTextOverlays(); if (m_debugOverlays & OVERLAY_TEXT_BIT) { char tempstr[512]; Q_snprintf( tempstr, sizeof( tempstr ),"Health: %d / %d ( %.1f )", GetHealth(), GetMaxHealth(), (float)GetHealth() / (float)GetMaxHealth() ); EntityText(text_offset,tempstr,0); text_offset++; CTFPlayer *pBuilder = GetBuilder(); Q_snprintf( tempstr, sizeof( tempstr ),"Built by: (%d) %s", pBuilder ? pBuilder->entindex() : -1, pBuilder ? pBuilder->GetPlayerName() : "invalid builder" ); EntityText(text_offset,tempstr,0); text_offset++; if ( IsBuilding() ) { Q_snprintf( tempstr, sizeof( tempstr ),"Build Rate: %.1f", GetConstructionMultiplier() ); EntityText(text_offset,tempstr,0); text_offset++; } } return text_offset; } //----------------------------------------------------------------------------- // Purpose: Change build orientation //----------------------------------------------------------------------------- void CBaseObject::RotateBuildAngles( void ) { // rotate the build angles by 90 degrees ( final angle calculated after we network this ) m_iDesiredBuildRotations++; m_iDesiredBuildRotations = m_iDesiredBuildRotations % 4; } //----------------------------------------------------------------------------- // Purpose: called on edge cases to see if we need to change our disabled state //----------------------------------------------------------------------------- void CBaseObject::UpdateDisabledState( void ) { SetDisabled( HasSapper() ); } //----------------------------------------------------------------------------- // Purpose: called when our disabled state changes //----------------------------------------------------------------------------- void CBaseObject::SetDisabled( bool bDisabled ) { if ( bDisabled && !m_bDisabled ) { OnStartDisabled(); } else if ( !bDisabled && m_bDisabled ) { OnEndDisabled(); } m_bDisabled = bDisabled; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseObject::OnStartDisabled( void ) { } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseObject::OnEndDisabled( void ) { } //----------------------------------------------------------------------------- // Purpose: Called when the model changes, find new attachments for the children //----------------------------------------------------------------------------- void CBaseObject::ReattachChildren( void ) { int iNumBuildPoints = GetNumBuildPoints(); for (CBaseEntity *pChild = FirstMoveChild(); pChild; pChild = pChild->NextMovePeer()) { //CBaseObject *pObject = GetBuildPointObject( iPoint ); CBaseObject *pObject = dynamic_cast<CBaseObject *>( pChild ); if ( !pObject ) { continue; } Assert( pObject->GetParent() == this ); // get the type int iObjectType = pObject->GetType(); bool bReattached = false; Vector vecDummy; for ( int i = 0; i < iNumBuildPoints && bReattached == false; i++ ) { // Can this object build on this point? if ( CanBuildObjectOnBuildPoint( i, iObjectType ) ) { pObject->AttachObjectToObject( this, i, vecDummy ); bReattached = true; } } // if we can't find an attach for the child, remove it and print an error if ( bReattached == false ) { pObject->DestroyObject(); Assert( !"Couldn't find attachment point on upgraded object for existing child.\n" ); } } } void CBaseObject::SetModel( const char *pModel ) { BaseClass::SetModel( pModel ); // Clear out the gib list and create a new one. m_aGibs.Purge(); BuildGibList( m_aGibs, GetModelIndex(), 1.0f, COLLISION_GROUP_NONE ); } <|start_filename|>src/game/shared/econ/econ_wearable.cpp<|end_filename|> //========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //========================================================================// #include "cbase.h" #include "econ_wearable.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" IMPLEMENT_NETWORKCLASS_ALIASED( EconWearable, DT_EconWearable ) BEGIN_NETWORK_TABLE( CEconWearable, DT_EconWearable ) #ifdef GAME_DLL SendPropString( SENDINFO( m_ParticleName ) ), SendPropBool( SENDINFO( m_bExtraWearable ) ), #else RecvPropString( RECVINFO( m_ParticleName ) ), RecvPropBool( RECVINFO( m_bExtraWearable ) ), #endif END_NETWORK_TABLE() void CEconWearable::Spawn( void ) { GetAttributeContainer()->InitializeAttributes( this ); Precache(); if ( m_bExtraWearable && m_Item.GetStaticData() ) { SetModel( m_Item.GetStaticData()->extra_wearable ); } else { SetModel( m_Item.GetPlayerDisplayModel() ); } BaseClass::Spawn(); AddEffects( EF_BONEMERGE ); AddEffects( EF_BONEMERGE_FASTCULL ); SetCollisionGroup( COLLISION_GROUP_WEAPON ); SetBlocksLOS( false ); } int CEconWearable::GetSkin( void ) { switch ( GetTeamNumber() ) { case TF_TEAM_BLUE: return 1; break; case TF_TEAM_RED: return 0; break; default: return 0; break; } } void CEconWearable::UpdateWearableBodyGroups( CBasePlayer *pPlayer ) { EconItemVisuals *visual = GetItem()->GetStaticData()->GetVisuals( GetTeamNumber() ); for ( unsigned int i = 0; i < visual->player_bodygroups.Count(); i++ ) { const char *szBodyGroupName = visual->player_bodygroups.GetElementName(i); if ( szBodyGroupName ) { int iBodyGroup = pPlayer->FindBodygroupByName( szBodyGroupName ); int iBodyGroupValue = visual->player_bodygroups.Element(i); pPlayer->SetBodygroup( iBodyGroup, iBodyGroupValue ); } } } void CEconWearable::SetParticle(const char* name) { #ifdef GAME_DLL Q_snprintf(m_ParticleName.GetForModify(), PARTICLE_MODIFY_STRING_SIZE, name); #else Q_snprintf(m_ParticleName, PARTICLE_MODIFY_STRING_SIZE, name); #endif } void CEconWearable::GiveTo( CBaseEntity *pEntity ) { #ifdef GAME_DLL CBasePlayer *pPlayer = ToBasePlayer( pEntity ); if ( pPlayer ) { pPlayer->EquipWearable( this ); } #endif } #ifdef GAME_DLL void CEconWearable::Equip( CBasePlayer *pPlayer ) { if ( pPlayer ) { FollowEntity( pPlayer, true ); SetOwnerEntity( pPlayer ); ChangeTeam( pPlayer->GetTeamNumber() ); // Extra wearables don't provide attribute bonuses if ( !IsExtraWearable() ) ReapplyProvision(); } } void CEconWearable::UnEquip( CBasePlayer *pPlayer ) { if ( pPlayer ) { StopFollowingEntity(); SetOwnerEntity( NULL ); ReapplyProvision(); } } #else void CEconWearable::OnDataChanged( DataUpdateType_t type ) { BaseClass::OnDataChanged( type ); if ( type == DATA_UPDATE_DATATABLE_CHANGED ) { if (Q_stricmp(m_ParticleName, "") && !m_pUnusualParticle) { m_pUnusualParticle = ParticleProp()->Create(m_ParticleName, PATTACH_ABSORIGIN_FOLLOW); } } } ShadowType_t CEconWearable::ShadowCastType( void ) { if ( ShouldDraw() ) { return SHADOWS_RENDER_TO_TEXTURE_DYNAMIC; } return SHADOWS_NONE; } bool CEconWearable::ShouldDraw( void ) { CBasePlayer *pOwner = ToBasePlayer( GetOwnerEntity() ); if ( !pOwner ) return false; if ( !pOwner->ShouldDrawThisPlayer() ) return false; if ( !pOwner->IsAlive() ) return false; return BaseClass::ShouldDraw(); } #endif <|start_filename|>src/game/shared/econ/econ_entity.h<|end_filename|> //========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //===========================================================================// #ifndef ECON_ENTITY_H #define ECON_ENTITY_H #ifdef _WIN32 #pragma once #endif #if defined( CLIENT_DLL ) #define CEconEntity C_EconEntity #endif #include "ihasattributes.h" #include "econ_item_view.h" #include "attribute_manager.h" #ifdef CLIENT_DLL #include "c_tf_viewmodeladdon.h" #endif struct wearableanimplayback_t { int iStub; }; //----------------------------------------------------------------------------- // Purpose: BaseCombatWeapon is derived from this in live tf2. //----------------------------------------------------------------------------- class CEconEntity : public CBaseAnimating, public IHasAttributes { DECLARE_CLASS( CEconEntity, CBaseAnimating ); DECLARE_NETWORKCLASS(); #ifdef CLIENT_DLL DECLARE_PREDICTABLE(); #endif public: CEconEntity(); ~CEconEntity(); #ifdef CLIENT_DLL virtual void OnPreDataChanged( DataUpdateType_t ); virtual void OnDataChanged( DataUpdateType_t ); virtual void FireEvent( const Vector& origin, const QAngle& angles, int event, const char *options ); virtual bool OnFireEvent( C_BaseViewModel *pViewModel, const Vector& origin, const QAngle& angles, int event, const char *options ); virtual C_ViewmodelAttachmentModel *GetViewmodelAddon( void ) { return NULL; } virtual bool OnInternalDrawModel( ClientModelRenderInfo_t *pInfo ); virtual void ViewModelAttachmentBlending( CStudioHdr *hdr, Vector pos[], Quaternion q[], float currentTime, int boneMask ); #endif virtual int TranslateViewmodelHandActivity( int iActivity ) { return iActivity; } virtual void PlayAnimForPlaybackEvent(wearableanimplayback_t iPlayback) {}; virtual void SetItem( CEconItemView &newItem ); CEconItemView *GetItem(); virtual bool HasItemDefinition() const; virtual int GetItemID(); virtual void GiveTo( CBaseEntity *pEntity ); virtual CAttributeManager *GetAttributeManager() { return &m_AttributeManager; } virtual CAttributeContainer *GetAttributeContainer() { return &m_AttributeManager; } virtual CBaseEntity *GetAttributeOwner() { return NULL; } virtual void ReapplyProvision( void ); void UpdatePlayerModelToClass( void ); virtual void UpdatePlayerBodygroups( void ); virtual void UpdateOnRemove( void ); protected: EHANDLE m_hOldOwner; CEconItemView m_Item; private: CNetworkVarEmbedded( CAttributeContainer, m_AttributeManager ); }; #ifdef CLIENT_DLL void DrawEconEntityAttachedModels( C_BaseAnimating *pAnimating, C_EconEntity *pEconEntity, ClientModelRenderInfo_t const *pInfo, int iModelType ); #endif #endif <|start_filename|>src/game/client/c_stickybolt.cpp<|end_filename|> //========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: Implements the Sticky Bolt code. This constraints ragdolls to the world // after being hit by a crossbow bolt. If something here is acting funny // let me know - Adrian. // // $Workfile: $ // $Date: $ // //----------------------------------------------------------------------------- // $Log: $ // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "c_basetempentity.h" #include "fx.h" #include "decals.h" #include "iefx.h" #include "engine/IEngineSound.h" #include "materialsystem/imaterialvar.h" #include "IEffects.h" #include "engine/IEngineTrace.h" #include "vphysics/constraints.h" #include "engine/ivmodelinfo.h" #include "tempent.h" #include "c_te_legacytempents.h" #include "engine/ivdebugoverlay.h" #include "c_te_effect_dispatch.h" #include "c_tf_player.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" extern IPhysicsSurfaceProps *physprops; IPhysicsObject *GetWorldPhysObject( void ); extern ITempEnts* tempents; class CRagdollBoltEnumerator : public IPartitionEnumerator { public: //Forced constructor CRagdollBoltEnumerator( Ray_t& shot, Vector vOrigin ) { m_rayShot = shot; m_vWorld = vOrigin; } //Actual work code IterationRetval_t EnumElement( IHandleEntity *pHandleEntity ) { C_BaseEntity *pEnt = ClientEntityList().GetBaseEntityFromHandle( pHandleEntity->GetRefEHandle() ); if ( pEnt == NULL ) return ITERATION_CONTINUE; C_BaseAnimating *pModel = static_cast< C_BaseAnimating * >( pEnt ); if ( pModel == NULL ) return ITERATION_CONTINUE; trace_t tr; enginetrace->ClipRayToEntity( m_rayShot, MASK_SHOT, pModel, &tr ); IPhysicsObject *pPhysicsObject = NULL; //Find the real object we hit. if( tr.physicsbone >= 0 ) { //Msg( "\nPhysics Bone: %i\n", tr.physicsbone ); if ( pModel->m_pRagdoll ) { CRagdoll *pCRagdoll = dynamic_cast < CRagdoll * > ( pModel->m_pRagdoll ); if ( pCRagdoll ) { ragdoll_t *pRagdollT = pCRagdoll->GetRagdoll(); if ( tr.physicsbone < pRagdollT->listCount ) { pPhysicsObject = pRagdollT->list[tr.physicsbone].pObject; } } } } if ( pPhysicsObject == NULL ) return ITERATION_CONTINUE; if ( tr.fraction < 1.0 ) { IPhysicsObject *pReference = GetWorldPhysObject(); if ( pReference == NULL || pPhysicsObject == NULL ) return ITERATION_CONTINUE; float flMass = pPhysicsObject->GetMass(); pPhysicsObject->SetMass( flMass * 2 ); constraint_ballsocketparams_t ballsocket; ballsocket.Defaults(); pReference->WorldToLocal( &ballsocket.constraintPosition[0], m_vWorld ); pPhysicsObject->WorldToLocal( &ballsocket.constraintPosition[1], tr.endpos ); physenv->CreateBallsocketConstraint( pReference, pPhysicsObject, NULL, ballsocket ); //Play a sound /*CPASAttenuationFilter filter( pEnt ); EmitSound_t ep; ep.m_nChannel = CHAN_VOICE; ep.m_pSoundName = "Weapon_Crossbow.BoltSkewer"; ep.m_flVolume = 1.0f; ep.m_SoundLevel = SNDLVL_NORM; ep.m_pOrigin = &pEnt->GetAbsOrigin(); C_BaseEntity::EmitSound( filter, SOUND_FROM_WORLD, ep );*/ return ITERATION_STOP; } return ITERATION_CONTINUE; } private: Ray_t m_rayShot; Vector m_vWorld; }; void CreateCrossbowBolt( const Vector &vecOrigin, const Vector &vecDirection ) { //model_t *pModel = (model_t *)engine->LoadModel( "models/crossbow_bolt.mdl" ); //repurpose old crossbow collision code for huntsman collisions model_t *pModel = (model_t *)engine->LoadModel( "models/weapons/w_models/w_arrow.mdl" ); QAngle vAngles; VectorAngles( vecDirection, vAngles ); tempents->SpawnTempModel( pModel, vecOrigin - vecDirection * 8, vAngles, Vector( 0, 0, 0 ), 30.0f, FTENT_NONE ); } void StickRagdollNow( const Vector &vecOrigin, const Vector &vecDirection ) { Ray_t shotRay; trace_t tr; UTIL_TraceLine( vecOrigin, vecOrigin + vecDirection * 16, MASK_SOLID_BRUSHONLY, NULL, COLLISION_GROUP_NONE, &tr ); if ( tr.surface.flags & SURF_SKY ) return; Vector vecEnd = vecOrigin - vecDirection * 128; shotRay.Init( vecOrigin, vecEnd ); CRagdollBoltEnumerator ragdollEnum( shotRay, vecOrigin ); partition->EnumerateElementsAlongRay( PARTITION_CLIENT_RESPONSIVE_EDICTS, shotRay, false, &ragdollEnum ); CreateCrossbowBolt( vecOrigin, vecDirection ); } //----------------------------------------------------------------------------- // Purpose: // Input : &data - //----------------------------------------------------------------------------- void StickyBoltCallback( const CEffectData &data ) { StickRagdollNow( data.m_vOrigin, data.m_vNormal ); } DECLARE_CLIENT_EFFECT( "BoltImpact", StickyBoltCallback ); <|start_filename|>src/game/shared/econ/econ_item_view.cpp<|end_filename|> #include "cbase.h" #include "econ_item_view.h" #include "econ_item_system.h" #include "activitylist.h" #ifdef CLIENT_DLL #include "dt_utlvector_recv.h" #else #include "dt_utlvector_send.h" #endif // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define MAX_ATTRIBUTES_SENT 20 #ifdef CLIENT_DLL BEGIN_RECV_TABLE_NOBASE(CEconItemView, DT_ScriptCreatedItem) RecvPropInt(RECVINFO(m_iItemDefinitionIndex)), RecvPropInt(RECVINFO(m_iEntityQuality)), RecvPropInt(RECVINFO(m_iEntityLevel)), RecvPropInt(RECVINFO(m_iItemID)), RecvPropInt(RECVINFO(m_iInventoryPosition)), RecvPropInt(RECVINFO(m_iTeamNumber)), RecvPropBool(RECVINFO(m_bOnlyIterateItemViewAttributes)), RecvPropUtlVector( RECVINFO_UTLVECTOR( m_AttributeList ), MAX_ATTRIBUTES_SENT, RecvPropDataTable( NULL, 0, 0, &REFERENCE_RECV_TABLE( DT_EconItemAttribute ) ) ) END_RECV_TABLE() #else BEGIN_SEND_TABLE_NOBASE(CEconItemView, DT_ScriptCreatedItem) SendPropInt(SENDINFO(m_iItemDefinitionIndex)), SendPropInt(SENDINFO(m_iEntityQuality)), SendPropInt(SENDINFO(m_iEntityLevel)), SendPropInt(SENDINFO(m_iItemID)), SendPropInt(SENDINFO(m_iInventoryPosition)), SendPropInt(SENDINFO(m_iTeamNumber)), SendPropBool(SENDINFO(m_bOnlyIterateItemViewAttributes)), SendPropUtlVector( SENDINFO_UTLVECTOR( m_AttributeList ), MAX_ATTRIBUTES_SENT, SendPropDataTable( NULL, 0, &REFERENCE_SEND_TABLE( DT_EconItemAttribute ) ) ) END_SEND_TABLE() #endif #define FIND_ELEMENT(map, key, val) \ unsigned int index = map.Find(key); \ if (index != map.InvalidIndex()) \ val = map.Element(index) #define FIND_ELEMENT_STRING(map, key, val) \ unsigned int index = map.Find(key); \ if (index != map.InvalidIndex()) \ Q_snprintf(val, sizeof(val), map.Element(index)) CEconItemView::CEconItemView() { Init( -1 ); } CEconItemView::CEconItemView( int iItemID ) { Init( iItemID ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CEconItemView::Init( int iItemID ) { SetItemDefIndex( iItemID ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CEconItemView::SetItemDefIndex( int iItemID ) { m_iItemDefinitionIndex = iItemID; //m_pItemDef = GetItemSchema()->GetItemDefinition( m_iItemDefinitionIndex ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CEconItemView::GetItemDefIndex( void ) const { return m_iItemDefinitionIndex; } CEconItemDefinition *CEconItemView::GetStaticData( void ) const { return GetItemSchema()->GetItemDefinition( m_iItemDefinitionIndex ); } const char *CEconItemView::GetWorldDisplayModel( int iClass/* = 0*/ ) const { CEconItemDefinition *pStatic = GetStaticData(); const char *pszModelName = NULL; if ( pStatic ) { pszModelName = pStatic->model_world; // Assuming we're using same model for both 1st person and 3rd person view. if ( !pszModelName[0] && pStatic->attach_to_hands == 1 ) { pszModelName = pStatic->model_player; } } return pszModelName; } const char *CEconItemView::GetPlayerDisplayModel( int iClass/* = 0*/ ) const { CEconItemDefinition *pStatic = GetStaticData(); if ( pStatic ) { if ( pStatic->model_player_per_class[iClass][0] != '\0' ) return pStatic->model_player_per_class[iClass]; return pStatic->model_player; } return NULL; } const char* CEconItemView::GetEntityName() { CEconItemDefinition *pStatic = GetStaticData(); if ( pStatic ) { return pStatic->item_class; } return NULL; } bool CEconItemView::IsCosmetic() { bool result = false; CEconItemDefinition *pStatic = GetStaticData(); if ( pStatic ) { FIND_ELEMENT( pStatic->tags, "is_cosmetic", result ); } return result; } int CEconItemView::GetAnimationSlot( void ) { CEconItemDefinition *pStatic = GetStaticData(); if ( pStatic ) { return pStatic->anim_slot; } return -1; } Activity CEconItemView::GetActivityOverride( int iTeamNumber, Activity actOriginalActivity ) { CEconItemDefinition *pStatic = GetStaticData(); if ( pStatic ) { int iOverridenActivity = ACT_INVALID; EconItemVisuals *pVisuals = pStatic->GetVisuals( iTeamNumber ); FIND_ELEMENT( pVisuals->animation_replacement, actOriginalActivity, iOverridenActivity ); if ( iOverridenActivity != ACT_INVALID ) return (Activity)iOverridenActivity; } return actOriginalActivity; } const char *CEconItemView::GetActivityOverride( int iTeamNumber, const char *name ) { CEconItemDefinition *pStatic = GetStaticData(); if ( pStatic ) { int iOriginalAct = ActivityList_IndexForName( name ); int iOverridenAct = ACT_INVALID; EconItemVisuals *pVisuals = pStatic->GetVisuals( iTeamNumber ); FIND_ELEMENT( pVisuals->animation_replacement, iOriginalAct, iOverridenAct ); if ( iOverridenAct != ACT_INVALID ) return ActivityList_NameForIndex( iOverridenAct ); } return name; } const char *CEconItemView::GetSoundOverride( int iIndex, int iTeamNum /*= 0*/ ) const { CEconItemDefinition *pStatic = GetStaticData(); if ( pStatic ) { EconItemVisuals *pVisuals = pStatic->GetVisuals( iTeamNum ); return pVisuals->aWeaponSounds[iIndex]; } return NULL; } bool CEconItemView::HasCapability( const char* name ) { bool result = false; CEconItemDefinition *pStatic = GetStaticData(); if ( pStatic ) { FIND_ELEMENT( pStatic->capabilities, name, result ); } return result; } bool CEconItemView::HasTag( const char* name ) { bool result = false; CEconItemDefinition *pStatic = GetStaticData(); if ( pStatic ) { FIND_ELEMENT( pStatic->tags, name, result ); } return result; } bool CEconItemView::AddAttribute( CEconItemAttribute *pAttribute ) { // Make sure this attribute exists. EconAttributeDefinition *pAttribDef = pAttribute->GetStaticData(); if ( pAttribDef ) { m_AttributeList.AddToTail( *pAttribute ); return true; } return false; } void CEconItemView::SkipBaseAttributes( bool bSkip ) { m_bOnlyIterateItemViewAttributes = bSkip; } CEconItemAttribute *CEconItemView::IterateAttributes( string_t strClass ) { // Returning the first attribute found. // This is not how live TF2 does this but this will do for now. for ( int i = 0; i < m_AttributeList.Count(); i++ ) { CEconItemAttribute *pAttribute = &m_AttributeList[i]; if ( pAttribute->m_strAttributeClass == strClass ) { return pAttribute; } } CEconItemDefinition *pStatic = GetStaticData(); if ( pStatic && !m_bOnlyIterateItemViewAttributes ) { return pStatic->IterateAttributes( strClass ); } return NULL; } <|start_filename|>src/game/shared/econ/attribute_manager.cpp<|end_filename|> #include "cbase.h" #include "attribute_manager.h" #include "econ_item_schema.h" #ifdef CLIENT_DLL #include "prediction.h" #endif // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define ATTRIB_REAPPLY_PARITY_BITS 3 BEGIN_NETWORK_TABLE_NOBASE( CAttributeManager, DT_AttributeManager ) #ifdef CLIENT_DLL RecvPropEHandle( RECVINFO( m_hOuter ) ), RecvPropInt( RECVINFO( m_iReapplyProvisionParity ) ), #else SendPropEHandle( SENDINFO( m_hOuter ) ), SendPropInt( SENDINFO( m_iReapplyProvisionParity ), ATTRIB_REAPPLY_PARITY_BITS, SPROP_UNSIGNED ), #endif END_NETWORK_TABLE() CAttributeManager::CAttributeManager() { m_bParsingMyself = false; m_iReapplyProvisionParity = 0; } #ifdef CLIENT_DLL void CAttributeManager::OnPreDataChanged( DataUpdateType_t updateType ) { m_iOldReapplyProvisionParity = m_iReapplyProvisionParity; } void CAttributeManager::OnDataChanged( DataUpdateType_t updateType ) { // If parity ever falls out of sync we can catch up here. if ( m_iReapplyProvisionParity != m_iOldReapplyProvisionParity ) { if ( m_hOuter ) { IHasAttributes *pAttributes = m_hOuter->GetHasAttributesInterfacePtr(); pAttributes->ReapplyProvision(); m_iOldReapplyProvisionParity = m_iReapplyProvisionParity; } } } #endif void CAttributeManager::AddProvider( CBaseEntity *pEntity ) { m_AttributeProviders.AddToTail( pEntity ); } void CAttributeManager::RemoveProvider( CBaseEntity *pEntity ) { m_AttributeProviders.FindAndRemove( pEntity ); } void CAttributeManager::ProviteTo( CBaseEntity *pEntity ) { if ( !pEntity || !m_hOuter.Get() ) return; IHasAttributes *pAttributes = pEntity->GetHasAttributesInterfacePtr(); if ( pAttributes ) { pAttributes->GetAttributeManager()->AddProvider( m_hOuter.Get() ); } #ifdef CLIENT_DLL if ( prediction->InPrediction() ) #endif m_iReapplyProvisionParity = ( m_iReapplyProvisionParity + 1 ) & ( ( 1 << ATTRIB_REAPPLY_PARITY_BITS ) - 1 ); } void CAttributeManager::StopProvidingTo( CBaseEntity *pEntity ) { if ( !pEntity || !m_hOuter.Get() ) return; IHasAttributes *pAttributes = pEntity->GetHasAttributesInterfacePtr(); if ( pAttributes ) { pAttributes->GetAttributeManager()->RemoveProvider( m_hOuter.Get() ); } #ifdef CLIENT_DLL if ( prediction->InPrediction() ) #endif m_iReapplyProvisionParity = ( m_iReapplyProvisionParity + 1 ) & ( ( 1 << ATTRIB_REAPPLY_PARITY_BITS ) - 1 ); } void CAttributeManager::InitializeAttributes( CBaseEntity *pEntity ) { Assert( pEntity->GetHasAttributesInterfacePtr() != NULL ); m_hOuter.Set( pEntity ); m_bParsingMyself = false; } float CAttributeManager::ApplyAttributeFloat( float flValue, const CBaseEntity *pEntity, string_t strAttributeClass ) { if ( m_bParsingMyself || m_hOuter.Get() == NULL ) { return flValue; } // Safeguard to prevent potential infinite loops. m_bParsingMyself = true; for ( int i = 0; i < m_AttributeProviders.Count(); i++ ) { CBaseEntity *pProvider = m_AttributeProviders[i].Get(); if ( !pProvider || pProvider == pEntity ) continue; IHasAttributes *pAttributes = pProvider->GetHasAttributesInterfacePtr(); if ( pAttributes ) { flValue = pAttributes->GetAttributeManager()->ApplyAttributeFloat( flValue, pEntity, strAttributeClass ); } } IHasAttributes *pAttributes = m_hOuter->GetHasAttributesInterfacePtr(); CBaseEntity *pOwner = pAttributes->GetAttributeOwner(); if ( pOwner ) { IHasAttributes *pOwnerAttrib = pOwner->GetHasAttributesInterfacePtr(); if ( pOwnerAttrib ) { flValue = pOwnerAttrib->GetAttributeManager()->ApplyAttributeFloat( flValue, pEntity, strAttributeClass ); } } m_bParsingMyself = false; return flValue; } //----------------------------------------------------------------------------- // Purpose: Search for an attribute on our providers. //----------------------------------------------------------------------------- string_t CAttributeManager::ApplyAttributeString( string_t strValue, const CBaseEntity *pEntity, string_t strAttributeClass ) { if ( m_bParsingMyself || m_hOuter.Get() == NULL ) { return strValue; } // Safeguard to prevent potential infinite loops. m_bParsingMyself = true; for ( int i = 0; i < m_AttributeProviders.Count(); i++ ) { CBaseEntity *pProvider = m_AttributeProviders[i].Get(); if ( !pProvider || pProvider == pEntity ) continue; IHasAttributes *pAttributes = pProvider->GetHasAttributesInterfacePtr(); if ( pAttributes ) { strValue = pAttributes->GetAttributeManager()->ApplyAttributeString( strValue, pEntity, strAttributeClass ); } } IHasAttributes *pAttributes = m_hOuter->GetHasAttributesInterfacePtr(); CBaseEntity *pOwner = pAttributes->GetAttributeOwner(); if ( pOwner ) { IHasAttributes *pOwnerAttrib = pOwner->GetHasAttributesInterfacePtr(); if ( pOwnerAttrib ) { strValue = pOwnerAttrib->GetAttributeManager()->ApplyAttributeString( strValue, pEntity, strAttributeClass ); } } m_bParsingMyself = false; return strValue; } BEGIN_NETWORK_TABLE_NOBASE( CAttributeContainer, DT_AttributeContainer ) #ifdef CLIENT_DLL RecvPropEHandle( RECVINFO( m_hOuter ) ), RecvPropInt( RECVINFO( m_iReapplyProvisionParity ) ), #else SendPropEHandle( SENDINFO( m_hOuter ) ), SendPropInt( SENDINFO( m_iReapplyProvisionParity ), ATTRIB_REAPPLY_PARITY_BITS, SPROP_UNSIGNED ), #endif END_NETWORK_TABLE() #ifdef CLIENT_DLL BEGIN_PREDICTION_DATA_NO_BASE( CAttributeContainer ) DEFINE_PRED_FIELD( m_iReapplyProvisionParity, FIELD_INTEGER, FTYPEDESC_INSENDTABLE ), END_PREDICTION_DATA() #endif CAttributeContainer::CAttributeContainer() { } float CAttributeContainer::ApplyAttributeFloat( float flValue, const CBaseEntity *pEntity, string_t strAttributeClass ) { if ( m_bParsingMyself || m_hOuter.Get() == NULL ) return flValue; m_bParsingMyself = true;; // This should only ever be used by econ entities. CEconEntity *pEconEnt = assert_cast<CEconEntity *>( m_hOuter.Get() ); CEconItemView *pItem = pEconEnt->GetItem(); CEconItemAttribute *pAttribute = pItem->IterateAttributes( strAttributeClass ); if ( pAttribute ) { EconAttributeDefinition *pStatic = pAttribute->GetStaticData(); switch ( pStatic->description_format ) { case ATTRIB_FORMAT_ADDITIVE: case ATTRIB_FORMAT_ADDITIVE_PERCENTAGE: flValue += pAttribute->value; break; case ATTRIB_FORMAT_PERCENTAGE: case ATTRIB_FORMAT_INVERTED_PERCENTAGE: flValue *= pAttribute->value; break; case ATTRIB_FORMAT_OR: default: { // Oh, man... int iValue = (int)flValue; int iAttrib = (int)pAttribute->value; iValue |= iAttrib; flValue = (float)iValue; break; } } } m_bParsingMyself = false; return BaseClass::ApplyAttributeFloat( flValue, pEntity, strAttributeClass ); } //----------------------------------------------------------------------------- // Purpose: Search for an attribute and apply its value. //----------------------------------------------------------------------------- string_t CAttributeContainer::ApplyAttributeString( string_t strValue, const CBaseEntity *pEntity, string_t strAttributeClass ) { if ( m_bParsingMyself || m_hOuter.Get() == NULL ) return strValue; m_bParsingMyself = true;; // This should only ever be used by econ entities. CEconEntity *pEconEnt = assert_cast<CEconEntity *>( m_hOuter.Get() ); CEconItemView *pItem = pEconEnt->GetItem(); CEconItemAttribute *pAttribute = pItem->IterateAttributes( strAttributeClass ); if ( pAttribute ) { strValue = AllocPooledString( pAttribute->value_string.Get() ); } m_bParsingMyself = false; return BaseClass::ApplyAttributeString( strValue, pEntity, strAttributeClass ); } <|start_filename|>src/game/client/tf/vgui/panels/tf_itemtooltippanel.h<|end_filename|> #ifndef TF_ITEMMODELTOOLTIPPANEL_H #define TF_ITEMMODELTOOLTIPPANEL_H #include "tf_dialogpanelbase.h" #include "tf_tooltippanel.h" class CTFAdvModelPanel; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- class CTFItemToolTipPanel : public CTFToolTipPanel { DECLARE_CLASS_SIMPLE( CTFItemToolTipPanel, CTFToolTipPanel ); public: CTFItemToolTipPanel( vgui::Panel* parent, const char *panelName ); virtual bool Init(); virtual ~CTFItemToolTipPanel(); virtual void PerformLayout(); virtual void ApplySchemeSettings( vgui::IScheme *pScheme ); virtual void OnChildSettingsApplied( KeyValues *pInResourceData, Panel *pChild ); virtual void Show(); virtual void Hide(); virtual void ShowToolTip( CEconItemDefinition *pItemData ); virtual void HideToolTip(); private: int iItemID; CExLabel *m_pTitle; CExLabel *m_pClassName; CExLabel *m_pAttributeText; CTFAdvModelPanel *m_pClassModelPanel; CUtlVector<CExLabel*> m_pAttributes; Color m_colorTitle; }; #endif // TF_ITEMMODELTOOLTIPPANEL_H <|start_filename|>src/game/shared/tf/tf_projectile_stunball.cpp<|end_filename|> #include "cbase.h" #include "tf_projectile_stunball.h" #include "tf_gamerules.h" #include "effect_dispatch_data.h" #include "tf_weapon_bat.h" #ifdef GAME_DLL #include "tf_fx.h" #include "tf_gamestats.h" #else #include "particles_new.h" #endif #define TF_STUNBALL_MODEL "models/weapons/w_models/w_baseball.mdl" #define TF_STUNBALL_LIFETIME 15.0f ConVar tf_scout_stunball_base_duration( "tf_scout_stunball_base_duration", "6.0", FCVAR_NOTIFY | FCVAR_REPLICATED, "Modifies stun duration of stunball" ); IMPLEMENT_NETWORKCLASS_ALIASED( TFStunBall, DT_TFStunBall ) BEGIN_NETWORK_TABLE( CTFStunBall, DT_TFStunBall ) #ifdef CLIENT_DLL RecvPropBool( RECVINFO( m_bCritical ) ), #else SendPropBool( SENDINFO( m_bCritical ) ), #endif END_NETWORK_TABLE() #ifdef GAME_DLL BEGIN_DATADESC( CTFStunBall ) END_DATADESC() #endif LINK_ENTITY_TO_CLASS( tf_projectile_stunball, CTFStunBall ); PRECACHE_REGISTER( tf_projectile_stunball ); CTFStunBall::CTFStunBall() { } CTFStunBall::~CTFStunBall() { #ifdef CLIENT_DLL ParticleProp()->StopEmission(); #endif } #ifdef GAME_DLL CTFStunBall *CTFStunBall::Create( CBaseEntity *pWeapon, const Vector &vecOrigin, const QAngle &vecAngles, const Vector &vecVelocity, CBaseCombatCharacter *pOwner, CBaseEntity *pScorer, const AngularImpulse &angVelocity, const CTFWeaponInfo &weaponInfo ) { CTFStunBall *pStunBall = static_cast<CTFStunBall *>( CBaseEntity::CreateNoSpawn( "tf_projectile_stunball", vecOrigin, vecAngles, pOwner ) ); if ( pStunBall ) { // Set scorer. pStunBall->SetScorer( pScorer ); // Set firing weapon. pStunBall->SetLauncher( pWeapon ); DispatchSpawn( pStunBall ); pStunBall->InitGrenade( vecVelocity, angVelocity, pOwner, weaponInfo ); pStunBall->ApplyLocalAngularVelocityImpulse( angVelocity ); } return pStunBall; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFStunBall::Precache( void ) { PrecacheModel( TF_STUNBALL_MODEL ); PrecacheScriptSound( "TFPlayer.StunImpactRange" ); PrecacheScriptSound( "TFPlayer.StunImpact" ); PrecacheTeamParticles( "stunballtrail_%s", false ); PrecacheTeamParticles( "stunballtrail_%s_crit", false ); BaseClass::Precache(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFStunBall::Spawn( void ) { SetModel( TF_STUNBALL_MODEL ); SetDetonateTimerLength( TF_STUNBALL_LIFETIME ); BaseClass::Spawn(); SetTouch( &CTFStunBall::StunBallTouch ); CreateTrail(); // Pumpkin Bombs AddFlag( FL_GRENADE ); // Don't collide with anything for a short time so that we never get stuck behind surfaces SetCollisionGroup( TFCOLLISION_GROUP_NONE ); AddSolidFlags( FSOLID_TRIGGER ); m_flCreationTime = gpGlobals->curtime; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFStunBall::Explode( trace_t *pTrace, int bitsDamageType ) { m_takedamage = DAMAGE_NO; // Pull out of the wall a bit if ( pTrace->fraction != 1.0 ) { SetAbsOrigin( pTrace->endpos + ( pTrace->plane.normal * 1.0f ) ); } CTFWeaponBase *pWeapon = dynamic_cast< CTFWeaponBase * >( m_hLauncher.Get() ); // Pull out a bit. if ( pTrace->fraction != 1.0 ) { SetAbsOrigin( pTrace->endpos + ( pTrace->plane.normal * 1.0f ) ); } // Damage. CTFPlayer *pAttacker = dynamic_cast< CTFPlayer * >( GetThrower() ); CTFPlayer *pPlayer = dynamic_cast< CTFPlayer * >( m_hEnemy.Get() ); // Make sure the player is stunnable if ( pPlayer && pAttacker && CanStun( pPlayer ) ) { float flAirTime = gpGlobals->curtime - m_flCreationTime; float flStunDuration = tf_scout_stunball_base_duration.GetFloat(); Vector vecDir = GetAbsOrigin(); VectorNormalize( vecDir ); // Do damage. CTakeDamageInfo info( this, pAttacker, pWeapon, GetDamage(), GetDamageType(), TF_DMG_CUSTOM_BASEBALL ); CalculateBulletDamageForce( &info, pWeapon ? pWeapon->GetTFWpnData().iAmmoType : 0, vecDir, GetAbsOrigin() ); info.SetReportedPosition( pAttacker ? pAttacker->GetAbsOrigin() : vec3_origin ); pPlayer->DispatchTraceAttack( info, vecDir, pTrace ); ApplyMultiDamage(); if ( flAirTime > 0.1f ) { int iBonus = 1; if ( flAirTime >= 1.0f ) { // Maximum stun is base duration + 1 second flAirTime = 1.0f; flStunDuration += 1.0f; // 2 points for moonshots iBonus++; // Big stun pPlayer->m_Shared.StunPlayer(flStunDuration * ( flAirTime ), 0.0f, 0.75f, TF_STUNFLAGS_BIGBONK, pAttacker ); } else { // Small stun pPlayer->m_Shared.StunPlayer(flStunDuration * ( flAirTime ), 0.8f, 0.0f, TF_STUNFLAGS_SMALLBONK, pAttacker ); } pAttacker->SpeakConceptIfAllowed( MP_CONCEPT_STUNNED_TARGET ); // Bonus points. IGameEvent *event_bonus = gameeventmanager->CreateEvent( "player_bonuspoints" ); if ( event_bonus ) { event_bonus->SetInt( "player_entindex", pPlayer->entindex() ); event_bonus->SetInt( "source_entindex", pAttacker->entindex() ); event_bonus->SetInt( "points", iBonus ); gameeventmanager->FireEvent( event_bonus ); } CTF_GameStats.Event_PlayerAwardBonusPoints( pAttacker, pPlayer, iBonus ); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFStunBall::StunBallTouch( CBaseEntity *pOther ) { // Verify a correct "other." if ( !pOther->IsSolid() || pOther->IsSolidFlagSet( FSOLID_VOLUME_CONTENTS ) ) return; trace_t pTrace; Vector velDir = GetAbsVelocity(); VectorNormalize( velDir ); Vector vecSpot = GetAbsOrigin() - velDir * 32; UTIL_TraceLine( vecSpot, vecSpot + velDir * 64, MASK_SOLID, this, COLLISION_GROUP_NONE, &pTrace ); CTFPlayer *pPlayer = dynamic_cast< CTFPlayer * >( pOther ); // Make us solid once we reach our owner if ( GetCollisionGroup() == TFCOLLISION_GROUP_NONE ) { if ( pOther == GetThrower() ) SetCollisionGroup( COLLISION_GROUP_PROJECTILE ); return; } // Stun the person we hit if ( pPlayer && ( gpGlobals->curtime - m_flCreationTime > 0.2f || GetTeamNumber() != pPlayer->GetTeamNumber() ) ) { if ( !m_bTouched ) { // Save who we hit for calculations m_hEnemy = pOther; m_hSpriteTrail->SUB_FadeOut(); Explode( &pTrace, GetDamageType() ); // Die a little bit after the hit SetDetonateTimerLength( 3.0f ); m_bTouched = true; } CTFWeaponBase *pWeapon = pPlayer->Weapon_GetWeaponByType( TF_WPN_TYPE_MELEE ); if ( pWeapon && pWeapon->PickedUpBall( pPlayer ) ) { UTIL_Remove( this ); } } } //----------------------------------------------------------------------------- // Purpose: Check if this player can be stunned //----------------------------------------------------------------------------- bool CTFStunBall::CanStun( CTFPlayer *pOther ) { // Dead players can't be stunned if ( !pOther->IsAlive() ) return false; // Don't stun team members if ( GetTeamNumber() == pOther->GetTeamNumber() ) return false; // Don't stun players we can't damage if ( pOther->m_Shared.InCond( TF_COND_INVULNERABLE ) || pOther->m_Shared.InCond( TF_COND_PHASE ) ) return false; return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFStunBall::Detonate() { UTIL_Remove( this ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFStunBall::VPhysicsCollision( int index, gamevcollisionevent_t *pEvent ) { BaseClass::VPhysicsCollision( index, pEvent ); int otherIndex = !index; CBaseEntity *pHitEntity = pEvent->pEntities[otherIndex]; if ( !pHitEntity ) { return; } // we've touched a surface m_bTouched = true; // Handle hitting skybox (disappear). surfacedata_t *pprops = physprops->GetSurfaceData( pEvent->surfaceProps[otherIndex] ); if ( pprops->game.material == 'X' ) { // uncomment to destroy ball upon hitting sky brush //SetThink( &CTFGrenadePipebombProjectile::SUB_Remove ); //SetNextThink( gpGlobals->curtime ); return; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFStunBall::SetScorer( CBaseEntity *pScorer ) { m_Scorer = pScorer; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CBasePlayer *CTFStunBall::GetAssistant( void ) { return dynamic_cast<CBasePlayer *>( m_Scorer.Get() ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFStunBall::Deflected( CBaseEntity *pDeflectedBy, Vector &vecDir ) { IPhysicsObject *pPhysicsObject = VPhysicsGetObject(); if ( pPhysicsObject ) { Vector vecOldVelocity, vecVelocity; pPhysicsObject->GetVelocity( &vecOldVelocity, NULL ); float flVel = vecOldVelocity.Length(); vecVelocity = vecDir; vecVelocity *= flVel; AngularImpulse angVelocity( ( 600, random->RandomInt( -1200, 1200 ), 0 ) ); // Now change grenade's direction. pPhysicsObject->SetVelocityInstantaneous( &vecVelocity, &angVelocity ); } CBaseCombatCharacter *pBCC = pDeflectedBy->MyCombatCharacterPointer(); IncremenentDeflected(); m_hDeflectOwner = pDeflectedBy; SetThrower( pBCC ); ChangeTeam( pDeflectedBy->GetTeamNumber() ); // Change trail color. if ( m_hSpriteTrail.Get() ) { UTIL_Remove( m_hSpriteTrail.Get() ); } CreateTrail(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CTFStunBall::GetDamageType() { int iDmgType = BaseClass::GetDamageType(); if ( m_bCritical ) { iDmgType |= DMG_CRITICAL; } if ( m_iDeflected > 0 ) { iDmgType |= DMG_MINICRITICAL; } return iDmgType; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- const char *CTFStunBall::GetTrailParticleName( void ) { return ConstructTeamParticle( "effects/baseballtrail_%s.vmt", GetTeamNumber(), false, g_aTeamNamesShort ); } // ---------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFStunBall::CreateTrail( void ) { CSpriteTrail *pTrail = CSpriteTrail::SpriteTrailCreate( GetTrailParticleName(), GetAbsOrigin(), true ); if ( pTrail ) { pTrail->FollowEntity( this ); pTrail->SetTransparency( kRenderTransAlpha, 255, 255, 255, 128, kRenderFxNone ); pTrail->SetStartWidth( 9.0f ); pTrail->SetTextureResolution( 0.01f ); pTrail->SetLifeTime( 0.4f ); pTrail->TurnOn(); pTrail->SetContextThink( &CBaseEntity::SUB_Remove, gpGlobals->curtime + 5.0f, "RemoveThink" ); m_hSpriteTrail.Set( pTrail ); } } #else //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFStunBall::OnDataChanged( DataUpdateType_t updateType ) { BaseClass::OnDataChanged( updateType ); if ( updateType == DATA_UPDATE_CREATED ) { m_flCreationTime = gpGlobals->curtime; CreateTrails(); } if ( m_iOldTeamNum && m_iOldTeamNum != m_iTeamNum ) { ParticleProp()->StopEmission(); CreateTrails(); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFStunBall::CreateTrails( void ) { if ( IsDormant() ) return; if ( m_bCritical ) { const char *pszEffectName = ConstructTeamParticle( "stunballtrail_%s_crit", GetTeamNumber(), false ); ParticleProp()->Create( pszEffectName, PATTACH_ABSORIGIN_FOLLOW ); } else { const char *pszEffectName = ConstructTeamParticle( "stunballtrail_%s", GetTeamNumber(), false ); ParticleProp()->Create( pszEffectName, PATTACH_ABSORIGIN_FOLLOW ); } } //----------------------------------------------------------------------------- // Purpose: Don't draw if we haven't yet gone past our original spawn point //----------------------------------------------------------------------------- int CTFStunBall::DrawModel( int flags ) { if ( gpGlobals->curtime - m_flCreationTime < 0.1f ) return 0; return BaseClass::DrawModel( flags ); } #endif <|start_filename|>src/game/shared/tf/tf_wearable.cpp<|end_filename|> #include "cbase.h" #include "tf_wearable.h" #ifdef GAME_DLL #include "tf_player.h" #endif // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" IMPLEMENT_NETWORKCLASS_ALIASED( TFWearable, DT_TFWearable ); BEGIN_NETWORK_TABLE( CTFWearable, DT_TFWearable ) END_NETWORK_TABLE() LINK_ENTITY_TO_CLASS( tf_wearable, CTFWearable ); PRECACHE_REGISTER( tf_wearable ); #ifdef GAME_DLL //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFWearable::Equip( CBasePlayer *pPlayer ) { BaseClass::Equip( pPlayer ); UpdateModelToClass(); // player_bodygroups UpdatePlayerBodygroups(); } //---------------------------------------------------------------------------- - // Purpose: //----------------------------------------------------------------------------- void CTFWearable::UpdateModelToClass( void ) { if ( m_bExtraWearable && m_Item.GetStaticData() ) { SetModel( m_Item.GetStaticData()->extra_wearable ); } else { CTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() ); if ( pOwner ) { const char *pszModel = m_Item.GetPlayerDisplayModel( pOwner->GetPlayerClass()->GetClassIndex() ); if ( pszModel[0] != '\0' ) { SetModel( pszModel ); } } } } #endif // GAME_DLL <|start_filename|>src/game/client/tf/tf_hud_crosshair.cpp<|end_filename|> //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #include "cbase.h" #include "hudelement.h" #include <vgui_controls/Panel.h> #include <vgui/ISurface.h> #include "clientmode.h" #include "c_tf_player.h" #include "tf_hud_crosshair.h" #include "materialsystem/imaterial.h" #include "materialsystem/imesh.h" #include "materialsystem/imaterialvar.h" #include "mathlib/mathlib.h" #include "basecombatweapon_shared.h" ConVar cl_crosshair_red( "cl_crosshair_red", "200", FCVAR_ARCHIVE ); ConVar cl_crosshair_green( "cl_crosshair_green", "200", FCVAR_ARCHIVE ); ConVar cl_crosshair_blue( "cl_crosshair_blue", "200", FCVAR_ARCHIVE ); ConVar cl_crosshair_alpha( "cl_crosshair_alpha", "200", FCVAR_ARCHIVE ); ConVar cl_crosshair_file( "cl_crosshair_file", "", FCVAR_ARCHIVE ); ConVar cl_crosshair_scale( "cl_crosshair_scale", "32.0", FCVAR_ARCHIVE ); ConVar cl_crosshair_approach_speed( "cl_crosshair_approach_speed", "0.015" ); ConVar cl_dynamic_crosshair( "cl_dynamic_crosshair", "1", FCVAR_ARCHIVE ); ConVar tf2v_revolver_scale_crosshair( "tf2v_revolver_scale_crosshair", "1", FCVAR_ARCHIVE, "Toggle the crosshair size scaling on the ambassador" ); using namespace vgui; DECLARE_HUDELEMENT(CHudTFCrosshair); CHudTFCrosshair::CHudTFCrosshair(const char *pElementName) : CHudCrosshair("CHudCrosshair") { vgui::Panel *pParent = g_pClientMode->GetViewport(); SetParent(pParent); m_pCrosshair = 0; m_szPreviousCrosshair[0] = '\0'; m_pFrameVar = NULL; m_flAccuracy = 0.1; m_clrCrosshair = Color(0, 0, 0, 0); m_vecCrossHairOffsetAngle.Init(); SetHiddenBits(HIDEHUD_PLAYERDEAD | HIDEHUD_CROSSHAIR); } void CHudTFCrosshair::ApplySchemeSettings(IScheme *scheme) { BaseClass::ApplySchemeSettings( scheme ); SetSize( ScreenWidth(), ScreenHeight() ); } void CHudTFCrosshair::LevelShutdown(void) { // forces m_pFrameVar to recreate next map m_szPreviousCrosshair[0] = '\0'; if (m_pCrosshairOverride) { delete m_pCrosshairOverride; m_pCrosshairOverride = NULL; } if ( m_pFrameVar ) { delete m_pFrameVar; m_pFrameVar = NULL; } } void CHudTFCrosshair::Init() { m_iCrosshairTextureID = vgui::surface()->CreateNewTextureID(); } void CHudTFCrosshair::SetCrosshair(CHudTexture *texture, Color& clr) { m_pCrosshair = texture; m_clrCrosshair = clr; } bool CHudTFCrosshair::ShouldDraw() { C_TFPlayer *pPlayer = C_TFPlayer::GetLocalTFPlayer(); if ( !pPlayer ) return false; CTFWeaponBase *pWeapon = pPlayer->GetActiveTFWeapon(); if ( !pWeapon ) return false; if ( pPlayer->m_Shared.InCond( TF_COND_TAUNTING ) || pPlayer->m_Shared.InCond( TF_COND_STUNNED ) || pPlayer->m_Shared.IsLoser() ) return false; return pWeapon->ShouldDrawCrosshair(); } void CHudTFCrosshair::Paint() { C_TFPlayer *pPlayer = C_TFPlayer::GetLocalTFPlayer(); if ( !pPlayer ) return; const char *crosshairfile = cl_crosshair_file.GetString(); CTFWeaponBase *pWeapon = pPlayer->GetActiveTFWeapon(); if ( !pWeapon ) return; if ( crosshairfile[0] == '\0' ) { m_pCrosshair = pWeapon->GetWpnData().iconCrosshair; BaseClass::Paint(); return; } else { if ( Q_stricmp( m_szPreviousCrosshair, crosshairfile ) != 0 ) { char buf[256]; Q_snprintf( buf, sizeof( buf ), "vgui/crosshairs/%s", crosshairfile ); vgui::surface()->DrawSetTextureFile( m_iCrosshairTextureID, buf, true, false ); if ( m_pCrosshairOverride ) { delete m_pCrosshairOverride; } m_pCrosshairOverride = vgui::surface()->DrawGetTextureMatInfoFactory( m_iCrosshairTextureID ); if ( !m_pCrosshairOverride ) return; if ( m_pFrameVar ) { delete m_pFrameVar; } bool bFound = false; m_pFrameVar = m_pCrosshairOverride->FindVarFactory( "$frame", &bFound ); Assert( bFound ); m_nNumFrames = m_pCrosshairOverride->GetNumAnimationFrames(); // save the name to compare with the cvar in the future Q_strncpy( m_szPreviousCrosshair, crosshairfile, sizeof( m_szPreviousCrosshair ) ); } Color clr( cl_crosshair_red.GetInt(), cl_crosshair_green.GetInt(), cl_crosshair_blue.GetInt(), 255 ); float x, y; bool bBehindCamera; GetDrawPosition( &x, &y, &bBehindCamera, m_vecCrossHairOffsetAngle ); if ( bBehindCamera ) return; int screenWide, screenTall; GetHudSize( screenWide, screenTall ); int iWidth, iHeight; // Ambassador crosshair scaling float flCrosshairScale = 1.0f; if ( pWeapon->GetWeaponID() == TF_WEAPON_REVOLVER ) { int iMode = 0; CALL_ATTRIB_HOOK_INT_ON_OTHER( pWeapon, iMode, set_weapon_mode ); if ( iMode == 1 && tf2v_revolver_scale_crosshair.GetBool() ) { float flFireInterval = min( gpGlobals->curtime - pWeapon->GetLastFireTime(), 1.25f ); flCrosshairScale = clamp( ( flFireInterval / 1.25f ), 0.334, 1.0f ); } } iWidth = iHeight = cl_crosshair_scale.GetInt() / flCrosshairScale; int iX = (int)( x + 0.5f ); int iY = (int)( y + 0.5f ); vgui::surface()->DrawSetColor( clr ); vgui::surface()->DrawSetTexture( m_iCrosshairTextureID ); vgui::surface()->DrawTexturedRect( iX - iWidth, iY - iHeight, iX + iWidth, iY + iHeight ); vgui::surface()->DrawSetTexture( 0 ); } /* if (m_pFrameVar) { if (cl_dynamic_crosshair.GetBool() == false) { m_pFrameVar->SetIntValue(0); } else { CTFWeaponBase *pWeapon = pPlayer->GetActiveTFWeapon(); if (!pWeapon) return; float accuracy = 5;//pWeapon->GetWeaponAccuracy(pPlayer->GetAbsVelocity().Length2D()); float flMin = 0.02; float flMax = 0.125; accuracy = clamp(accuracy, flMin, flMax); // approach this accuracy from our current accuracy m_flAccuracy = Approach(accuracy, m_flAccuracy, cl_crosshair_approach_speed.GetFloat()); float flFrame = RemapVal(m_flAccuracy, flMin, flMax, 0, m_nNumFrames - 1); m_pFrameVar->SetIntValue((int)flFrame); } } */ } <|start_filename|>src/game/client/tf/vgui/controls/tf_advitembutton.cpp<|end_filename|> #include "cbase.h" #include "tf_advitembutton.h" #include "vgui_controls/Frame.h" #include <vgui/ISurface.h> #include <vgui/IVGui.h> #include <vgui/IInput.h> #include "vgui_controls/Button.h" #include "vgui_controls/ImagePanel.h" #include "tf_controls.h" #include <filesystem.h> #include <vgui_controls/AnimationController.h> #include "basemodelpanel.h" #include "panels/tf_dialogpanelbase.h" #include "inputsystem/iinputsystem.h" #include "tf_inventory.h" using namespace vgui; // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" DECLARE_BUILD_FACTORY_DEFAULT_TEXT(CTFAdvItemButton, CTFAdvItemButtonBase); //----------------------------------------------------------------------------- // Purpose: Constructor //----------------------------------------------------------------------------- CTFAdvItemButton::CTFAdvItemButton(vgui::Panel *parent, const char *panelName, const char *text) : CTFAdvButton(parent, panelName, text) { Init(); } //----------------------------------------------------------------------------- // Purpose: Destructor //----------------------------------------------------------------------------- CTFAdvItemButton::~CTFAdvItemButton() { } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFAdvItemButton::Init() { BaseClass::Init(); m_pItemDefinition = NULL; m_iLoadoutSlot = TF_LOADOUT_SLOT_PRIMARY; pButton->SetContentAlignment(CTFAdvButtonBase::GetAlignment("south")); pButton->SetTextInset(0, -10); } void CTFAdvItemButton::PerformLayout() { int inset = YRES(45); int wide = GetWide() - inset; SetImageSize(wide, wide); SetImageInset(inset / 2, -1 * wide / 5); SetShouldScaleImage(true); BaseClass::PerformLayout(); }; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFAdvItemButton::SendAnimation(MouseState flag) { BaseClass::SendAnimation(flag); switch (flag) { case MOUSE_DEFAULT: if ( m_pItemDefinition ) MAINMENU_ROOT->ShowItemToolTip( m_pItemDefinition ); break; case MOUSE_ENTERED: if ( m_pItemDefinition ) MAINMENU_ROOT->ShowItemToolTip( m_pItemDefinition ); break; case MOUSE_EXITED: if ( m_pItemDefinition ) MAINMENU_ROOT->HideItemToolTip(); break; case MOUSE_PRESSED: break; default: break; } } void CTFAdvItemButton::SetItemDefinition(CEconItemDefinition *pItemData) { m_pItemDefinition = pItemData; char szIcon[128]; Q_snprintf(szIcon, sizeof(szIcon), "../%s_large", pItemData->image_inventory); SetImage(szIcon); pButton->SetText( pItemData->GenerateLocalizedFullItemName() ); } void CTFAdvItemButton::SetLoadoutSlot( int iSlot, int iPreset ) { m_iLoadoutSlot = iSlot; char szCommand[64]; Q_snprintf( szCommand, sizeof( szCommand ), "loadout %d %d", iSlot, iPreset ); SetCommandString( szCommand ); } <|start_filename|>src/game/shared/econ/econ_item_schema.h<|end_filename|> #ifndef ECON_ITEM_SCHEMA_H #define ECON_ITEM_SCHEMA_H #ifdef _WIN32 #pragma once #endif #include "tf_shareddefs.h" enum { ATTRIB_FORMAT_INVALID = -1, ATTRIB_FORMAT_PERCENTAGE = 0, ATTRIB_FORMAT_INVERTED_PERCENTAGE, ATTRIB_FORMAT_ADDITIVE, ATTRIB_FORMAT_ADDITIVE_PERCENTAGE, ATTRIB_FORMAT_OR, }; enum { ATTRIB_EFFECT_INVALID = -1, ATTRIB_EFFECT_UNUSUAL = 0, ATTRIB_EFFECT_STRANGE, ATTRIB_EFFECT_NEUTRAL, ATTRIB_EFFECT_POSITIVE, ATTRIB_EFFECT_NEGATIVE, }; enum { QUALITY_NORMAL, QUALITY_GENUINE, QUALITY_RARITY2, QUALITY_VINTAGE, QUALITY_RARITY3, QUALITY_UNUSUAL, QUALITY_UNIQUE, QUALITY_COMMUNITY, QUALITY_VALVE, QUALITY_SELFMADE, QUALITY_CUSTOMIZED, QUALITY_STRANGE, QUALITY_COMPLETED, QUALITY_HUNTED, QUALITY_COLLECTOR, QUALITY_DECORATED, }; extern const char *g_szQualityColorStrings[]; extern const char *g_szQualityLocalizationStrings[]; #define CALL_ATTRIB_HOOK_INT(value, name) \ value = CAttributeManager::AttribHookValue<int>(value, #name, this) #define CALL_ATTRIB_HOOK_FLOAT(value, name) \ value = CAttributeManager::AttribHookValue<float>(value, #name, this) #define CALL_ATTRIB_HOOK_STRING(value, name) \ value = CAttributeManager::AttribHookValue<string_t>(value, #name, this) #define CALL_ATTRIB_HOOK_INT_ON_OTHER(ent, value, name) \ value = CAttributeManager::AttribHookValue<int>(value, #name, ent) #define CALL_ATTRIB_HOOK_FLOAT_ON_OTHER(ent, value, name) \ value = CAttributeManager::AttribHookValue<float>(value, #name, ent) #define CALL_ATTRIB_HOOK_STRING_ON_OTHER(ent, value, name) \ value = CAttributeManager::AttribHookValue<string_t>(value, #name, ent) #define CLEAR_STR(name) \ name[0] = '\0' struct EconQuality { EconQuality() { value = 0; } int value; }; struct EconColor { EconColor() { CLEAR_STR(color_name); } char color_name[128]; }; struct EconAttributeDefinition { EconAttributeDefinition() { CLEAR_STR(name); CLEAR_STR(attribute_class); CLEAR_STR(description_string); string_attribute = false; description_format = -1; hidden = false; effect_type = -1; stored_as_integer = false; } char name[128]; char attribute_class[128]; char description_string[128]; bool string_attribute; int description_format; int effect_type; bool hidden; bool stored_as_integer; }; // Live TF2 uses flags instead of view_model and world_model struct attachedmodel_t { char attachment[128]; // not sure what this does char model[128]; int view_model; int world_model; }; // Client specific. #ifdef CLIENT_DLL EXTERN_RECV_TABLE( DT_EconItemAttribute ); // Server specific. #else EXTERN_SEND_TABLE( DT_EconItemAttribute ); #endif class CEconItemAttribute { public: DECLARE_EMBEDDED_NETWORKVAR(); DECLARE_CLASS_NOBASE( CEconItemAttribute ); EconAttributeDefinition *GetStaticData( void ); CEconItemAttribute() { Init( -1, 0.0f ); } CEconItemAttribute( int iIndex, float flValue ) { Init( iIndex, flValue ); } CEconItemAttribute( int iIndex, float flValue, const char *pszAttributeClass ) { Init( iIndex, flValue, pszAttributeClass ); } CEconItemAttribute( int iIndex, const char *pszValue, const char *pszAttributeClass ) { Init( iIndex, pszValue, pszAttributeClass ); } void Init( int iIndex, float flValue, const char *pszAttributeClass = NULL ); void Init( int iIndex, const char *iszValue, const char *pszAttributeClass = NULL ); public: CNetworkVar( int, m_iAttributeDefinitionIndex ); CNetworkVar( float, value ); // m_iRawValue32 CNetworkString( value_string, 128 ); CNetworkString( attribute_class, 128 ); string_t m_strAttributeClass; }; struct EconItemStyle { EconItemStyle() { CLEAR_STR(name); CLEAR_STR(model_player); CLEAR_STR(image_inventory); skin_red = 0; skin_blu = 0; selectable = false; } int skin_red; int skin_blu; bool selectable; char name[128]; char model_player[128]; char image_inventory[128]; CUtlDict< const char*, unsigned short > model_player_per_class; }; class EconItemVisuals { public: EconItemVisuals(); public: CUtlDict< bool, unsigned short > player_bodygroups; CUtlMap< int, int > animation_replacement; CUtlDict< const char*, unsigned short > playback_activity; CUtlDict< const char*, unsigned short > misc_info; CUtlVector< attachedmodel_t > attached_models; char aWeaponSounds[NUM_SHOOT_SOUND_TYPES][MAX_WEAPON_STRING]; char custom_particlesystem[128]; //CUtlDict< EconItemStyle*, unsigned short > styles; }; class CEconItemDefinition { public: CEconItemDefinition() { CLEAR_STR(name); used_by_classes = 0; for ( int i = 0; i < TF_CLASS_COUNT_ALL; i++ ) item_slot_per_class[i] = -1; show_in_armory = false; CLEAR_STR(item_class); CLEAR_STR(item_type_name); CLEAR_STR(item_name); CLEAR_STR(item_description); item_slot = -1; anim_slot = -1; item_quality = QUALITY_NORMAL; baseitem = false; propername = false; CLEAR_STR(item_logname); CLEAR_STR(item_iconname); min_ilevel = 0; max_ilevel = 0; CLEAR_STR(image_inventory); image_inventory_size_w = 0; image_inventory_size_h = 0; CLEAR_STR(model_player); CLEAR_STR(model_world); memset( model_player_per_class, 0, sizeof( model_player_per_class ) ); attach_to_hands = 0; CLEAR_STR(extra_wearable); act_as_wearable = false; hide_bodygroups_deployed_only = 0; } EconItemVisuals *GetVisuals( int iTeamNum = TEAM_UNASSIGNED ); int GetLoadoutSlot( int iClass = TF_CLASS_UNDEFINED ); const wchar_t *GenerateLocalizedFullItemName( void ); const wchar_t *GenerateLocalizedItemNameNoQuality( void ); CEconItemAttribute *IterateAttributes( string_t strClass ); public: char name[128]; CUtlDict< bool, unsigned short > capabilities; CUtlDict< bool, unsigned short > tags; int used_by_classes; int item_slot_per_class[TF_CLASS_COUNT_ALL]; bool show_in_armory; char item_class[128]; char item_type_name[128]; char item_name[128]; char item_description[128]; int item_slot; int anim_slot; int item_quality; bool baseitem; bool propername; char item_logname[128]; char item_iconname[128]; int min_ilevel; int max_ilevel; char image_inventory[128]; int image_inventory_size_w; int image_inventory_size_h; char model_player[128]; char model_world[128]; char model_player_per_class[TF_CLASS_COUNT_ALL][128]; char extra_wearable[128]; int attach_to_hands; bool act_as_wearable; int hide_bodygroups_deployed_only; CUtlVector<CEconItemAttribute> attributes; EconItemVisuals visual[TF_TEAM_COUNT]; }; #endif // ECON_ITEM_SCHEMA_H <|start_filename|>src/game/server/tf/tf_obj_dispenser.cpp<|end_filename|> //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: Engineer's Dispenser // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "tf_obj_dispenser.h" #include "engine/IEngineSound.h" #include "tf_player.h" #include "tf_team.h" #include "vguiscreen.h" #include "world.h" #include "explode.h" #include "triggers.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" // Ground placed version #define DISPENSER_MODEL_PLACEMENT "models/buildables/dispenser_blueprint.mdl" // *_UPGRADE models are models used during the upgrade transition // Valve fucked up the naming of the models. the _light ones (which should be the transition models) // are actually the ones that are set AFTER the upgrade transition. #define DISPENSER_MODEL_LEVEL_1 "models/buildables/dispenser_light.mdl" #define DISPENSER_MODEL_LEVEL_1_UPGRADE "models/buildables/dispenser.mdl" #define DISPENSER_MODEL_LEVEL_2 "models/buildables/dispenser_lvl2_light.mdl" #define DISPENSER_MODEL_LEVEL_2_UPGRADE "models/buildables/dispenser_lvl2.mdl" #define DISPENSER_MODEL_LEVEL_3 "models/buildables/dispenser_lvl3_light.mdl" #define DISPENSER_MODEL_LEVEL_3_UPGRADE "models/buildables/dispenser_lvl3.mdl" #define DISPENSER_MINS Vector( -20, -20, 0 ) #define DISPENSER_MAXS Vector( 20, 20, 55 ) // tweak me #define DISPENSER_TRIGGER_MINS Vector( -70, -70, 0 ) #define DISPENSER_TRIGGER_MAXS Vector( 70, 70, 50 ) // tweak me #define REFILL_CONTEXT "RefillContext" #define DISPENSE_CONTEXT "DispenseContext" //----------------------------------------------------------------------------- // Purpose: SendProxy that converts the Healing list UtlVector to entindices //----------------------------------------------------------------------------- void SendProxy_HealingList( const SendProp *pProp, const void *pStruct, const void *pData, DVariant *pOut, int iElement, int objectID ) { CObjectDispenser *pDispenser = (CObjectDispenser*)pStruct; // If this assertion fails, then SendProxyArrayLength_HealingArray must have failed. Assert( iElement < pDispenser->m_hHealingTargets.Size() ); CBaseEntity *pEnt = pDispenser->m_hHealingTargets[iElement].Get(); EHANDLE hOther = pEnt; SendProxy_EHandleToInt( pProp, pStruct, &hOther, pOut, iElement, objectID ); } int SendProxyArrayLength_HealingArray( const void *pStruct, int objectID ) { CObjectDispenser *pDispenser = (CObjectDispenser*)pStruct; return pDispenser->m_hHealingTargets.Count(); } IMPLEMENT_SERVERCLASS_ST( CObjectDispenser, DT_ObjectDispenser ) SendPropInt( SENDINFO( m_iAmmoMetal ), 10 ), SendPropBool(SENDINFO(m_bStealthed)), SendPropArray2( SendProxyArrayLength_HealingArray, SendPropInt("healing_array_element", 0, SIZEOF_IGNORE, NUM_NETWORKED_EHANDLE_BITS, SPROP_UNSIGNED, SendProxy_HealingList), MAX_PLAYERS, 0, "healing_array" ) END_SEND_TABLE() BEGIN_DATADESC( CObjectDispenser ) DEFINE_KEYFIELD( m_szTriggerName, FIELD_STRING, "touch_trigger" ), DEFINE_THINKFUNC( RefillThink ), DEFINE_THINKFUNC( DispenseThink ), END_DATADESC() LINK_ENTITY_TO_CLASS( obj_dispenser, CObjectDispenser ); PRECACHE_REGISTER( obj_dispenser ); #define DISPENSER_MAX_HEALTH 150 // How much of each ammo gets added per refill #define DISPENSER_REFILL_METAL_AMMO 40 // How much ammo is given our per use #define DISPENSER_DROP_PRIMARY 40 #define DISPENSER_DROP_SECONDARY 40 #define DISPENSER_DROP_METAL 40 ConVar obj_dispenser_heal_rate( "obj_dispenser_heal_rate", "10.0", FCVAR_CHEAT |FCVAR_DEVELOPMENTONLY ); extern ConVar tf_cheapobjects; class CDispenserTouchTrigger : public CBaseTrigger { DECLARE_CLASS( CDispenserTouchTrigger, CBaseTrigger ); public: CDispenserTouchTrigger() {} void Spawn( void ) { BaseClass::Spawn(); AddSpawnFlags( SF_TRIGGER_ALLOW_CLIENTS ); InitTrigger(); } virtual void StartTouch( CBaseEntity *pEntity ) { CBaseEntity *pParent = GetOwnerEntity(); if ( pParent ) { pParent->StartTouch( pEntity ); } } virtual void EndTouch( CBaseEntity *pEntity ) { CBaseEntity *pParent = GetOwnerEntity(); if ( pParent ) { pParent->EndTouch( pEntity ); } } }; LINK_ENTITY_TO_CLASS( dispenser_touch_trigger, CDispenserTouchTrigger ); //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CObjectDispenser::CObjectDispenser() { SetMaxHealth( DISPENSER_MAX_HEALTH ); m_iHealth = DISPENSER_MAX_HEALTH; UseClientSideAnimation(); m_hTouchingEntities.Purge(); SetType( OBJ_DISPENSER ); } CObjectDispenser::~CObjectDispenser() { if ( m_hTouchTrigger.Get() ) { UTIL_Remove( m_hTouchTrigger ); } int iSize = m_hHealingTargets.Count(); for ( int i = iSize-1; i >= 0; i-- ) { EHANDLE hOther = m_hHealingTargets[i]; StopHealing( hOther ); } StopSound( "Building_Dispenser.Idle" ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CObjectDispenser::Spawn() { SetModel( GetPlacementModel() ); SetSolid( SOLID_BBOX ); UTIL_SetSize(this, DISPENSER_MINS, DISPENSER_MAXS); m_takedamage = DAMAGE_YES; m_iAmmoMetal = 0; m_bStealthed = false; m_flNextStealthThink = 0.0f; BaseClass::Spawn(); } void CObjectDispenser::MakeCarriedObject( CTFPlayer *pPlayer ) { StopSound( "Building_Dispenser.Idle" ); // Remove our healing trigger. if ( m_hTouchTrigger.Get() ) { UTIL_Remove( m_hTouchTrigger ); m_hTouchTrigger = NULL; } // Stop healing everyone. for ( int i = m_hTouchingEntities.Count() - 1; i >= 0; i-- ) { EHANDLE hEnt = m_hTouchingEntities[i]; CBaseEntity *pOther = hEnt.Get(); if ( pOther ) { EndTouch( pOther ); } } // Stop all thinking, we'll resume it once we get re-deployed. SetContextThink( NULL, 0, DISPENSE_CONTEXT ); SetContextThink( NULL, 0, REFILL_CONTEXT ); BaseClass::MakeCarriedObject( pPlayer ); } void CObjectDispenser::DropCarriedObject( CTFPlayer *pPlayer ) { BaseClass::DropCarriedObject( pPlayer ); } //----------------------------------------------------------------------------- // Purpose: Start building the object //----------------------------------------------------------------------------- bool CObjectDispenser::StartBuilding( CBaseEntity *pBuilder ) { SetModel( DISPENSER_MODEL_LEVEL_1_UPGRADE ); CreateBuildPoints(); return BaseClass::StartBuilding( pBuilder ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CObjectDispenser::InitializeMapPlacedObject( void ) { // Must set model here so we can add control panels. SetModel( DISPENSER_MODEL_LEVEL_1 ); BaseClass::InitializeMapPlacedObject(); } void CObjectDispenser::SetModel( const char *pModel ) { BaseClass::SetModel( pModel ); UTIL_SetSize( this, DISPENSER_MINS, DISPENSER_MAXS ); } //----------------------------------------------------------------------------- // Purpose: Finished building //----------------------------------------------------------------------------- void CObjectDispenser::OnGoActive( void ) { /* CTFPlayer *pBuilder = GetBuilder(); Assert( pBuilder ); if ( !pBuilder ) return; */ SetModel( DISPENSER_MODEL_LEVEL_1 ); CreateBuildPoints(); if ( !m_bCarryDeploy ) { // Put some ammo in the Dispenser m_iAmmoMetal = 25; } // Begin thinking SetContextThink( &CObjectDispenser::RefillThink, gpGlobals->curtime + 3, REFILL_CONTEXT ); SetContextThink( &CObjectDispenser::DispenseThink, gpGlobals->curtime + 0.1, DISPENSE_CONTEXT ); m_flNextAmmoDispense = gpGlobals->curtime + 0.5; CDispenserTouchTrigger *pTriggerEnt; if ( m_szTriggerName != NULL_STRING ) { pTriggerEnt = dynamic_cast< CDispenserTouchTrigger* >( gEntList.FindEntityByName( NULL, m_szTriggerName ) ); if ( pTriggerEnt ) { pTriggerEnt->SetOwnerEntity( this ); m_hTouchTrigger = pTriggerEnt; } } else { pTriggerEnt = dynamic_cast< CDispenserTouchTrigger* >( CBaseEntity::Create( "dispenser_touch_trigger", GetAbsOrigin(), vec3_angle, this ) ); if ( pTriggerEnt ) { pTriggerEnt->SetSolid( SOLID_BBOX ); UTIL_SetSize( pTriggerEnt, Vector( -70,-70,-70 ), Vector( 70,70,70 ) ); m_hTouchTrigger = pTriggerEnt; } } BaseClass::OnGoActive(); EmitSound( "Building_Dispenser.Idle" ); } //----------------------------------------------------------------------------- // Spawn the vgui control screens on the object //----------------------------------------------------------------------------- void CObjectDispenser::GetControlPanelInfo( int nPanelIndex, const char *&pPanelName ) { // Panels 0 and 1 are both control panels for now if ( nPanelIndex == 0 || nPanelIndex == 1 ) { switch (GetTeamNumber()) { case TF_TEAM_RED: pPanelName = "screen_obj_dispenser_red"; break; case TF_TEAM_BLUE: pPanelName = "screen_obj_dispenser_blue"; break; default: pPanelName = "screen_obj_dispenser_blue"; break; } } else { BaseClass::GetControlPanelInfo( nPanelIndex, pPanelName ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CObjectDispenser::Precache() { BaseClass::Precache(); int iModelIndex; PrecacheModel( DISPENSER_MODEL_PLACEMENT ); iModelIndex = PrecacheModel( DISPENSER_MODEL_LEVEL_1 ); PrecacheGibsForModel( iModelIndex ); iModelIndex = PrecacheModel( DISPENSER_MODEL_LEVEL_1_UPGRADE ); PrecacheGibsForModel( iModelIndex ); iModelIndex = PrecacheModel( DISPENSER_MODEL_LEVEL_2 ); PrecacheGibsForModel(iModelIndex); iModelIndex = PrecacheModel( DISPENSER_MODEL_LEVEL_2_UPGRADE ); PrecacheGibsForModel(iModelIndex); iModelIndex = PrecacheModel( DISPENSER_MODEL_LEVEL_3 ); PrecacheGibsForModel(iModelIndex); iModelIndex = PrecacheModel( DISPENSER_MODEL_LEVEL_3_UPGRADE ); PrecacheGibsForModel(iModelIndex); PrecacheVGuiScreen( "screen_obj_dispenser_blue" ); PrecacheVGuiScreen( "screen_obj_dispenser_red" ); PrecacheVGuiScreen( "screen_obj_dispenser_green" ); PrecacheVGuiScreen( "screen_obj_dispenser_yellow" ); PrecacheScriptSound( "Building_Dispenser.Idle" ); PrecacheScriptSound( "Building_Dispenser.GenerateMetal" ); PrecacheScriptSound( "Building_Dispenser.Heal" ); PrecacheTeamParticles("dispenser_heal_%s"); } #define DISPENSER_UPGRADE_DURATION 1.5f //----------------------------------------------------------------------------- // Hit by a friendly engineer's wrench //----------------------------------------------------------------------------- bool CObjectDispenser::OnWrenchHit( CTFPlayer *pPlayer, CTFWrench *pWrench, Vector vecHitPos ) { bool bDidWork = false; bDidWork = BaseClass::OnWrenchHit( pPlayer, pWrench, vecHitPos ); return bDidWork; } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- bool CObjectDispenser::IsUpgrading( void ) const { return m_bIsUpgrading; } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- char *CObjectDispenser::GetPlacementModel( void ) { return DISPENSER_MODEL_PLACEMENT; } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- int CObjectDispenser::GetMaxUpgradeLevel(void) { return 3; } //----------------------------------------------------------------------------- // If detonated, do some damage //----------------------------------------------------------------------------- void CObjectDispenser::DetonateObject( void ) { /* float flDamage = min( 100 + m_iAmmoMetal, 250 ); ExplosionCreate( GetAbsOrigin(), GetAbsAngles(), GetBuilder(), flDamage, //magnitude flDamage, //radius 0, 0.0f, //explosion force this, //inflictor DMG_BLAST | DMG_HALF_FALLOFF); */ BaseClass::DetonateObject(); } //----------------------------------------------------------------------------- // Handle commands sent from vgui panels on the client //----------------------------------------------------------------------------- bool CObjectDispenser::ClientCommand( CTFPlayer *pPlayer, const CCommand &args ) { const char *pCmd = args[0]; if ( FStrEq( pCmd, "use" ) ) { // I can't do anything if I'm not active if ( !ShouldBeActive() ) return true; // player used the dispenser if ( DispenseAmmo( pPlayer ) ) { CSingleUserRecipientFilter filter( pPlayer ); pPlayer->EmitSound( filter, pPlayer->entindex(), "BaseCombatCharacter.AmmoPickup" ); } return true; } else if ( FStrEq( pCmd, "repair" ) ) { Command_Repair( pPlayer ); return true; } return BaseClass::ClientCommand( pPlayer, args ); } //----------------------------------------------------------------------------- // Raises the dispenser one level //----------------------------------------------------------------------------- void CObjectDispenser::StartUpgrading( void ) { ResetHealingTargets(); BaseClass::StartUpgrading(); switch( GetUpgradeLevel() ) { case 1: SetModel( DISPENSER_MODEL_LEVEL_1_UPGRADE ); break; case 2: SetModel( DISPENSER_MODEL_LEVEL_2_UPGRADE ); break; case 3: SetModel( DISPENSER_MODEL_LEVEL_3_UPGRADE ); break; default: Assert(0); break; } m_bIsUpgrading = true; // Start upgrade anim instantly DetermineAnimation(); } void CObjectDispenser::FinishUpgrading( void ) { switch( GetUpgradeLevel() ) { case 1: SetModel( DISPENSER_MODEL_LEVEL_1 ); break; case 2: SetModel( DISPENSER_MODEL_LEVEL_2 ); break; case 3: SetModel( DISPENSER_MODEL_LEVEL_3 ); break; default: Assert(0); break; } m_bIsUpgrading = false; SetActivity( ACT_RESET ); BaseClass::FinishUpgrading(); } bool CObjectDispenser::DispenseAmmo( CTFPlayer *pPlayer ) { int iTotalPickedUp = 0; float flAmmoRate = g_flDispenserAmmoRates[GetUpgradeLevel() - 1]; // primary int iPrimary = pPlayer->GiveAmmo( floor( pPlayer->GetMaxAmmo( TF_AMMO_PRIMARY ) * flAmmoRate ), TF_AMMO_PRIMARY, false, TF_AMMO_SOURCE_DISPENSER ); iTotalPickedUp += iPrimary; // secondary int iSecondary = pPlayer->GiveAmmo( floor( pPlayer->GetMaxAmmo( TF_AMMO_SECONDARY ) * flAmmoRate ), TF_AMMO_SECONDARY, false, TF_AMMO_SOURCE_DISPENSER ); iTotalPickedUp += iSecondary; // Cart dispenser has infinite metal. int iMetalToGive = DISPENSER_DROP_METAL + 10 * ( GetUpgradeLevel() - 1 ); if ( ( GetObjectFlags() & OF_IS_CART_OBJECT ) == 0 ) iMetalToGive = min( m_iAmmoMetal, iMetalToGive ); int iMetal = pPlayer->GiveAmmo( iMetalToGive, TF_AMMO_METAL, false, TF_AMMO_SOURCE_DISPENSER ); iTotalPickedUp += iMetal; if ( ( GetObjectFlags() & OF_IS_CART_OBJECT ) == 0 ) m_iAmmoMetal -= iMetal; if ( iTotalPickedUp > 0 ) { if (pPlayer->m_Shared.InCond(TF_COND_STEALTHED)) { CRecipientFilter filter; filter.AddRecipient(pPlayer); EmitSound(filter, entindex(), "BaseCombatCharacter.AmmoPickup"); } else EmitSound( "BaseCombatCharacter.AmmoPickup" ); return true; } // return false if we didn't pick up anything return false; } int CObjectDispenser::GetBaseHealth( void ) { return DISPENSER_MAX_HEALTH; } float CObjectDispenser::GetDispenserRadius( void ) { float flRadius = 64.0f; if ( GetOwner() ) CALL_ATTRIB_HOOK_FLOAT_ON_OTHER( GetOwner(), flRadius, mult_dispenser_radius ); return flRadius; } float CObjectDispenser::GetHealRate( void ) { return g_flDispenserHealRates[ GetUpgradeLevel() - 1 ]; } void CObjectDispenser::RefillThink( void ) { if ( GetObjectFlags() & OF_IS_CART_OBJECT ) return; if ( IsDisabled() || IsUpgrading() || IsRedeploying() ) { // Hit a refill time while disabled, so do the next refill ASAP. SetContextThink( &CObjectDispenser::RefillThink, gpGlobals->curtime + 0.1, REFILL_CONTEXT ); return; } // Auto-refill half the amount as tfc, but twice as often if ( m_iAmmoMetal < DISPENSER_MAX_METAL_AMMO ) { m_iAmmoMetal = min( m_iAmmoMetal + DISPENSER_MAX_METAL_AMMO * ( 0.1 + 0.025 * ( GetUpgradeLevel() - 1 ) ), DISPENSER_MAX_METAL_AMMO ); EmitSound( "Building_Dispenser.GenerateMetal" ); } SetContextThink( &CObjectDispenser::RefillThink, gpGlobals->curtime + 6, REFILL_CONTEXT ); } //----------------------------------------------------------------------------- // Generate ammo over time //----------------------------------------------------------------------------- void CObjectDispenser::DispenseThink( void ) { if ( IsDisabled() || IsUpgrading() || IsRedeploying() ) { // Don't heal or dispense ammo SetContextThink( &CObjectDispenser::DispenseThink, gpGlobals->curtime + 0.1, DISPENSE_CONTEXT ); // stop healing everyone for ( int i=m_hHealingTargets.Count()-1; i>=0; i-- ) { EHANDLE hEnt = m_hHealingTargets[i]; CBaseEntity *pOther = hEnt.Get(); if ( pOther ) { StopHealing( pOther ); } } return; } if ( m_flNextAmmoDispense <= gpGlobals->curtime ) { int iNumNearbyPlayers = 0; // find players in sphere, that are visible static float flRadius = GetDispenserRadius(); Vector vecOrigin = GetAbsOrigin() + Vector(0,0,32); CBaseEntity *pListOfNearbyEntities[32]; int iNumberOfNearbyEntities = UTIL_EntitiesInSphere( pListOfNearbyEntities, 32, vecOrigin, flRadius, FL_CLIENT ); for (int i=0;i<iNumberOfNearbyEntities;i++ ) { CTFPlayer *pPlayer = ToTFPlayer( pListOfNearbyEntities[i] ); if ( !pPlayer || !pPlayer->IsAlive() || !CouldHealTarget(pPlayer) ) continue; DispenseAmmo( pPlayer ); iNumNearbyPlayers++; } // Try to dispense more often when no players are around so we // give it as soon as possible when a new player shows up m_flNextAmmoDispense = gpGlobals->curtime + ( ( iNumNearbyPlayers > 0 ) ? 1.0 : 0.1 ); } ResetHealingTargets(); SetContextThink( &CObjectDispenser::DispenseThink, gpGlobals->curtime + 0.1, DISPENSE_CONTEXT ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CObjectDispenser::ResetHealingTargets( void ) { // for each player in touching list int iSize = m_hTouchingEntities.Count(); for (int i = iSize - 1; i >= 0; i--) { EHANDLE hOther = m_hTouchingEntities[i]; CBaseEntity *pEnt = hOther.Get(); bool bHealingTarget = IsHealingTarget(pEnt); bool bValidHealTarget = CouldHealTarget(pEnt); CTFPlayer *pPlayer; pPlayer = ToTFPlayer(pEnt); if (pPlayer) { if (pPlayer->m_Shared.InCond(TF_COND_STEALTHED) && m_flNextStealthThink < gpGlobals->curtime) { m_bStealthed = true; NetworkStateChanged(); m_flNextStealthThink = gpGlobals->curtime + 1.0f; } } if ( bHealingTarget && !bValidHealTarget ) { // if we can't see them, remove them from healing list // does nothing if we are not healing them already StopHealing( pEnt ); } else if ( !bHealingTarget && bValidHealTarget ) { // if we can see them, add to healing list // does nothing if we are healing them already StartHealing( pEnt ); } } if (m_flNextStealthThink < gpGlobals->curtime) { if (m_bStealthed) NetworkStateChanged(); m_bStealthed = false; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CObjectDispenser::StartTouch( CBaseEntity *pOther ) { // add to touching entities EHANDLE hOther = pOther; m_hTouchingEntities.AddToTail( hOther ); if ( !IsBuilding() && !IsDisabled() && !IsRedeploying() && CouldHealTarget( pOther ) && !IsHealingTarget( pOther ) ) { // try to start healing them StartHealing( pOther ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CObjectDispenser::EndTouch( CBaseEntity *pOther ) { // remove from touching entities EHANDLE hOther = pOther; m_hTouchingEntities.FindAndRemove( hOther ); // remove from healing list StopHealing( pOther ); } //----------------------------------------------------------------------------- // Purpose: Try to start healing this target //----------------------------------------------------------------------------- void CObjectDispenser::StartHealing( CBaseEntity *pOther ) { AddHealingTarget( pOther ); CTFPlayer *pPlayer = ToTFPlayer( pOther ); if ( pPlayer ) { pPlayer->m_Shared.Heal( GetOwner(), GetHealRate(), true ); } } //----------------------------------------------------------------------------- // Purpose: Stop healing this target //----------------------------------------------------------------------------- void CObjectDispenser::StopHealing( CBaseEntity *pOther ) { bool bFound = false; EHANDLE hOther = pOther; bFound = m_hHealingTargets.FindAndRemove( hOther ); NetworkStateChanged(); if ( bFound ) { CTFPlayer *pPlayer = ToTFPlayer( pOther ); if ( pPlayer ) { pPlayer->m_Shared.StopHealing( GetOwner() ); } } } //----------------------------------------------------------------------------- // Purpose: Is this a valid heal target? and not already healing them? //----------------------------------------------------------------------------- bool CObjectDispenser::CouldHealTarget( CBaseEntity *pTarget ) { if ( !HasSpawnFlags( SF_IGNORE_LOS ) && !pTarget->FVisible( this, MASK_BLOCKLOS ) ) return false; if ( pTarget->IsPlayer() && pTarget->IsAlive() ) { CTFPlayer *pTFPlayer = ToTFPlayer( pTarget ); // don't heal enemies unless they are disguised as our team int iTeam = GetTeamNumber(); int iPlayerTeam = pTFPlayer->GetTeamNumber(); if ( iPlayerTeam != iTeam && pTFPlayer->m_Shared.InCond( TF_COND_DISGUISED ) && !HasSpawnFlags( SF_NO_DISGUISED_SPY_HEALING ) ) { iPlayerTeam = pTFPlayer->m_Shared.GetDisguiseTeam(); } if ( iPlayerTeam != iTeam ) { return false; } return true; } return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CObjectDispenser::AddHealingTarget( CBaseEntity *pOther ) { // add to tail EHANDLE hOther = pOther; m_hHealingTargets.AddToTail( hOther ); NetworkStateChanged(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CObjectDispenser::RemoveHealingTarget( CBaseEntity *pOther ) { // remove EHANDLE hOther = pOther; m_hHealingTargets.FindAndRemove( hOther ); } //----------------------------------------------------------------------------- // Purpose: Are we healing this target already //----------------------------------------------------------------------------- bool CObjectDispenser::IsHealingTarget( CBaseEntity *pTarget ) { EHANDLE hOther = pTarget; return m_hHealingTargets.HasElement( hOther ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CObjectDispenser::DrawDebugTextOverlays( void ) { int text_offset = BaseClass::DrawDebugTextOverlays(); if (m_debugOverlays & OVERLAY_TEXT_BIT) { char tempstr[512]; Q_snprintf( tempstr, sizeof( tempstr ),"Metal: %d", m_iAmmoMetal ); EntityText(text_offset,tempstr,0); text_offset++; } return text_offset; } IMPLEMENT_SERVERCLASS_ST( CObjectCartDispenser, DT_ObjectCartDispenser ) END_SEND_TABLE() BEGIN_DATADESC( CObjectCartDispenser ) DEFINE_KEYFIELD( m_szTriggerName, FIELD_STRING, "touch_trigger" ), END_DATADESC() LINK_ENTITY_TO_CLASS( mapobj_cart_dispenser, CObjectCartDispenser ); //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CObjectCartDispenser::Spawn( void ) { SetObjectFlags( OF_IS_CART_OBJECT ); m_takedamage = DAMAGE_NO; m_iUpgradeLevel = 1; m_iUpgradeMetal = 0; AddFlag( FL_OBJECT ); m_iAmmoMetal = 0; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CObjectCartDispenser::SetModel( const char *pModel ) { // Deliberately skip dispenser since it has some stuff we don't want. CBaseObject::SetModel( pModel ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CObjectCartDispenser::OnGoActive( void ) { // Hacky: base class needs a model to init some things properly so we gotta clear it here. BaseClass::OnGoActive(); SetModel( "" ); } <|start_filename|>src/game/shared/tf/tf_projectile_arrow.cpp<|end_filename|> //=============================================================================// // // Purpose: // //=============================================================================// #include "cbase.h" #include "tf_projectile_arrow.h" #include "effect_dispatch_data.h" #ifdef GAME_DLL #include "SpriteTrail.h" #include "props_shared.h" #include "debugoverlay_shared.h" #include "te_effect_dispatch.h" #include "decals.h" #include "bone_setup.h" #endif #ifdef GAME_DLL ConVar tf_debug_arrows( "tf_debug_arrows", "0", FCVAR_CHEAT ); #endif const char *g_pszArrowModels[] = { "models/weapons/w_models/w_arrow.mdl", "models/weapons/w_models/w_syringe_proj.mdl", "models/weapons/w_models/w_repair_claw.mdl", //"models/weapons/w_models/w_arrow_xmas.mdl", }; IMPLEMENT_NETWORKCLASS_ALIASED( TFProjectile_Arrow, DT_TFProjectile_Arrow ) BEGIN_NETWORK_TABLE( CTFProjectile_Arrow, DT_TFProjectile_Arrow ) #ifdef CLIENT_DLL RecvPropBool( RECVINFO( m_bCritical ) ), RecvPropBool( RECVINFO( m_bFlame ) ), RecvPropInt( RECVINFO( m_iType ) ), #else SendPropBool( SENDINFO( m_bCritical ) ), SendPropBool( SENDINFO( m_bFlame ) ), SendPropInt( SENDINFO( m_iType ), 3, SPROP_UNSIGNED ), #endif END_NETWORK_TABLE() #ifdef GAME_DLL BEGIN_DATADESC( CTFProjectile_Arrow ) DEFINE_ENTITYFUNC( ArrowTouch ) END_DATADESC() #endif LINK_ENTITY_TO_CLASS( tf_projectile_arrow, CTFProjectile_Arrow ); PRECACHE_REGISTER( tf_projectile_arrow ); CTFProjectile_Arrow::CTFProjectile_Arrow() { } CTFProjectile_Arrow::~CTFProjectile_Arrow() { #ifdef CLIENT_DLL ParticleProp()->StopEmission(); bEmitting = false; #else m_bCollideWithTeammates = false; #endif } #ifdef GAME_DLL CTFProjectile_Arrow *CTFProjectile_Arrow::Create( CBaseEntity *pWeapon, const Vector &vecOrigin, const QAngle &vecAngles, float flSpeed, float flGravity, bool bFlame, CBaseEntity *pOwner, CBaseEntity *pScorer, int iType ) { CTFProjectile_Arrow *pArrow = static_cast<CTFProjectile_Arrow *>( CBaseEntity::CreateNoSpawn( "tf_projectile_arrow", vecOrigin, vecAngles, pOwner ) ); if ( pArrow ) { // Set team. pArrow->ChangeTeam( pOwner->GetTeamNumber() ); // Set scorer. pArrow->SetScorer( pScorer ); // Set firing weapon. pArrow->SetLauncher( pWeapon ); // Set arrow type. pArrow->SetType( iType ); // Set flame arrow. pArrow->SetFlameArrow( bFlame ); // Spawn. DispatchSpawn( pArrow ); // Setup the initial velocity. Vector vecForward, vecRight, vecUp; AngleVectors( vecAngles, &vecForward, &vecRight, &vecUp ); CALL_ATTRIB_HOOK_FLOAT_ON_OTHER( pWeapon, flSpeed, mult_projectile_speed ); Vector vecVelocity = vecForward * flSpeed; pArrow->SetAbsVelocity( vecVelocity ); pArrow->SetupInitialTransmittedGrenadeVelocity( vecVelocity ); // Setup the initial angles. QAngle angles; VectorAngles( vecVelocity, angles ); pArrow->SetAbsAngles( angles ); pArrow->SetGravity( flGravity ); return pArrow; } return pArrow; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFProjectile_Arrow::Precache( void ) { // Precache all arrow models we have. for ( int i = 0; i < ARRAYSIZE( g_pszArrowModels ); i++ ) { int iIndex = PrecacheModel( g_pszArrowModels[i] ); PrecacheGibsForModel( iIndex ); } for ( int i = FIRST_GAME_TEAM; i < TF_TEAM_COUNT; i++ ) { PrecacheModel( ConstructTeamParticle( "effects/arrowtrail_%s.vmt", i, false, g_aTeamNamesShort ) ); PrecacheModel( ConstructTeamParticle( "effects/healingtrail_%s.vmt", i, false, g_aTeamNamesShort ) ); PrecacheModel( ConstructTeamParticle( "effects/repair_claw_trail_%s.vmt", i, false, g_aTeamParticleNames ) ); } // Precache flame effects PrecacheParticleSystem( "flying_flaming_arrow" ); PrecacheScriptSound( "Weapon_Arrow.ImpactFlesh" ); PrecacheScriptSound( "Weapon_Arrow.ImpactMetal" ); PrecacheScriptSound( "Weapon_Arrow.ImpactWood" ); PrecacheScriptSound( "Weapon_Arrow.ImpactConcrete" ); PrecacheScriptSound( "Weapon_Arrow.Nearmiss" ); BaseClass::Precache(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFProjectile_Arrow::Spawn( void ) { switch ( m_iType ) { case TF_PROJECTILE_BUILDING_REPAIR_BOLT: SetModel( g_pszArrowModels[2] ); break; case TF_PROJECTILE_HEALING_BOLT: case TF_PROJECTILE_FESTITIVE_HEALING_BOLT: SetModel( g_pszArrowModels[1] ); break; default: SetModel( g_pszArrowModels[0] ); break; } BaseClass::Spawn(); #ifdef TF_ARROW_FIX SetSolidFlags( FSOLID_NOT_SOLID | FSOLID_TRIGGER ); #endif SetMoveType( MOVETYPE_FLYGRAVITY, MOVECOLLIDE_FLY_CUSTOM ); SetGravity( 0.3f ); // TODO: Check again later. UTIL_SetSize( this, -Vector( 1, 1, 1 ), Vector( 1, 1, 1 ) ); CreateTrail(); SetTouch( &CTFProjectile_Arrow::ArrowTouch ); SetThink(&CTFProjectile_Arrow::FlyThink); SetNextThink(gpGlobals->curtime); // TODO: Set skin here... } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFProjectile_Arrow::SetScorer( CBaseEntity *pScorer ) { m_Scorer = pScorer; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CBasePlayer *CTFProjectile_Arrow::GetScorer( void ) { return dynamic_cast<CBasePlayer *>( m_Scorer.Get() ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFProjectile_Arrow::ArrowTouch( CBaseEntity *pOther ) { // Verify a correct "other." Assert( pOther ); if ( pOther->IsSolidFlagSet( FSOLID_TRIGGER | FSOLID_VOLUME_CONTENTS ) ) { return; } // Handle hitting skybox (disappear). trace_t *pTrace = const_cast<trace_t *>( &CBaseEntity::GetTouchTrace() ); if ( pTrace->surface.flags & SURF_SKY ) { UTIL_Remove( this ); return; } // Invisible. SetModelName( NULL_STRING ); AddSolidFlags( FSOLID_NOT_SOLID ); m_takedamage = DAMAGE_NO; // Damage. CBaseEntity *pAttacker = GetOwnerEntity(); IScorer *pScorerInterface = dynamic_cast<IScorer*>( pAttacker ); if ( pScorerInterface ) { pAttacker = pScorerInterface->GetScorer(); } Vector vecOrigin = GetAbsOrigin(); Vector vecDir = GetAbsVelocity(); CTFPlayer *pPlayer = ToTFPlayer( pOther ); CTFWeaponBase *pWeapon = dynamic_cast<CTFWeaponBase *>( m_hLauncher.Get() ); trace_t trHit, tr; trHit = *pTrace; const char* pszImpactSound = NULL; bool bPlayerImpact = false; if ( pPlayer ) { // Determine where we should land Vector vecDir = GetAbsVelocity(); VectorNormalizeFast( vecDir ); CStudioHdr *pStudioHdr = pPlayer->GetModelPtr(); if ( !pStudioHdr ) return; mstudiohitboxset_t *set = pStudioHdr->pHitboxSet( pPlayer->GetHitboxSet() ); if ( !set ) return; // Oh boy... we gotta figure out the closest hitbox on player model to land a hit on. QAngle angHit; float flClosest = FLT_MAX; mstudiobbox_t *pBox = NULL, *pCurrentBox = NULL; //int bone = -1; //int group = 0; //Msg( "\nNum of Hitboxes: %i", set->numhitboxes ); for ( int i = 0; i < set->numhitboxes; i++ ) { pCurrentBox = set->pHitbox( i ); //Msg( "\nGroup: %i", pBox->group ); Vector boxPosition; QAngle boxAngles; pPlayer->GetBonePosition( pCurrentBox->bone, boxPosition, boxAngles ); Vector vecCross = CrossProduct( vecOrigin + vecDir * 16, boxPosition ); trace_t tr; UTIL_TraceLine( vecOrigin, boxPosition, MASK_SHOT, this, COLLISION_GROUP_NONE, &tr ); float flLengthSqr = ( boxPosition - vecCross ).LengthSqr(); if ( flLengthSqr < flClosest ) { //Msg( "\nCLOSER: %i", pBox->group ); //group = pBox->group; flClosest = flLengthSqr; trHit = tr; pBox = pCurrentBox; } } //Msg("\nClosest: %i\n", group); if ( tf_debug_arrows.GetBool() ) { //Msg("\nHitBox: %i\nHitgroup: %i\n", trHit.hitbox, trHit.hitgroup); NDebugOverlay::Line( trHit.startpos, trHit.endpos, 0, 255, 0, true, 5.0f ); NDebugOverlay::Line( vecOrigin, vecOrigin + vecDir * 16, 255, 0, 0, true, 5.0f ); } pszImpactSound = "Weapon_Arrow.ImpactFlesh"; bPlayerImpact = true; if ( !PositionArrowOnBone( pBox , pPlayer ) ) { // This shouldn't happen UTIL_Remove( this ); return; } Vector vecOrigin; QAngle vecAngles; int bone, iPhysicsBone; GetBoneAttachmentInfo( pBox, pPlayer, vecOrigin, vecAngles, bone, iPhysicsBone ); // TODO: Redo the whole "BoltImpact" logic // CTFProjectile_Arrow::CheckRagdollPinned if( GetDamage() > pPlayer->GetHealth() ) { // pPlayer->StopRagdollDeathAnim(); Vector vForward; AngleVectors( GetAbsAngles(), &vForward ); VectorNormalize ( vForward ); UTIL_TraceLine( GetAbsOrigin(), GetAbsOrigin() + vForward * 256, MASK_BLOCKLOS, pOther, COLLISION_GROUP_NONE, &tr ); if ( tr.fraction != 1.0f ) { //NDebugOverlay::Box( tr.endpos, Vector( -16, -16, -16 ), Vector( 16, 16, 16 ), 0, 255, 0, 0, 10 ); //NDebugOverlay::Box( GetAbsOrigin(), Vector( -16, -16, -16 ), Vector( 16, 16, 16 ), 0, 0, 255, 0, 10 ); if ( tr.m_pEnt == NULL || ( tr.m_pEnt && tr.m_pEnt->GetMoveType() == MOVETYPE_NONE ) ) { CEffectData data; data.m_vOrigin = tr.endpos; data.m_vNormal = vForward; data.m_nEntIndex = tr.fraction != 1.0f; DispatchEffect( "BoltImpact", data ); } } } else { IGameEvent *event = gameeventmanager->CreateEvent( "arrow_impact" ); if ( event ) { event->SetInt( "attachedEntity", pOther->entindex() ); event->SetInt( "shooter", pAttacker->entindex() ); event->SetInt( "boneIndexAttached", bone ); event->SetFloat( "bonePositionX", vecOrigin.x ); event->SetFloat( "bonePositionY", vecOrigin.y ); event->SetFloat( "bonePositionZ", vecOrigin.z ); event->SetFloat( "boneAnglesX", vecAngles.x ); event->SetFloat( "boneAnglesY", vecAngles.y ); event->SetFloat( "boneAnglesZ", vecAngles.z ); gameeventmanager->FireEvent( event ); } } } else if ( pOther->GetMoveType() == MOVETYPE_NONE ) { surfacedata_t *psurfaceData = physprops->GetSurfaceData( trHit.surface.surfaceProps ); int iMaterial = psurfaceData->game.material; bool bArrowSound = false; if ( ( iMaterial == CHAR_TEX_CONCRETE ) || ( iMaterial == CHAR_TEX_TILE ) ) { pszImpactSound = "Weapon_Arrow.ImpactConcrete"; bArrowSound = true; } else if ( iMaterial == CHAR_TEX_WOOD ) { pszImpactSound = "Weapon_Arrow.ImpactWood"; bArrowSound = true; } else if ( ( iMaterial == CHAR_TEX_METAL ) || ( iMaterial == CHAR_TEX_VENT ) ) { pszImpactSound = "Weapon_Arrow.ImpactMetal"; bArrowSound = true; } Vector vForward; AngleVectors( GetAbsAngles(), &vForward ); VectorNormalize ( vForward ); UTIL_TraceLine( GetAbsOrigin(), GetAbsOrigin() + vForward * 256, MASK_BLOCKLOS, pOther, COLLISION_GROUP_NONE, &tr ); if ( tr.fraction != 1.0f ) { //NDebugOverlay::Box( tr.endpos, Vector( -16, -16, -16 ), Vector( 16, 16, 16 ), 0, 255, 0, 0, 10 ); //NDebugOverlay::Box( GetAbsOrigin(), Vector( -16, -16, -16 ), Vector( 16, 16, 16 ), 0, 0, 255, 0, 10 ); if ( tr.m_pEnt == NULL || ( tr.m_pEnt && tr.m_pEnt->GetMoveType() == MOVETYPE_NONE ) ) { CEffectData data; data.m_vOrigin = tr.endpos; data.m_vNormal = vForward; data.m_nEntIndex = tr.fraction != 1.0f; DispatchEffect( "BoltImpact", data ); } } // If we didn't play a collision sound already, play a bullet collision sound for this prop if( !bArrowSound ) { UTIL_ImpactTrace( &trHit, DMG_BULLET ); } else { UTIL_ImpactTrace( &trHit, DMG_BULLET, "ImpactArrow" ); } //UTIL_Remove( this ); } else { // TODO: Figure out why arrow gibs sometimes cause crashes //BreakArrow(); UTIL_Remove( this ); } // Play sound if ( pszImpactSound ) { PlayImpactSound( ToTFPlayer( pAttacker ), pszImpactSound, bPlayerImpact ); } int iCustomDamage = m_bFlame ? TF_DMG_CUSTOM_BURNING_ARROW : TF_DMG_CUSTOM_NONE; // Do damage. CTakeDamageInfo info( this, pAttacker, pWeapon, GetDamage(), GetDamageType(), iCustomDamage ); CalculateBulletDamageForce( &info, pWeapon ? pWeapon->GetTFWpnData().iAmmoType : 0, vecDir, vecOrigin ); info.SetReportedPosition( pAttacker ? pAttacker->GetAbsOrigin() : vec3_origin ); pOther->DispatchTraceAttack( info, vecDir, &trHit ); ApplyMultiDamage(); // Remove. UTIL_Remove( this ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFProjectile_Arrow::FlyThink(void) { QAngle angles; VectorAngles(GetAbsVelocity(), angles); SetAbsAngles(angles); SetNextThink(gpGlobals->curtime + 0.1f); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CTFProjectile_Arrow::GetDamageType() { int iDmgType = BaseClass::GetDamageType(); // Buff banner mini-crit calculations CTFWeaponBase *pWeapon = ( CTFWeaponBase * )m_hLauncher.Get(); if ( pWeapon ) { pWeapon->CalcIsAttackMiniCritical(); if ( pWeapon->IsCurrentAttackAMiniCrit() ) { iDmgType |= DMG_MINICRITICAL; } } if ( m_bCritical ) { iDmgType |= DMG_CRITICAL; } if ( CanHeadshot() ) { iDmgType |= DMG_USE_HITLOCATIONS; } if ( m_bFlame == true ) { iDmgType |= DMG_IGNITE; } if ( m_iDeflected > 0 ) { iDmgType |= DMG_MINICRITICAL; } return iDmgType; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFProjectile_Arrow::Deflected( CBaseEntity *pDeflectedBy, Vector &vecDir ) { // Get arrow's speed. float flVel = GetAbsVelocity().Length(); QAngle angForward; VectorAngles( vecDir, angForward ); // Now change arrow's direction. SetAbsAngles( angForward ); SetAbsVelocity( vecDir * flVel ); // And change owner. IncremenentDeflected(); SetOwnerEntity( pDeflectedBy ); ChangeTeam( pDeflectedBy->GetTeamNumber() ); SetScorer( pDeflectedBy ); // Change trail color. if ( m_hSpriteTrail.Get() ) { UTIL_Remove( m_hSpriteTrail.Get() ); } CreateTrail(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CTFProjectile_Arrow::CanHeadshot( void ) { return ( m_iType == TF_PROJECTILE_ARROW || m_iType == TF_PROJECTILE_FESTITIVE_ARROW ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- const char *CTFProjectile_Arrow::GetTrailParticleName( void ) { const char *pszFormat = NULL; bool bLongTeamName = false; switch( m_iType ) { case TF_PROJECTILE_BUILDING_REPAIR_BOLT: pszFormat = "effects/repair_claw_trail_%s.vmt"; bLongTeamName = true; break; case TF_PROJECTILE_HEALING_BOLT: case TF_PROJECTILE_FESTITIVE_HEALING_BOLT: pszFormat = "effects/healingtrail_%s.vmt"; break; default: pszFormat = "effects/arrowtrail_%s.vmt"; break; } return ConstructTeamParticle( pszFormat, GetTeamNumber(), false, bLongTeamName ? g_aTeamParticleNames : g_aTeamNamesShort ); } // ---------------------------------------------------------------------------- - // Purpose: //----------------------------------------------------------------------------- void CTFProjectile_Arrow::CreateTrail( void ) { CSpriteTrail *pTrail = CSpriteTrail::SpriteTrailCreate( GetTrailParticleName(), GetAbsOrigin(), true ); if ( pTrail ) { pTrail->FollowEntity( this ); pTrail->SetTransparency( kRenderTransAlpha, -1, -1, -1, 255, kRenderFxNone ); pTrail->SetStartWidth( m_iType == TF_PROJECTILE_BUILDING_REPAIR_BOLT ? 5.0f : 3.0f ); pTrail->SetTextureResolution( 0.01f ); pTrail->SetLifeTime( 0.3f ); pTrail->TurnOn(); pTrail->SetContextThink( &CBaseEntity::SUB_Remove, gpGlobals->curtime + 3.0f, "RemoveThink" ); m_hSpriteTrail.Set( pTrail ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFProjectile_Arrow::UpdateOnRemove( void ) { UTIL_Remove( m_hSpriteTrail.Get() ); BaseClass::UpdateOnRemove(); } //----------------------------------------------------------------------------- // Purpose: Sends to the client information for arrow gibs //----------------------------------------------------------------------------- void CTFProjectile_Arrow::BreakArrow( void ) { SetMoveType( MOVETYPE_NONE, MOVECOLLIDE_DEFAULT ); SetAbsVelocity( vec3_origin ); SetSolidFlags( FSOLID_NOT_SOLID ); AddEffects( EF_NODRAW ); SetContextThink( &CTFProjectile_Arrow::RemoveThink, gpGlobals->curtime + 3.0, "ARROW_REMOVE_THINK" ); CRecipientFilter pFilter; pFilter.AddRecipientsByPVS( GetAbsOrigin() ); UserMessageBegin( pFilter, "BreakModel" ); WRITE_SHORT( GetModelIndex() ); WRITE_VEC3COORD( GetAbsOrigin() ); WRITE_ANGLES( GetAbsAngles() ); MessageEnd(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CTFProjectile_Arrow::PositionArrowOnBone(mstudiobbox_t *pbox, CBaseAnimating *pAnim ) { matrix3x4_t *bones[MAXSTUDIOBONES]; CStudioHdr *pStudioHdr = pAnim->GetModelPtr(); if ( !pStudioHdr ) return false; mstudiohitboxset_t *set = pStudioHdr->pHitboxSet( pAnim->GetHitboxSet() ); if ( !set->numhitboxes || pbox->bone > 127 ) return false; CBoneCache *pCache = pAnim->GetBoneCache(); if ( !pCache ) return false; pCache->ReadCachedBonePointers( bones, pStudioHdr->numbones() ); Vector vecMins, vecMaxs, vecResult; TransformAABB( *bones[pbox->bone], pbox->bbmin, pbox->bbmax, vecMins, vecMaxs ); vecResult = vecMaxs - vecMins; // This is a mess SetAbsOrigin( ( ( ( vecResult ) * 0.60000002f ) + vecMins ) + ( ( ( rand() / RAND_MAX ) * vecResult ) * -0.2f ) ); return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFProjectile_Arrow::GetBoneAttachmentInfo( mstudiobbox_t *pbox, CBaseAnimating *pAnim, Vector &vecOrigin, QAngle &vecAngles, int &bone, int &iPhysicsBone ) { bone = pbox->bone; iPhysicsBone = pAnim->GetPhysicsBone( bone ); //pAnim->GetBonePosition( bone, vecOrigin, vecAngles ); matrix3x4_t arrowToWorld, boneToWorld, invBoneToWorld, boneToWorldTransform; MatrixCopy( EntityToWorldTransform(), arrowToWorld ); pAnim->GetBoneTransform( bone, boneToWorld ); MatrixInvert( boneToWorld, invBoneToWorld ); ConcatTransforms( invBoneToWorld, arrowToWorld, boneToWorldTransform ); MatrixAngles( boneToWorldTransform, vecAngles ); MatrixGetColumn( boneToWorldTransform, 3, vecOrigin ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFProjectile_Arrow::CheckRagdollPinned( Vector &, Vector &, int, int, CBaseEntity *, int, int ) { } // ---------------------------------------------------------------------------- // Purpose: Play the impact sound to nearby players of the recipient and the attacker //----------------------------------------------------------------------------- void CTFProjectile_Arrow::PlayImpactSound( CTFPlayer *pAttacker, const char *pszImpactSound, bool bIsPlayerImpact /*= false*/ ) { if ( pAttacker ) { CRecipientFilter filter; filter.AddRecipientsByPAS( GetAbsOrigin() ); // Only play the sound locally to the attacker if it's a player impact if ( bIsPlayerImpact ) { filter.RemoveRecipient( pAttacker ); CSingleUserRecipientFilter filterAttacker( pAttacker ); EmitSound( filterAttacker, pAttacker->entindex(), pszImpactSound ); } EmitSound( filter, entindex(), pszImpactSound ); } } #else //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_TFProjectile_Arrow::OnDataChanged( DataUpdateType_t updateType ) { BaseClass::OnDataChanged( updateType ); if ( updateType == DATA_UPDATE_CREATED ) { SetNextClientThink( gpGlobals->curtime + 0.1f ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_TFProjectile_Arrow::ClientThink( void ) { if ( m_bAttachment && m_flDieTime < gpGlobals->curtime ) { // Die SetNextClientThink( CLIENT_THINK_NEVER ); Remove(); return; } if ( m_bFlame && !bEmitting ) { Light(); SetNextClientThink( CLIENT_THINK_NEVER ); return; } SetNextClientThink( gpGlobals->curtime + 0.1f ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_TFProjectile_Arrow::Light( void ) { if ( IsDormant() || !m_bFlame ) return; ParticleProp()->Create( "flying_flaming_arrow", PATTACH_ABSORIGIN_FOLLOW ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_TFProjectile_Arrow::NotifyBoneAttached( C_BaseAnimating* attachTarget ) { BaseClass::NotifyBoneAttached( attachTarget ); m_bAttachment = true; SetNextClientThink( CLIENT_THINK_ALWAYS ); } #endif <|start_filename|>src/game/shared/tf/tf_shareddefs.h<|end_filename|> //====== Copyright © 1996-2006, Valve Corporation, All rights reserved. ======= // // Purpose: // //============================================================================= #ifndef TF_SHAREDDEFS_H #define TF_SHAREDDEFS_H #ifdef _WIN32 #pragma once #endif #include "shareddefs.h" #include "mp_shareddefs.h" // Using MAP_DEBUG mode? #ifdef MAP_DEBUG #define MDEBUG(x) x #else #define MDEBUG(x) #endif //----------------------------------------------------------------------------- // Teams. //----------------------------------------------------------------------------- enum { TF_TEAM_RED = LAST_SHARED_TEAM+1, TF_TEAM_BLUE, TF_TEAM_COUNT }; #define TF_TEAM_AUTOASSIGN (TF_TEAM_COUNT + 1 ) extern const char *g_aTeamNames[TF_TEAM_COUNT]; extern const char *g_aTeamNamesShort[TF_TEAM_COUNT]; extern const char *g_aTeamParticleNames[TF_TEAM_COUNT]; extern color32 g_aTeamColors[TF_TEAM_COUNT]; extern color32 g_aTeamSkinColors[TF_TEAM_COUNT]; const char *GetTeamParticleName( int iTeam, bool bDummyBoolean = false, const char **pNames = g_aTeamParticleNames ); const char *ConstructTeamParticle( const char *pszFormat, int iTeam, bool bDummyBoolean = false, const char **pNames = g_aTeamParticleNames ); void PrecacheTeamParticles( const char *pszFormat, bool bDummyBoolean = false, const char **pNames = g_aTeamParticleNames ); #define CONTENTS_REDTEAM CONTENTS_TEAM1 #define CONTENTS_BLUETEAM CONTENTS_TEAM2 // Team roles enum { TEAM_ROLE_NONE = 0, TEAM_ROLE_DEFENDERS, TEAM_ROLE_ATTACKERS, NUM_TEAM_ROLES, }; //----------------------------------------------------------------------------- // CVar replacements //----------------------------------------------------------------------------- #define TF_DAMAGE_CRIT_CHANCE 0.02f #define TF_DAMAGE_CRIT_CHANCE_RAPID 0.02f #define TF_DAMAGE_CRIT_DURATION_RAPID 2.0f #define TF_DAMAGE_CRIT_CHANCE_MELEE 0.10f #define TF_DAMAGE_CRITMOD_MAXTIME 20 #define TF_DAMAGE_CRITMOD_MINTIME 2 #define TF_DAMAGE_CRITMOD_DAMAGE 800 #define TF_DAMAGE_CRITMOD_MAXMULT 6 #define TF_DAMAGE_CRIT_MULTIPLIER 3.0f #define TF_DAMAGE_MINICRIT_MULTIPLIER 1.35f //----------------------------------------------------------------------------- // TF-specific viewport panels //----------------------------------------------------------------------------- #define PANEL_CLASS_BLUE "class_blue" #define PANEL_CLASS_RED "class_red" #define PANEL_MAPINFO "mapinfo" #define PANEL_ROUNDINFO "roundinfo" #define PANEL_ARENATEAMSELECT "arenateamselect" // file we'll save our list of viewed intro movies in #define MOVIES_FILE "viewed.res" //----------------------------------------------------------------------------- // Used in calculating the health percentage of a player //----------------------------------------------------------------------------- #define TF_HEALTH_UNDEFINED 1 //----------------------------------------------------------------------------- // Used to mark a spy's disguise attribute (team or class) as "unused" //----------------------------------------------------------------------------- #define TF_SPY_UNDEFINED TEAM_UNASSIGNED #define COLOR_TF_BLUE Color( 64, 64, 255, 255 ) #define COLOR_TF_RED Color( 255, 64, 64, 255 ) #define COLOR_TF_SPECTATOR Color( 245, 229, 196, 255 ) //----------------------------------------------------------------------------- // Player Classes. //----------------------------------------------------------------------------- #define TF_CLASS_COUNT ( TF_CLASS_COUNT_ALL - 1 ) #define TF_FIRST_NORMAL_CLASS ( TF_CLASS_UNDEFINED + 1 ) #define TF_CLASS_MENU_BUTTONS ( TF_CLASS_RANDOM + 1 ) enum { TF_CLASS_UNDEFINED = 0, TF_CLASS_SCOUT, // TF_FIRST_NORMAL_CLASS TF_CLASS_SNIPER, TF_CLASS_SOLDIER, TF_CLASS_DEMOMAN, TF_CLASS_MEDIC, TF_CLASS_HEAVYWEAPONS, TF_CLASS_PYRO, TF_CLASS_SPY, TF_CLASS_ENGINEER, // TF_CLASS_COUNT TF_CLASS_COUNT_ALL, TF_CLASS_RANDOM }; extern const char *g_aPlayerClassNames[]; // localized class names extern const char *g_aPlayerClassNames_NonLocalized[]; // non-localized class names extern const char *g_aDominationEmblems[]; extern const char *g_aPlayerClassEmblems[]; extern const char *g_aPlayerClassEmblemsDead[]; //----------------------------------------------------------------------------- // For entity_capture_flags to use when placed in the world //----------------------------------------------------------------------------- enum { TF_FLAGTYPE_CTF = 0, TF_FLAGTYPE_ATTACK_DEFEND, TF_FLAGTYPE_TERRITORY_CONTROL, TF_FLAGTYPE_INVADE, TF_FLAGTYPE_KINGOFTHEHILL, }; //----------------------------------------------------------------------------- // For the game rules to determine which type of game we're playing //----------------------------------------------------------------------------- enum { TF_GAMETYPE_UNDEFINED = 0, TF_GAMETYPE_CTF, TF_GAMETYPE_CP, TF_GAMETYPE_ESCORT, TF_GAMETYPE_ARENA, TF_GAMETYPE_MVM, TF_GAMETYPE_RD, TF_GAMETYPE_PASSTIME, TF_GAMETYPE_PD, TF_GAMETYPE_MEDIEVAL, }; extern const char *g_aGameTypeNames[]; // localized gametype names //----------------------------------------------------------------------------- // Buildings. //----------------------------------------------------------------------------- enum { TF_BUILDING_SENTRY = (1<<0), TF_BUILDING_DISPENSER = (1<<1), TF_BUILDING_TELEPORT = (1<<2), }; //----------------------------------------------------------------------------- // Items. //----------------------------------------------------------------------------- enum { TF_ITEM_UNDEFINED = 0, TF_ITEM_CAPTURE_FLAG = (1<<0), TF_ITEM_HEALTH_KIT = (1<<1), TF_ITEM_ARMOR = (1<<2), TF_ITEM_AMMO_PACK = (1<<3), TF_ITEM_GRENADE_PACK = (1<<4), }; //----------------------------------------------------------------------------- // Ammo. //----------------------------------------------------------------------------- enum { TF_AMMO_DUMMY = 0, // Dummy index to make the CAmmoDef indices correct for the other ammo types. TF_AMMO_PRIMARY, TF_AMMO_SECONDARY, TF_AMMO_METAL, TF_AMMO_GRENADES1, TF_AMMO_GRENADES2, TF_AMMO_COUNT }; enum EAmmoSource { TF_AMMO_SOURCE_AMMOPACK = 0, // Default, used for ammopacks TF_AMMO_SOURCE_RESUPPLY, // Maybe? TF_AMMO_SOURCE_DISPENSER, TF_AMMO_SOURCE_COUNT }; //----------------------------------------------------------------------------- // Grenade Launcher mode (for pipebombs). //----------------------------------------------------------------------------- enum { TF_GL_MODE_REGULAR = 0, TF_GL_MODE_REMOTE_DETONATE, TF_GL_MODE_FIZZLE }; //----------------------------------------------------------------------------- // Weapon Types //----------------------------------------------------------------------------- enum { TF_WPN_TYPE_PRIMARY = 0, TF_WPN_TYPE_SECONDARY, TF_WPN_TYPE_MELEE, TF_WPN_TYPE_GRENADE, TF_WPN_TYPE_BUILDING, TF_WPN_TYPE_PDA, TF_WPN_TYPE_ITEM1, TF_WPN_TYPE_ITEM2, TF_WPN_TYPE_MELEE_ALLCLASS, // In live tf2 this is equal to 10, however keep it at 8 just in case it screws something else up TF_WPN_TYPE_SECONDARY2, TF_WPN_TYPE_PRIMARY2, TF_WPN_TYPE_COUNT }; extern const char *g_AnimSlots[]; extern const char *g_LoadoutSlots[]; //----------------------------------------------------------------------------- // Loadout slots //----------------------------------------------------------------------------- enum { TF_LOADOUT_SLOT_PRIMARY = 0, TF_LOADOUT_SLOT_SECONDARY, TF_LOADOUT_SLOT_MELEE, TF_LOADOUT_SLOT_PDA1, TF_LOADOUT_SLOT_PDA2, TF_LOADOUT_SLOT_BUILDING, TF_LOADOUT_SLOT_HAT, TF_LOADOUT_SLOT_MISC, TF_LOADOUT_SLOT_ACTION, TF_LOADOUT_SLOT_COUNT }; extern const char *g_aAmmoNames[]; //----------------------------------------------------------------------------- // Weapons. //----------------------------------------------------------------------------- #define TF_PLAYER_WEAPON_COUNT 5 #define TF_PLAYER_GRENADE_COUNT 2 #define TF_PLAYER_BUILDABLE_COUNT 4 #define TF_WEAPON_PRIMARY_MODE 0 #define TF_WEAPON_SECONDARY_MODE 1 #define TF_WEAPON_GRENADE_FRICTION 0.6f #define TF_WEAPON_GRENADE_GRAVITY 0.81f #define TF_WEAPON_GRENADE_INITPRIME 0.8f #define TF_WEAPON_GRENADE_CONCUSSION_TIME 15.0f #define TF_WEAPON_GRENADE_MIRV_BOMB_COUNT 4 #define TF_WEAPON_GRENADE_CALTROP_TIME 8.0f #define TF_WEAPON_PIPEBOMB_WORLD_COUNT 15 #define TF_WEAPON_PIPEBOMB_COUNT 8 #define TF_WEAPON_PIPEBOMB_INTERVAL 0.6f #define TF_WEAPON_ROCKET_INTERVAL 0.8f #define TF_WEAPON_FLAMETHROWER_INTERVAL 0.15f #define TF_WEAPON_FLAMETHROWER_ROCKET_INTERVAL 0.8f #define TF_WEAPON_ZOOM_FOV 20 enum { TF_WEAPON_NONE = 0, TF_WEAPON_BAT, TF_WEAPON_BOTTLE, TF_WEAPON_FIREAXE, TF_WEAPON_CLUB, TF_WEAPON_CROWBAR, TF_WEAPON_KNIFE, TF_WEAPON_FISTS, TF_WEAPON_SHOVEL, TF_WEAPON_WRENCH, TF_WEAPON_BONESAW, TF_WEAPON_SHOTGUN_PRIMARY, TF_WEAPON_SHOTGUN_SOLDIER, TF_WEAPON_SHOTGUN_HWG, TF_WEAPON_SHOTGUN_PYRO, TF_WEAPON_SCATTERGUN, TF_WEAPON_SNIPERRIFLE, TF_WEAPON_MINIGUN, TF_WEAPON_SMG, TF_WEAPON_SYRINGEGUN_MEDIC, TF_WEAPON_TRANQ, TF_WEAPON_ROCKETLAUNCHER, TF_WEAPON_GRENADELAUNCHER, TF_WEAPON_PIPEBOMBLAUNCHER, TF_WEAPON_FLAMETHROWER, TF_WEAPON_GRENADE_NORMAL, TF_WEAPON_GRENADE_CONCUSSION, TF_WEAPON_GRENADE_NAIL, TF_WEAPON_GRENADE_MIRV, TF_WEAPON_GRENADE_MIRV_DEMOMAN, TF_WEAPON_GRENADE_NAPALM, TF_WEAPON_GRENADE_GAS, TF_WEAPON_GRENADE_EMP, TF_WEAPON_GRENADE_CALTROP, TF_WEAPON_GRENADE_PIPEBOMB, TF_WEAPON_GRENADE_SMOKE_BOMB, TF_WEAPON_GRENADE_HEAL, TF_WEAPON_PISTOL, TF_WEAPON_PISTOL_SCOUT, TF_WEAPON_REVOLVER, TF_WEAPON_NAILGUN, TF_WEAPON_PDA, TF_WEAPON_PDA_ENGINEER_BUILD, TF_WEAPON_PDA_ENGINEER_DESTROY, TF_WEAPON_PDA_SPY, TF_WEAPON_BUILDER, TF_WEAPON_MEDIGUN, TF_WEAPON_GRENADE_MIRVBOMB, TF_WEAPON_FLAMETHROWER_ROCKET, TF_WEAPON_GRENADE_DEMOMAN, TF_WEAPON_SENTRY_BULLET, TF_WEAPON_SENTRY_ROCKET, TF_WEAPON_DISPENSER, TF_WEAPON_INVIS, TF_WEAPON_FLAG, // ADD NEW WEAPONS AFTER THIS TF_WEAPON_FLAREGUN, TF_WEAPON_LUNCHBOX, TF_WEAPON_LUNCHBOX_DRINK, TF_WEAPON_COMPOUND_BOW, TF_WEAPON_JAR, TF_WEAPON_LASER_POINTER, TF_WEAPON_HANDGUN_SCOUT_PRIMARY, TF_WEAPON_STICKBOMB, TF_WEAPON_BAT_WOOD, TF_WEAPON_ROBOT_ARM, TF_WEAPON_BUFF_ITEM, TF_WEAPON_COUNT }; extern const char *g_aWeaponNames[]; extern int g_aWeaponDamageTypes[]; extern const Vector g_vecFixedWpnSpreadPellets[]; int GetWeaponId( const char *pszWeaponName ); #ifdef GAME_DLL int GetWeaponFromDamage( const CTakeDamageInfo &info ); #endif int GetBuildableId( const char *pszBuildableName ); const char *WeaponIdToAlias( int iWeapon ); const char *WeaponIdToClassname( int iWeapon ); const char *TranslateWeaponEntForClass( const char *pszName, int iClass ); enum { TF_PROJECTILE_NONE, TF_PROJECTILE_BULLET, TF_PROJECTILE_ROCKET, TF_PROJECTILE_PIPEBOMB, TF_PROJECTILE_PIPEBOMB_REMOTE, TF_PROJECTILE_SYRINGE, TF_PROJECTILE_FLARE, TF_PROJECTILE_JAR, TF_PROJECTILE_ARROW, TF_PROJECTILE_FLAME_ROCKET, TF_PROJECTILE_JAR_MILK, TF_PROJECTILE_HEALING_BOLT, TF_PROJECTILE_ENERGY_BALL, TF_PROJECTILE_ENERGY_RING, TF_PROJECTILE_PIPEBOMB_REMOTE_PRACTICE, TF_PROJECTILE_CLEAVER, TF_PROJECTILE_STICKY_BALL, TF_PROJECTILE_CANNONBALL, TF_PROJECTILE_BUILDING_REPAIR_BOLT, TF_PROJECTILE_FESTITIVE_ARROW, TF_PROJECTILE_THROWABLE, TF_PROJECTILE_SPELLFIREBALL, TF_PROJECTILE_FESTITIVE_URINE, TF_PROJECTILE_FESTITIVE_HEALING_BOLT, TF_PROJECTILE_BREADMONSTER_JARATE, TF_PROJECTILE_BREADMONSTER_MADMILK, TF_PROJECTILE_GRAPPLINGHOOK, TF_PROJECTILE_SENTRY_ROCKET, TF_PROJECTILE_BREAD_MONSTER, TF_NUM_PROJECTILES }; extern const char *g_szProjectileNames[]; //----------------------------------------------------------------------------- // Attributes. //----------------------------------------------------------------------------- #define TF_PLAYER_VIEW_OFFSET Vector( 0, 0, 64.0 ) //--> see GetViewVectors() //----------------------------------------------------------------------------- // TF Player Condition. //----------------------------------------------------------------------------- // Burning #define TF_BURNING_FREQUENCY 0.5f #define TF_BURNING_FLAME_LIFE 10.0 #define TF_BURNING_FLAME_LIFE_PYRO 0.25 // pyro only displays burning effect momentarily #define TF_BURNING_DMG 3 // disguising #define TF_TIME_TO_CHANGE_DISGUISE 0.5 #define TF_TIME_TO_DISGUISE 2.0 #define TF_TIME_TO_SHOW_DISGUISED_FINISHED_EFFECT 5.0 #define SHOW_DISGUISE_EFFECT 1 #define TF_DISGUISE_TARGET_INDEX_NONE ( MAX_PLAYERS + 1 ) #define TF_PLAYER_INDEX_NONE ( MAX_PLAYERS + 1 ) // Most of these conds aren't actually implemented but putting them here for compatibility. enum { TF_COND_AIMING = 0, // Sniper aiming, Heavy minigun. TF_COND_ZOOMED, TF_COND_DISGUISING, TF_COND_DISGUISED, TF_COND_STEALTHED, TF_COND_INVULNERABLE, TF_COND_TELEPORTED, TF_COND_TAUNTING, TF_COND_INVULNERABLE_WEARINGOFF, TF_COND_STEALTHED_BLINK, TF_COND_SELECTED_TO_TELEPORT, TF_COND_CRITBOOSTED, TF_COND_TMPDAMAGEBONUS, TF_COND_FEIGN_DEATH, TF_COND_PHASE, TF_COND_STUNNED, TF_COND_OFFENSEBUFF, TF_COND_SHIELD_CHARGE, TF_COND_DEMO_BUFF, TF_COND_ENERGY_BUFF, TF_COND_RADIUSHEAL, TF_COND_HEALTH_BUFF, TF_COND_BURNING, TF_COND_HEALTH_OVERHEALED, TF_COND_URINE, TF_COND_BLEEDING, TF_COND_DEFENSEBUFF, TF_COND_MAD_MILK, TF_COND_MEGAHEAL, TF_COND_REGENONDAMAGEBUFF, TF_COND_MARKEDFORDEATH, TF_COND_NOHEALINGDAMAGEBUFF, TF_COND_SPEED_BOOST, TF_COND_CRITBOOSTED_PUMPKIN, TF_COND_CRITBOOSTED_USER_BUFF, TF_COND_CRITBOOSTED_DEMO_CHARGE, TF_COND_SODAPOPPER_HYPE, TF_COND_CRITBOOSTED_FIRST_BLOOD, TF_COND_CRITBOOSTED_BONUS_TIME, TF_COND_CRITBOOSTED_CTF_CAPTURE, TF_COND_CRITBOOSTED_ON_KILL, TF_COND_CANNOT_SWITCH_FROM_MELEE, TF_COND_DEFENSEBUFF_NO_CRIT_BLOCK, TF_COND_REPROGRAMMED, TF_COND_CRITBOOSTED_RAGE_BUFF, TF_COND_DEFENSEBUFF_HIGH, TF_COND_SNIPERCHARGE_RAGE_BUFF, TF_COND_DISGUISE_WEARINGOFF, TF_COND_MARKEDFORDEATH_SILENT, TF_COND_DISGUISED_AS_DISPENSER, TF_COND_SAPPED, TF_COND_INVULNERABLE_HIDE_UNLESS_DAMAGE, TF_COND_INVULNERABLE_USER_BUFF, TF_COND_HALLOWEEN_BOMB_HEAD, TF_COND_HALLOWEEN_THRILLER, TF_COND_RADIUSHEAL_ON_DAMAGE, TF_COND_CRITBOOSTED_CARD_EFFECT, TF_COND_INVULNERABLE_CARD_EFFECT, TF_COND_MEDIGUN_UBER_BULLET_RESIST, TF_COND_MEDIGUN_UBER_BLAST_RESIST, TF_COND_MEDIGUN_UBER_FIRE_RESIST, TF_COND_MEDIGUN_SMALL_BULLET_RESIST, TF_COND_MEDIGUN_SMALL_BLAST_RESIST, TF_COND_MEDIGUN_SMALL_FIRE_RESIST, TF_COND_STEALTHED_USER_BUFF, TF_COND_MEDIGUN_DEBUFF, TF_COND_STEALTHED_USER_BUFF_FADING, TF_COND_BULLET_IMMUNE, TF_COND_BLAST_IMMUNE, TF_COND_FIRE_IMMUNE, TF_COND_PREVENT_DEATH, TF_COND_MVM_BOT_STUN_RADIOWAVE, TF_COND_HALLOWEEN_SPEED_BOOST, TF_COND_HALLOWEEN_QUICK_HEAL, TF_COND_HALLOWEEN_GIANT, TF_COND_HALLOWEEN_TINY, TF_COND_HALLOWEEN_IN_HELL, TF_COND_HALLOWEEN_GHOST_MODE, TF_COND_MINICRITBOOSTED_ON_KILL, TF_COND_OBSCURED_SMOKE, TF_COND_PARACHUTE_DEPLOYED, TF_COND_BLASTJUMPING, TF_COND_HALLOWEEN_KART, TF_COND_HALLOWEEN_KART_DASH, TF_COND_BALLOON_HEAD, TF_COND_MELEE_ONLY, TF_COND_SWIMMING_CURSE, TF_COND_FREEZE_INPUT, TF_COND_HALLOWEEN_KART_CAGE, TF_COND_DONOTUSE_0, TF_COND_RUNE_STRENGTH, TF_COND_RUNE_HASTE, TF_COND_RUNE_REGEN, TF_COND_RUNE_RESIST, TF_COND_RUNE_VAMPIRE, TF_COND_RUNE_WARLOCK, TF_COND_RUNE_PRECISION, TF_COND_RUNE_AGILITY, TF_COND_GRAPPLINGHOOK, TF_COND_GRAPPLINGHOOK_SAFEFALL, TF_COND_GRAPPLINGHOOK_LATCHED, TF_COND_GRAPPLINGHOOK_BLEEDING, TF_COND_AFTERBURN_IMMUNE, TF_COND_RUNE_KNOCKOUT, TF_COND_RUNE_IMBALANCE, TF_COND_CRITBOOSTED_RUNE_TEMP, TF_COND_PASSTIME_INTERCEPTION, // TF2V conds TF_COND_NO_MOVE, TF_COND_DISGUISE_HEALTH_OVERHEALED, TF_COND_LAST }; extern int condition_to_attribute_translation[]; int ConditionExpiresFast( int nCond ); //----------------------------------------------------------------------------- // Mediguns. //----------------------------------------------------------------------------- enum { TF_MEDIGUN_STOCK = 0, TF_MEDIGUN_KRITZKRIEG, TF_MEDIGUN_QUICKFIX, TF_MEDIGUN_VACCINATOR, TF_MEDIGUN_OVERHEALER, TF_MEDIGUN_COUNT }; enum medigun_charge_types { TF_CHARGE_NONE = -1, TF_CHARGE_INVULNERABLE = 0, TF_CHARGE_CRITBOOSTED, // TODO: #if 0 TF_CHARGE_MEGAHEAL, TF_CHARGE_BULLET_RESIST, TF_CHARGE_BLAST_RESIST, TF_CHARGE_FIRE_RESIST, #endif TF_CHARGE_COUNT }; typedef struct { int condition_enable; int condition_disable; const char *sound_enable; const char *sound_disable; } MedigunEffects_t; extern MedigunEffects_t g_MedigunEffects[]; //----------------------------------------------------------------------------- // TF Player State. //----------------------------------------------------------------------------- enum { TF_STATE_ACTIVE = 0, // Happily running around in the game. TF_STATE_WELCOME, // First entering the server (shows level intro screen). TF_STATE_OBSERVER, // Game observer mode. TF_STATE_DYING, // Player is dying. TF_STATE_COUNT }; //----------------------------------------------------------------------------- // TF FlagInfo State. //----------------------------------------------------------------------------- #define TF_FLAGINFO_NONE 0 #define TF_FLAGINFO_STOLEN (1<<0) #define TF_FLAGINFO_DROPPED (1<<1) enum { TF_FLAGEVENT_PICKUP = 1, TF_FLAGEVENT_CAPTURE, TF_FLAGEVENT_DEFEND, TF_FLAGEVENT_DROPPED }; //----------------------------------------------------------------------------- // Class data //----------------------------------------------------------------------------- #define TF_MEDIC_REGEN_TIME 1.0 // Number of seconds between each regen. #define TF_MEDIC_REGEN_AMOUNT 1 // Amount of health regenerated each regen. //----------------------------------------------------------------------------- // Assist-damage constants //----------------------------------------------------------------------------- #define TF_TIME_ASSIST_KILL 3.0f // Time window for a recent damager to get credit for an assist for a kill #define TF_TIME_ENV_DEATH_KILL_CREDIT 5.0f // Time window for a recent damager to get credit for an environmental kill #define TF_TIME_SUICIDE_KILL_CREDIT 10.0f // Time window for a recent damager to get credit for a kill if target suicides //----------------------------------------------------------------------------- // Domination/nemesis constants //----------------------------------------------------------------------------- #define TF_KILLS_DOMINATION 4 // # of unanswered kills to dominate another player //----------------------------------------------------------------------------- // TF Hints //----------------------------------------------------------------------------- enum { HINT_FRIEND_SEEN = 0, // #Hint_spotted_a_friend HINT_ENEMY_SEEN, // #Hint_spotted_an_enemy HINT_ENEMY_KILLED, // #Hint_killing_enemies_is_good HINT_AMMO_EXHAUSTED, // #Hint_out_of_ammo HINT_TURN_OFF_HINTS, // #Hint_turn_off_hints HINT_PICKUP_AMMO, // #Hint_pickup_ammo HINT_CANNOT_TELE_WITH_FLAG, // #Hint_Cannot_Teleport_With_Flag HINT_CANNOT_CLOAK_WITH_FLAG, // #Hint_Cannot_Cloak_With_Flag HINT_CANNOT_DISGUISE_WITH_FLAG, // #Hint_Cannot_Disguise_With_Flag HINT_CANNOT_ATTACK_WHILE_CLOAKED, // #Hint_Cannot_Attack_While_Cloaked HINT_CLASSMENU, // #Hint_ClassMenu // Grenades HINT_GREN_CALTROPS, // #Hint_gren_caltrops HINT_GREN_CONCUSSION, // #Hint_gren_concussion HINT_GREN_EMP, // #Hint_gren_emp HINT_GREN_GAS, // #Hint_gren_gas HINT_GREN_MIRV, // #Hint_gren_mirv HINT_GREN_NAIL, // #Hint_gren_nail HINT_GREN_NAPALM, // #Hint_gren_napalm HINT_GREN_NORMAL, // #Hint_gren_normal // Weapon alt-fires HINT_ALTFIRE_SNIPERRIFLE, // #Hint_altfire_sniperrifle HINT_ALTFIRE_FLAMETHROWER, // #Hint_altfire_flamethrower HINT_ALTFIRE_GRENADELAUNCHER, // #Hint_altfire_grenadelauncher HINT_ALTFIRE_PIPEBOMBLAUNCHER, // #Hint_altfire_pipebomblauncher HINT_ALTFIRE_ROTATE_BUILDING, // #Hint_altfire_rotate_building // Class specific // Soldier HINT_SOLDIER_RPG_RELOAD, // #Hint_Soldier_rpg_reload // Engineer HINT_ENGINEER_USE_WRENCH_ONOWN, // "#Hint_Engineer_use_wrench_onown", HINT_ENGINEER_USE_WRENCH_ONOTHER, // "#Hint_Engineer_use_wrench_onother", HINT_ENGINEER_USE_WRENCH_FRIEND, // "#Hint_Engineer_use_wrench_onfriend", HINT_ENGINEER_BUILD_SENTRYGUN, // "#Hint_Engineer_build_sentrygun" HINT_ENGINEER_BUILD_DISPENSER, // "#Hint_Engineer_build_dispenser" HINT_ENGINEER_BUILD_TELEPORTERS, // "#Hint_Engineer_build_teleporters" HINT_ENGINEER_PICKUP_METAL, // "#Hint_Engineer_pickup_metal" HINT_ENGINEER_REPAIR_OBJECT, // "#Hint_Engineer_repair_object" HINT_ENGINEER_METAL_TO_UPGRADE, // "#Hint_Engineer_metal_to_upgrade" HINT_ENGINEER_UPGRADE_SENTRYGUN, // "#Hint_Engineer_upgrade_sentrygun" HINT_OBJECT_HAS_SAPPER, // "#Hint_object_has_sapper" HINT_OBJECT_YOUR_OBJECT_SAPPED, // "#Hint_object_your_object_sapped" HINT_OBJECT_ENEMY_USING_DISPENSER, // "#Hint_enemy_using_dispenser" HINT_OBJECT_ENEMY_USING_TP_ENTRANCE, // "#Hint_enemy_using_tp_entrance" HINT_OBJECT_ENEMY_USING_TP_EXIT, // "#Hint_enemy_using_tp_exit" NUM_HINTS }; extern const char *g_pszHintMessages[]; /*======================*/ // Menu stuff // /*======================*/ #define MENU_DEFAULT 1 #define MENU_TEAM 2 #define MENU_CLASS 3 #define MENU_MAPBRIEFING 4 #define MENU_INTRO 5 #define MENU_CLASSHELP 6 #define MENU_CLASSHELP2 7 #define MENU_REPEATHELP 8 #define MENU_SPECHELP 9 #define MENU_SPY 12 #define MENU_SPY_SKIN 13 #define MENU_SPY_COLOR 14 #define MENU_ENGINEER 15 #define MENU_ENGINEER_FIX_DISPENSER 16 #define MENU_ENGINEER_FIX_SENTRYGUN 17 #define MENU_ENGINEER_FIX_MORTAR 18 #define MENU_DISPENSER 19 #define MENU_CLASS_CHANGE 20 #define MENU_TEAM_CHANGE 21 #define MENU_REFRESH_RATE 25 #define MENU_VOICETWEAK 50 // Additional classes // NOTE: adding them onto the Class_T's in baseentity.h is cheesy, but so is // having an #ifdef for each mod in baseentity.h. #define CLASS_TFGOAL ((Class_T)NUM_AI_CLASSES) #define CLASS_TFGOAL_TIMER ((Class_T)(NUM_AI_CLASSES+1)) #define CLASS_TFGOAL_ITEM ((Class_T)(NUM_AI_CLASSES+2)) #define CLASS_TFSPAWN ((Class_T)(NUM_AI_CLASSES+3)) #define CLASS_MACHINE ((Class_T)(NUM_AI_CLASSES+4)) // TeamFortress State Flags #define TFSTATE_GRENPRIMED 0x000001 // Whether the player has a primed grenade #define TFSTATE_RELOADING 0x000002 // Whether the player is reloading #define TFSTATE_ALTKILL 0x000004 // #TRUE if killed with a weapon not in self.weapon: NOT USED ANYMORE #define TFSTATE_RANDOMPC 0x000008 // Whether Playerclass is random, new one each respawn #define TFSTATE_INFECTED 0x000010 // set when player is infected by the bioweapon #define TFSTATE_INVINCIBLE 0x000020 // Player has permanent Invincibility (Usually by GoalItem) #define TFSTATE_INVISIBLE 0x000040 // Player has permanent Invisibility (Usually by GoalItem) #define TFSTATE_QUAD 0x000080 // Player has permanent Quad Damage (Usually by GoalItem) #define TFSTATE_RADSUIT 0x000100 // Player has permanent Radsuit (Usually by GoalItem) #define TFSTATE_BURNING 0x000200 // Is on fire #define TFSTATE_GRENTHROWING 0x000400 // is throwing a grenade #define TFSTATE_AIMING 0x000800 // is using the laser sight #define TFSTATE_ZOOMOFF 0x001000 // doesn't want the FOV changed when zooming #define TFSTATE_RESPAWN_READY 0x002000 // is waiting for respawn, and has pressed fire #define TFSTATE_HALLUCINATING 0x004000 // set when player is hallucinating #define TFSTATE_TRANQUILISED 0x008000 // set when player is tranquilised #define TFSTATE_CANT_MOVE 0x010000 // player isn't allowed to move #define TFSTATE_RESET_FLAMETIME 0x020000 // set when the player has to have his flames increased in health #define TFSTATE_HIGHEST_VALUE TFSTATE_RESET_FLAMETIME // items #define IT_SHOTGUN (1<<0) #define IT_SUPER_SHOTGUN (1<<1) #define IT_NAILGUN (1<<2) #define IT_SUPER_NAILGUN (1<<3) #define IT_GRENADE_LAUNCHER (1<<4) #define IT_ROCKET_LAUNCHER (1<<5) #define IT_LIGHTNING (1<<6) #define IT_EXTRA_WEAPON (1<<7) #define IT_SHELLS (1<<8) #define IT_BULLETS (1<<9) #define IT_ROCKETS (1<<10) #define IT_CELLS (1<<11) #define IT_AXE (1<<12) #define IT_ARMOR1 (1<<13) #define IT_ARMOR2 (1<<14) #define IT_ARMOR3 (1<<15) #define IT_SUPERHEALTH (1<<16) #define IT_KEY1 (1<<17) #define IT_KEY2 (1<<18) #define IT_INVISIBILITY (1<<19) #define IT_INVULNERABILITY (1<<20) #define IT_SUIT (1<<21) #define IT_QUAD (1<<22) #define IT_HOOK (1<<23) #define IT_KEY3 (1<<24) // Stomp invisibility #define IT_KEY4 (1<<25) // Stomp invulnerability #define IT_LAST_ITEM IT_KEY4 /*==================================================*/ /* New Weapon Related Defines */ /*==================================================*/ // Medikit #define WEAP_MEDIKIT_OVERHEAL 50 // Amount of superhealth over max_health the medikit will dispense #define WEAP_MEDIKIT_HEAL 200 // Amount medikit heals per hit //-------------- // TF Specific damage flags //-------------- //#define DMG_UNUSED (DMG_LASTGENERICFLAG<<2) // We can't add anymore dmg flags, because we'd be over the 32 bit limit. // So lets re-use some of the old dmg flags in TF #define DMG_USE_HITLOCATIONS (DMG_AIRBOAT) #define DMG_HALF_FALLOFF (DMG_RADIATION) #define DMG_CRITICAL (DMG_ACID) #define DMG_MINICRITICAL (DMG_PHYSGUN) #define DMG_RADIUS_MAX (DMG_ENERGYBEAM) #define DMG_IGNITE (DMG_PLASMA) #define DMG_USEDISTANCEMOD (DMG_SLOWBURN) // NEED TO REMOVE CALTROPS #define DMG_NOCLOSEDISTANCEMOD (DMG_POISON) #define TF_DMG_SENTINEL_VALUE 0xFFFFFFFF // This can only ever be used on a TakeHealth call, since it re-uses a dmg flag that means something else #define DMG_IGNORE_MAXHEALTH (DMG_BULLET) // Special Damage types enum { TF_DMG_CUSTOM_NONE, // TODO: Remove this at some point TF_DMG_CUSTOM_HEADSHOT, TF_DMG_CUSTOM_BACKSTAB, TF_DMG_CUSTOM_BURNING, TF_DMG_WRENCH_FIX, TF_DMG_CUSTOM_MINIGUN, TF_DMG_CUSTOM_SUICIDE, TF_DMG_CUSTOM_TAUNTATK_HADOUKEN, TF_DMG_CUSTOM_BURNING_FLARE, TF_DMG_CUSTOM_TAUNTATK_HIGH_NOON, TF_DMG_CUSTOM_TAUNTATK_GRAND_SLAM, TF_DMG_CUSTOM_PENETRATE_MY_TEAM, TF_DMG_CUSTOM_PENETRATE_ALL_PLAYERS, TF_DMG_CUSTOM_TAUNTATK_FENCING, TF_DMG_CUSTOM_PENETRATE_NONBURNING_TEAMMATE, TF_DMG_CUSTOM_TAUNTATK_ARROW_STAB, TF_DMG_CUSTOM_TELEFRAG, TF_DMG_CUSTOM_BURNING_ARROW, TF_DMG_CUSTOM_FLYINGBURN, TF_DMG_CUSTOM_PUMPKIN_BOMB, TF_DMG_CUSTOM_DECAPITATION, TF_DMG_CUSTOM_TAUNTATK_GRENADE, TF_DMG_CUSTOM_BASEBALL, TF_DMG_CUSTOM_CHARGE_IMPACT, TF_DMG_CUSTOM_TAUNTATK_BARBARIAN_SWING, TF_DMG_CUSTOM_AIR_STICKY_BURST, TF_DMG_CUSTOM_DEFENSIVE_STICKY, TF_DMG_CUSTOM_PICKAXE, TF_DMG_CUSTOM_ROCKET_DIRECTHIT, TF_DMG_CUSTOM_TAUNTATK_UBERSLICE, TF_DMG_CUSTOM_PLAYER_SENTRY, TF_DMG_CUSTOM_STANDARD_STICKY, TF_DMG_CUSTOM_SHOTGUN_REVENGE_CRIT, TF_DMG_CUSTOM_TAUNTATK_ENGINEER_GUITAR_SMASH, TF_DMG_CUSTOM_BLEEDING, TF_DMG_CUSTOM_GOLD_WRENCH, TF_DMG_CUSTOM_CARRIED_BUILDING, TF_DMG_CUSTOM_COMBO_PUNCH, TF_DMG_CUSTOM_TAUNTATK_ENGINEER_ARM_KILL, TF_DMG_CUSTOM_FISH_KILL, TF_DMG_CUSTOM_TRIGGER_HURT, TF_DMG_CUSTOM_DECAPITATION_BOSS, TF_DMG_CUSTOM_STICKBOMB_EXPLOSION, TF_DMG_CUSTOM_AEGIS_ROUND, TF_DMG_CUSTOM_FLARE_EXPLOSION, TF_DMG_CUSTOM_BOOTS_STOMP, TF_DMG_CUSTOM_PLASMA, TF_DMG_CUSTOM_PLASMA_CHARGED, TF_DMG_CUSTOM_PLASMA_GIB, TF_DMG_CUSTOM_PRACTICE_STICKY, TF_DMG_CUSTOM_EYEBALL_ROCKET, TF_DMG_CUSTOM_HEADSHOT_DECAPITATION, TF_DMG_CUSTOM_TAUNTATK_ARMAGEDDON, TF_DMG_CUSTOM_FLARE_PELLET, TF_DMG_CUSTOM_CLEAVER, TF_DMG_CUSTOM_CLEAVER_CRIT, TF_DMG_CUSTOM_SAPPER_RECORDER_DEATH, TF_DMG_CUSTOM_MERASMUS_PLAYER_BOMB, TF_DMG_CUSTOM_MERASMUS_GRENADE, TF_DMG_CUSTOM_MERASMUS_ZAP, TF_DMG_CUSTOM_MERASMUS_DECAPITATION, TF_DMG_CUSTOM_CANNONBALL_PUSH, TF_DMG_CUSTOM_TAUNTATK_ALLCLASS_GUITAR_RIFF, TF_DMG_CUSTOM_THROWABLE, TF_DMG_CUSTOM_THROWABLE_KILL, TF_DMG_CUSTOM_SPELL_TELEPORT, TF_DMG_CUSTOM_SPELL_SKELETON, TF_DMG_CUSTOM_SPELL_MIRV, TF_DMG_CUSTOM_SPELL_METEOR, TF_DMG_CUSTOM_SPELL_LIGHTNING, TF_DMG_CUSTOM_SPELL_FIREBALL, TF_DMG_CUSTOM_SPELL_MONOCULUS, TF_DMG_CUSTOM_SPELL_BLASTJUMP, TF_DMG_CUSTOM_SPELL_BATS, TF_DMG_CUSTOM_SPELL_TINY, TF_DMG_CUSTOM_KART, TF_DMG_CUSTOM_GIANT_HAMMER, TF_DMG_CUSTOM_RUNE_REFLECT, TF_DMG_CUSTOM_DRAGONS_FURY_IGNITE, TF_DMG_CUSTOM_DRAGONS_FURY_BONUS_BURNIN, TF_DMG_CUSTOM_SLAP_KILL, TF_DMG_CUSTOM_CROC, TF_DMG_CUSTOM_TAUNTATK_GASBLAST, TF_DMG_CUSTOM_AXTINGUISHER_BOOSTED, }; #define TF_JUMP_ROCKET ( 1 << 0 ) #define TF_JUMP_STICKY ( 1 << 1 ) #define TF_JUMP_OTHER ( 1 << 2 ) enum { TF_COLLISIONGROUP_GRENADES = LAST_SHARED_COLLISION_GROUP, TFCOLLISION_GROUP_OBJECT, TFCOLLISION_GROUP_OBJECT_SOLIDTOPLAYERMOVEMENT, TFCOLLISION_GROUP_COMBATOBJECT, TFCOLLISION_GROUP_ROCKETS, // Solid to players, but not player movement. ensures touch calls are originating from rocket TFCOLLISION_GROUP_RESPAWNROOMS, TFCOLLISION_GROUP_PUMPKIN_BOMB, // Bombs TFCOLLISION_GROUP_ARROWS, // Arrows TFCOLLISION_GROUP_NONE, // Collides with nothing }; //----------------- // TF Objects Info //----------------- #define SENTRYGUN_UPGRADE_COST 130 #define SENTRYGUN_UPGRADE_METAL 200 #define SENTRYGUN_EYE_OFFSET_LEVEL_1 Vector( 0, 0, 32 ) #define SENTRYGUN_EYE_OFFSET_LEVEL_2 Vector( 0, 0, 40 ) #define SENTRYGUN_EYE_OFFSET_LEVEL_3 Vector( 0, 0, 46 ) #define SENTRYGUN_MAX_SHELLS_1 150 #define SENTRYGUN_MAX_SHELLS_2 200 #define SENTRYGUN_MAX_SHELLS_3 200 #define SENTRYGUN_MAX_ROCKETS 20 // Dispenser's maximum carrying capability #define DISPENSER_MAX_METAL_AMMO 400 #define MAX_DISPENSER_HEALING_TARGETS 32 //-------------------------------------------------------------------------- // OBJECTS //-------------------------------------------------------------------------- enum { OBJ_DISPENSER=0, OBJ_TELEPORTER, OBJ_SENTRYGUN, // Attachment Objects OBJ_ATTACHMENT_SAPPER, // If you add a new object, you need to add it to the g_ObjectInfos array // in tf_shareddefs.cpp, and add it's data to the scripts/object.txt OBJ_LAST, }; // Warning levels for buildings in the building hud, in priority order typedef enum { BUILDING_HUD_ALERT_NONE = 0, BUILDING_HUD_ALERT_LOW_AMMO, BUILDING_HUD_ALERT_LOW_HEALTH, BUILDING_HUD_ALERT_VERY_LOW_AMMO, BUILDING_HUD_ALERT_VERY_LOW_HEALTH, BUILDING_HUD_ALERT_SAPPER, MAX_BUILDING_HUD_ALERT_LEVEL } BuildingHudAlert_t; typedef enum { BUILDING_DAMAGE_LEVEL_NONE = 0, // 100% BUILDING_DAMAGE_LEVEL_LIGHT, // 75% - 99% BUILDING_DAMAGE_LEVEL_MEDIUM, // 50% - 76% BUILDING_DAMAGE_LEVEL_HEAVY, // 25% - 49% BUILDING_DAMAGE_LEVEL_CRITICAL, // 0% - 24% MAX_BUILDING_DAMAGE_LEVEL } BuildingDamageLevel_t; //-------------- // Scoring //-------------- #define TF_SCORE_KILL 1 #define TF_SCORE_DEATH 0 #define TF_SCORE_CAPTURE 2 #define TF_SCORE_DEFEND 1 #define TF_SCORE_DESTROY_BUILDING 1 #define TF_SCORE_HEADSHOT_PER_POINT 2 #define TF_SCORE_BACKSTAB 1 #define TF_SCORE_INVULN 1 #define TF_SCORE_REVENGE 1 #define TF_SCORE_KILL_ASSISTS_PER_POINT 2 #define TF_SCORE_TELEPORTS_PER_POINT 2 #define TF_SCORE_HEAL_HEALTHUNITS_PER_POINT 600 #define TF_SCORE_DAMAGE_PER_POINT 600 #define TF_SCORE_BONUS_PER_POINT 1 //------------------------- // Shared Teleporter State //------------------------- enum { TELEPORTER_STATE_BUILDING = 0, // Building, not active yet TELEPORTER_STATE_IDLE, // Does not have a matching teleporter yet TELEPORTER_STATE_READY, // Found match, charged and ready TELEPORTER_STATE_SENDING, // Teleporting a player away TELEPORTER_STATE_RECEIVING, TELEPORTER_STATE_RECEIVING_RELEASE, TELEPORTER_STATE_RECHARGING, // Waiting for recharge TELEPORTER_STATE_UPGRADING }; #define OBJECT_MODE_NONE 0 #define TELEPORTER_TYPE_ENTRANCE 0 #define TELEPORTER_TYPE_EXIT 1 #define TELEPORTER_RECHARGE_TIME 10 // seconds to recharge extern float g_flTeleporterRechargeTimes[]; extern float g_flDispenserAmmoRates[]; extern float g_flDispenserCloakRates[]; extern float g_flDispenserHealRates[]; //------------------------- // Shared Sentry State //------------------------- enum { SENTRY_STATE_INACTIVE = 0, SENTRY_STATE_SEARCHING, SENTRY_STATE_ATTACKING, SENTRY_STATE_UPGRADING, SENTRY_STATE_WRANGLED, SENTRY_STATE_WRANGLED_RECOVERY, SENTRY_NUM_STATES, }; //-------------------------------------------------------------------------- // OBJECT FLAGS //-------------------------------------------------------------------------- enum { OF_ALLOW_REPEAT_PLACEMENT = 0x01, OF_MUST_BE_BUILT_ON_ATTACHMENT = 0x02, OF_IS_CART_OBJECT = 0x04, //I'm not sure what the exact name is, but live tf2 uses it for the payload bomb dispenser object OF_BIT_COUNT = 4 }; //-------------------------------------------------------------------------- // Builder "weapon" states //-------------------------------------------------------------------------- enum { BS_IDLE = 0, BS_SELECTING, BS_PLACING, BS_PLACING_INVALID }; //-------------------------------------------------------------------------- // Builder object id... //-------------------------------------------------------------------------- enum { BUILDER_OBJECT_BITS = 8, BUILDER_INVALID_OBJECT = ((1 << BUILDER_OBJECT_BITS) - 1) }; // Analyzer state enum { AS_INACTIVE = 0, AS_SUBVERTING, AS_ANALYZING }; // Max number of objects a team can have #define MAX_OBJECTS_PER_PLAYER 4 //#define MAX_OBJECTS_PER_TEAM 128 // sanity check that commands send via user command are somewhat valid #define MAX_OBJECT_SCREEN_INPUT_DISTANCE 100 //-------------------------------------------------------------------------- // BUILDING //-------------------------------------------------------------------------- // Build checks will return one of these for a player enum { CB_CAN_BUILD, // Player is allowed to build this object CB_CANNOT_BUILD, // Player is not allowed to build this object CB_LIMIT_REACHED, // Player has reached the limit of the number of these objects allowed CB_NEED_RESOURCES, // Player doesn't have enough resources to build this object CB_NEED_ADRENALIN, // Commando doesn't have enough adrenalin to build a rally flag CB_UNKNOWN_OBJECT, // Error message, tried to build unknown object }; // Build animation events #define TF_OBJ_ENABLEBODYGROUP 6000 #define TF_OBJ_DISABLEBODYGROUP 6001 #define TF_OBJ_ENABLEALLBODYGROUPS 6002 #define TF_OBJ_DISABLEALLBODYGROUPS 6003 #define TF_OBJ_PLAYBUILDSOUND 6004 #define TF_AE_CIGARETTE_THROW 7000 #define OBJECT_COST_MULTIPLIER_PER_OBJECT 3 #define OBJECT_UPGRADE_COST_MULTIPLIER_PER_LEVEL 3 //-------------------------------------------------------------------------- // Powerups //-------------------------------------------------------------------------- enum { POWERUP_BOOST, // Medic, buff station POWERUP_EMP, // Technician POWERUP_RUSH, // Rally flag POWERUP_POWER, // Object power MAX_POWERUPS }; //-------------------------------------------------------------------------- // Stun //-------------------------------------------------------------------------- #define TF_STUNFLAG_SLOWDOWN (1<<0) // activates slowdown modifier #define TF_STUNFLAG_BONKSTUCK (1<<1) // bonk sound, stuck #define TF_STUNFLAG_LIMITMOVEMENT (1<<2) // disable forward/backward movement #define TF_STUNFLAG_CHEERSOUND (1<<3) // cheering sound #define TF_STUNFLAG_NOSOUNDOREFFECT (1<<4) // no sound or particle #define TF_STUNFLAG_THIRDPERSON (1<<5) // panic animation #define TF_STUNFLAG_GHOSTEFFECT (1<<6) // ghost particles #define TF_STUNFLAG_BONKEFFECT (1<<7) // sandman particles #define TF_STUNFLAG_RESISTDAMAGE (1<<8) // damage resist modifier enum { TF_STUNFLAGS_LOSERSTATE = TF_STUNFLAG_THIRDPERSON | TF_STUNFLAG_SLOWDOWN | TF_STUNFLAG_NOSOUNDOREFFECT, // Currently unused TF_STUNFLAGS_GHOSTSCARE = TF_STUNFLAG_THIRDPERSON |TF_STUNFLAG_GHOSTEFFECT, // Ghost stun TF_STUNFLAGS_SMALLBONK = TF_STUNFLAG_THIRDPERSON | TF_STUNFLAG_SLOWDOWN | TF_STUNFLAG_BONKEFFECT, // Half stun TF_STUNFLAGS_NORMALBONK = TF_STUNFLAG_BONKSTUCK, // Full stun TF_STUNFLAGS_BIGBONK = TF_STUNFLAG_CHEERSOUND | TF_STUNFLAG_BONKSTUCK | TF_STUNFLAG_RESISTDAMAGE | TF_STUNFLAG_BONKEFFECT, // Moonshot TF_STUNFLAGS_COUNT // This doesn't really work with flags }; //-------------------------------------------------------------------------- // Holiday //-------------------------------------------------------------------------- enum { kHoliday_None, kHoliday_TF2Birthday, kHoliday_Halloween, kHoliday_Christmas, kHoliday_CommunityUpdate, kHoliday_EOTL, kHoliday_ValentinesDay, kHoliday_MeetThePyro, kHoliday_FullMoon, kHoliday_HalloweenOrFullMoon, kHoliday_HalloweenOrFullMoonOrValentines, kHoliday_AprilFools, kHolidayCount, }; //-------------------------------------------------------------------------- // Rage //-------------------------------------------------------------------------- enum { TF_BUFF_OFFENSE = 1, TF_BUFF_DEFENSE, TF_BUFF_REGENONDAMAGE, }; #define MAX_CABLE_CONNECTIONS 4 bool IsObjectAnUpgrade( int iObjectType ); bool IsObjectAVehicle( int iObjectType ); bool IsObjectADefensiveBuilding( int iObjectType ); class CHudTexture; #define OBJECT_MAX_GIB_MODELS 9 class CObjectInfo { public: CObjectInfo( char *pObjectName ); CObjectInfo( const CObjectInfo& obj ) {} ~CObjectInfo(); // This is initialized by the code and matched with a section in objects.txt char *m_pObjectName; // This stuff all comes from objects.txt char *m_pClassName; // Code classname (in LINK_ENTITY_TO_CLASS). char *m_pStatusName; // Shows up when crosshairs are on the object. float m_flBuildTime; int m_nMaxObjects; // Maximum number of objects per player int m_Cost; // Base object resource cost float m_CostMultiplierPerInstance; // Cost multiplier int m_UpgradeCost; // Base object resource cost for upgrading float m_flUpgradeDuration; int m_MaxUpgradeLevel; // Max object upgrade level char *m_pBuilderWeaponName; // Names shown for each object onscreen when using the builder weapon char *m_pBuilderPlacementString; // String shown to player during placement of this object int m_SelectionSlot; // Weapon selection slots for objects int m_SelectionPosition; // Weapon selection positions for objects bool m_bSolidToPlayerMovement; bool m_bUseItemInfo; char *m_pViewModel; // View model to show in builder weapon for this object char *m_pPlayerModel; // World model to show attached to the player int m_iDisplayPriority; // Priority for ordering in the hud display ( higher is closer to top ) bool m_bVisibleInWeaponSelection; // should show up and be selectable via the weapon selection? char *m_pExplodeSound; // gamesound to play when object explodes char *m_pExplosionParticleEffect; // particle effect to play when object explodes bool m_bAutoSwitchTo; // should we let players switch back to the builder weapon representing this? char *m_pUpgradeSound; // gamesound to play when upgrading int m_BuildCount; // ??? bool m_bRequiresOwnBuilder; // ??? CUtlVector< const char * > m_AltModes; // HUD weapon selection menu icon ( from hud_textures.txt ) char *m_pIconActive; char *m_pIconInactive; char *m_pIconMenu; // HUD building status icon char *m_pHudStatusIcon; // gibs int m_iMetalToDropInGibs; }; // Loads the objects.txt script. class IBaseFileSystem; void LoadObjectInfos( IBaseFileSystem *pFileSystem ); // Get a CObjectInfo from a TFOBJ_ define. const CObjectInfo* GetObjectInfo( int iObject ); // Object utility funcs bool ClassCanBuild( int iClass, int iObjectType ); int CalculateObjectCost( int iObjectType, bool bMini = false /*, int iNumberOfObjects, int iTeam, bool bLast = false*/ ); int CalculateObjectUpgrade( int iObjectType, int iObjectLevel ); // Shell ejections enum { EJECTBRASS_PISTOL, EJECTBRASS_MINIGUN, }; // Win panel styles enum { WINPANEL_BASIC = 0, }; #define TF_DEATH_ANIMATION_TIME 2.0 // Taunt attack types enum { TAUNTATK_NONE, TAUNTATK_PYRO_HADOUKEN, TAUNTATK_HEAVY_EAT, // 1st Nom TAUNTATK_HEAVY_RADIAL_BUFF, // 2nd Nom gives hp TAUNTATK_SCOUT_DRINK, TAUNTATK_HEAVY_HIGH_NOON, // POW! TAUNTATK_SCOUT_GRAND_SLAM, // Sandman TAUNTATK_MEDIC_INHALE, // Oktoberfest TAUNTATK_SPY_FENCING_SLASH_A, // Just lay TAUNTATK_SPY_FENCING_SLASH_B, // Your weapon down TAUNTATK_SPY_FENCING_STAB, // And walk away. TAUNTATK_RPS_KILL, TAUNTATK_SNIPER_ARROW_STAB_IMPALE, // Stab stab TAUNTATK_SNIPER_ARROW_STAB_KILL, // STAB TAUNTATK_SOLDIER_GRENADE_KILL, // Equalizer TAUNTATK_DEMOMAN_BARBARIAN_SWING, TAUNTATK_MEDIC_UBERSLICE_IMPALE, // I'm going to saw TAUNTATK_MEDIC_UBERSLICE_KILL, // THROUGH YOUR BONES! TAUNTATK_FLIP_LAND_PARTICLE, TAUNTATK_RPS_PARTICLE, TAUNTATK_HIGHFIVE_PARTICLE, TAUNTATK_ENGINEER_GUITAR_SMASH, TAUNTATK_ENGINEER_ARM_IMPALE, // Grinder Start TAUNTATK_ENGINEER_ARM_KILL, // Grinder Kill TAUNTATK_ENGINEER_ARM_BLEND, // Grinder Loop TAUNTATK_SOLDIER_GRENADE_KILL_WORMSIGN, TAUNTATK_SHOW_ITEM, TAUNTATK_MEDIC_RELEASE_DOVES, TAUNTATK_PYRO_ARMAGEDDON, TAUNTATK_PYRO_SCORCHSHOT, TAUNTATK_ALLCLASS_GUITAR_RIFF, TAUNTATK_MEDIC_HEROIC_TAUNT, TAUNTATK_PYRO_GASBLAST, }; typedef enum { HUD_NOTIFY_YOUR_FLAG_TAKEN, HUD_NOTIFY_YOUR_FLAG_DROPPED, HUD_NOTIFY_YOUR_FLAG_RETURNED, HUD_NOTIFY_YOUR_FLAG_CAPTURED, HUD_NOTIFY_ENEMY_FLAG_TAKEN, HUD_NOTIFY_ENEMY_FLAG_DROPPED, HUD_NOTIFY_ENEMY_FLAG_RETURNED, HUD_NOTIFY_ENEMY_FLAG_CAPTURED, HUD_NOTIFY_TOUCHING_ENEMY_CTF_CAP, HUD_NOTIFY_NO_INVULN_WITH_FLAG, HUD_NOTIFY_NO_TELE_WITH_FLAG, HUD_NOTIFY_SPECIAL, HUD_NOTIFY_GOLDEN_WRENCH, HUD_NOTIFY_RD_ROBOT_ATTACKED, HUD_NOTIFY_HOW_TO_CONTROL_GHOST, HUD_NOTIFY_HOW_TO_CONTROL_KART, HUD_NOTIFY_PASSTIME_HOWTO, HUD_NOTIFY_PASSTIME_BALL_BASKET, HUD_NOTIFY_PASSTIME_BALL_ENDZONE, HUD_NOTIFY_PASSTIME_SCORE, HUD_NOTIFY_PASSTIME_FRIENDLY_SCORE, HUD_NOTIFY_PASSTIME_ENEMY_SCORE, HUD_NOTIFY_PASSTIME_NO_TELE, HUD_NOTIFY_PASSTIME_NO_CARRY, HUD_NOTIFY_PASSTIME_NO_INVULN, HUD_NOTIFY_PASSTIME_NO_DISGUISE, HUD_NOTIFY_PASSTIME_NO_CLOAK, HUD_NOTIFY_PASSTIME_NO_OOB, HUD_NOTIFY_PASSTIME_NO_HOLSTER, HUD_NOTIFY_PASSTIME_NO_TAUNT, NUM_STOCK_NOTIFICATIONS } HudNotification_t; class CTraceFilterIgnorePlayers : public CTraceFilterSimple { public: // It does have a base, but we'll never network anything below here.. DECLARE_CLASS( CTraceFilterIgnorePlayers, CTraceFilterSimple ); CTraceFilterIgnorePlayers( const IHandleEntity *passentity, int collisionGroup ) : CTraceFilterSimple( passentity, collisionGroup ) { } virtual bool ShouldHitEntity( IHandleEntity *pServerEntity, int contentsMask ) { CBaseEntity *pEntity = EntityFromEntityHandle( pServerEntity ); return pEntity && !pEntity->IsPlayer(); } }; class CTraceFilterIgnoreTeammatesAndTeamObjects : public CTraceFilterSimple { public: // It does have a base, but we'll never network anything below here.. DECLARE_CLASS( CTraceFilterIgnoreTeammatesAndTeamObjects, CTraceFilterSimple ); CTraceFilterIgnoreTeammatesAndTeamObjects( const IHandleEntity *passentity, int collisionGroup, int teamNumber ) : CTraceFilterSimple( passentity, collisionGroup ) { m_iTeamNumber = teamNumber; } virtual bool ShouldHitEntity( IHandleEntity *pServerEntity, int contentsMask ) { CBaseEntity *pEntity = EntityFromEntityHandle( pServerEntity ); if ( pEntity && pEntity->GetTeamNumber() == m_iTeamNumber ) return false; return BaseClass::ShouldHitEntity( pServerEntity, contentsMask ); } private: int m_iTeamNumber; }; // Unused #define TF_DEATH_FIRST_BLOOD 0x0010 #define TF_DEATH_FEIGN_DEATH 0x0020 #define TF_DEATH_GIB 0x0080 #define TF_DEATH_PURGATORY 0x0100 #define TF_DEATH_AUSTRALIUM 0x0400 #define HUD_ALERT_SCRAMBLE_TEAMS 0 #define TF_CAMERA_DIST 64 #define TF_CAMERA_DIST_RIGHT 30 #define TF_CAMERA_DIST_UP 0 #endif // TF_SHAREDDEFS_H <|start_filename|>src/game/shared/tf/tf_weapon_medigun.cpp<|end_filename|> //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: The Medic's Medikit weapon // // // $Workfile: $ // $Date: $ // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "in_buttons.h" #include "engine/IEngineSound.h" #include "tf_gamerules.h" #if defined( CLIENT_DLL ) #include <vgui_controls/Panel.h> #include <vgui/ISurface.h> #include "particles_simple.h" #include "c_tf_player.h" #include "soundenvelope.h" #else #include "ndebugoverlay.h" #include "tf_player.h" #include "tf_team.h" #include "tf_gamestats.h" #include "ilagcompensationmanager.h" #endif #include "tf_weapon_medigun.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" const char *g_pszMedigunHealSounds[TF_MEDIGUN_COUNT] = { "WeaponMedigun.Healing", "WeaponMedigun.Healing", "Weapon_Quick_Fix.Healing", "WeaponMedigun_Vaccinator.Healing", "WeaponMedigun.Healing" }; // Buff ranges ConVar weapon_medigun_damage_modifier( "weapon_medigun_damage_modifier", "1.5", FCVAR_CHEAT | FCVAR_REPLICATED | FCVAR_DEVELOPMENTONLY, "Scales the damage a player does while being healed with the medigun." ); ConVar weapon_medigun_construction_rate( "weapon_medigun_construction_rate", "10", FCVAR_CHEAT | FCVAR_REPLICATED | FCVAR_DEVELOPMENTONLY, "Constructing object health healed per second by the medigun." ); ConVar weapon_medigun_charge_rate( "weapon_medigun_charge_rate", "40", FCVAR_CHEAT | FCVAR_REPLICATED | FCVAR_DEVELOPMENTONLY, "Amount of time healing it takes to fully charge the medigun." ); ConVar weapon_medigun_chargerelease_rate( "weapon_medigun_chargerelease_rate", "8", FCVAR_CHEAT | FCVAR_REPLICATED | FCVAR_DEVELOPMENTONLY, "Amount of time it takes the a full charge of the medigun to be released." ); #if defined (CLIENT_DLL) ConVar tf_medigun_autoheal( "tf_medigun_autoheal", "0", FCVAR_CLIENTDLL | FCVAR_ARCHIVE | FCVAR_USERINFO, "Setting this to 1 will cause the Medigun's primary attack to be a toggle instead of needing to be held down." ); #endif #if !defined (CLIENT_DLL) ConVar tf_medigun_lagcomp( "tf_medigun_lagcomp", "1", FCVAR_DEVELOPMENTONLY ); #endif #ifdef CLIENT_DLL //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void RecvProxy_HealingTarget( const CRecvProxyData *pData, void *pStruct, void *pOut ) { CWeaponMedigun *pMedigun = ((CWeaponMedigun*)(pStruct)); if ( pMedigun != NULL ) { pMedigun->ForceHealingTargetUpdate(); } RecvProxy_IntToEHandle( pData, pStruct, pOut ); } #endif LINK_ENTITY_TO_CLASS( tf_weapon_medigun, CWeaponMedigun ); PRECACHE_WEAPON_REGISTER( tf_weapon_medigun ); IMPLEMENT_NETWORKCLASS_ALIASED( WeaponMedigun, DT_WeaponMedigun ) BEGIN_NETWORK_TABLE( CWeaponMedigun, DT_WeaponMedigun ) #if !defined( CLIENT_DLL ) SendPropFloat( SENDINFO( m_flChargeLevel ), 0, SPROP_NOSCALE | SPROP_CHANGES_OFTEN ), SendPropEHandle( SENDINFO( m_hHealingTarget ) ), SendPropBool( SENDINFO( m_bHealing ) ), SendPropBool( SENDINFO( m_bAttacking ) ), SendPropBool( SENDINFO( m_bChargeRelease ) ), SendPropBool( SENDINFO( m_bHolstered ) ), #else RecvPropFloat( RECVINFO(m_flChargeLevel) ), RecvPropEHandle( RECVINFO( m_hHealingTarget ), RecvProxy_HealingTarget ), RecvPropBool( RECVINFO( m_bHealing ) ), RecvPropBool( RECVINFO( m_bAttacking ) ), RecvPropBool( RECVINFO( m_bChargeRelease ) ), RecvPropBool( RECVINFO( m_bHolstered ) ), #endif END_NETWORK_TABLE() #ifdef CLIENT_DLL BEGIN_PREDICTION_DATA( CWeaponMedigun ) DEFINE_PRED_FIELD( m_bHealing, FIELD_BOOLEAN, FTYPEDESC_INSENDTABLE ), DEFINE_PRED_FIELD( m_bAttacking, FIELD_BOOLEAN, FTYPEDESC_INSENDTABLE ), DEFINE_PRED_FIELD( m_bHolstered, FIELD_BOOLEAN, FTYPEDESC_INSENDTABLE ), DEFINE_PRED_FIELD( m_hHealingTarget, FIELD_EHANDLE, FTYPEDESC_INSENDTABLE ), DEFINE_FIELD( m_flHealEffectLifetime, FIELD_FLOAT ), DEFINE_PRED_FIELD( m_flChargeLevel, FIELD_FLOAT, FTYPEDESC_INSENDTABLE ), DEFINE_PRED_FIELD( m_bChargeRelease, FIELD_BOOLEAN, FTYPEDESC_INSENDTABLE ), // DEFINE_PRED_FIELD( m_bPlayingSound, FIELD_BOOLEAN ), // DEFINE_PRED_FIELD( m_bUpdateHealingTargets, FIELD_BOOLEAN ), END_PREDICTION_DATA() #endif #define PARTICLE_PATH_VEL 140.0 #define NUM_PATH_PARTICLES_PER_SEC 300.0f #define NUM_MEDIGUN_PATH_POINTS 8 extern ConVar tf_max_health_boost; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CWeaponMedigun::CWeaponMedigun( void ) { WeaponReset(); SetPredictionEligible( true ); } CWeaponMedigun::~CWeaponMedigun() { #ifdef CLIENT_DLL if ( m_pChargedSound ) { CSoundEnvelopeController::GetController().SoundDestroy( m_pChargedSound ); } #endif } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponMedigun::WeaponReset( void ) { BaseClass::WeaponReset(); m_flHealEffectLifetime = 0; m_bHealing = false; m_bAttacking = false; m_bHolstered = true; m_bChargeRelease = false; m_bCanChangeTarget = true; m_flNextBuzzTime = 0; m_flReleaseStartedAt = 0; m_flChargeLevel = 0.0f; RemoveHealingTarget( true ); #if defined( CLIENT_DLL ) m_bPlayingSound = false; m_bUpdateHealingTargets = false; m_bOldChargeRelease = false; UpdateEffects(); ManageChargeEffect(); m_pChargeEffect = NULL; m_pChargedSound = NULL; #endif } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponMedigun::Precache() { BaseClass::Precache(); int iType = GetMedigunType(); PrecacheScriptSound( g_pszMedigunHealSounds[iType] ); PrecacheScriptSound( "WeaponMedigun.NoTarget" ); PrecacheScriptSound( "WeaponMedigun.Charged" ); PrecacheScriptSound( "WeaponMedigun.HealingDetach" ); PrecacheTeamParticles( "medicgun_invulnstatus_fullcharge_%s" ); PrecacheTeamParticles( "medicgun_beam_%s" ); PrecacheTeamParticles( "medicgun_beam_%s_invun" ); // Precache charge sounds. for ( int i = 0; i < TF_CHARGE_COUNT; i++ ) { PrecacheScriptSound( g_MedigunEffects[i].sound_enable ); PrecacheScriptSound( g_MedigunEffects[i].sound_disable ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CWeaponMedigun::Deploy( void ) { if ( BaseClass::Deploy() ) { m_bHolstered = false; #ifdef GAME_DLL CTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() ); if ( m_bChargeRelease && pOwner ) { pOwner->m_Shared.RecalculateChargeEffects(); } #endif #ifdef CLIENT_DLL ManageChargeEffect(); #endif m_flNextTargetCheckTime = gpGlobals->curtime; return true; } return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CWeaponMedigun::Holster( CBaseCombatWeapon *pSwitchingTo ) { RemoveHealingTarget( true ); m_bAttacking = false; m_bHolstered = true; #ifdef GAME_DLL CTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() ); if ( pOwner ) { pOwner->m_Shared.RecalculateChargeEffects( true ); } #endif #ifdef CLIENT_DLL UpdateEffects(); ManageChargeEffect(); #endif return BaseClass::Holster( pSwitchingTo ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponMedigun::UpdateOnRemove( void ) { RemoveHealingTarget( true ); m_bAttacking = false; m_bChargeRelease = false; m_bHolstered = true; #ifndef CLIENT_DLL CTFPlayer *pOwner = GetTFPlayerOwner(); if ( pOwner ) { pOwner->m_Shared.RecalculateChargeEffects( true ); } #else if ( m_bPlayingSound ) { m_bPlayingSound = false; StopHealSound(); } UpdateEffects(); ManageChargeEffect(); #endif BaseClass::UpdateOnRemove(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- float CWeaponMedigun::GetTargetRange( void ) { return (float)m_pWeaponInfo->GetWeaponData( m_iWeaponMode ).m_flRange; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- float CWeaponMedigun::GetStickRange( void ) { return (GetTargetRange() * 1.2); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- float CWeaponMedigun::GetHealRate( void ) { float flHealRate = (float)m_pWeaponInfo->GetWeaponData( m_iWeaponMode ).m_nDamage; CALL_ATTRIB_HOOK_FLOAT( flHealRate, mult_medigun_healrate ); return flHealRate; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CWeaponMedigun::GetMedigunType( void ) { int iType = 0; CALL_ATTRIB_HOOK_INT( iType, set_weapon_mode ); if ( iType >= 0 && iType < TF_MEDIGUN_COUNT ) return iType; AssertMsg( 0, "Invalid medigun type!\n" ); return TF_MEDIGUN_STOCK; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- medigun_charge_types CWeaponMedigun::GetChargeType( void ) { int iChargeType = TF_CHARGE_INVULNERABLE; CALL_ATTRIB_HOOK_INT( iChargeType, set_charge_type ); if ( iChargeType > TF_CHARGE_NONE && iChargeType < TF_CHARGE_COUNT ) return (medigun_charge_types)iChargeType; AssertMsg( 0, "Invalid charge type!\n" ); return TF_CHARGE_NONE; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- const char *CWeaponMedigun::GetHealSound( void ) { return g_pszMedigunHealSounds[GetMedigunType()]; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CWeaponMedigun::HealingTarget( CBaseEntity *pTarget ) { if ( pTarget == m_hHealingTarget ) return true; return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CWeaponMedigun::AllowedToHealTarget( CBaseEntity *pTarget ) { CTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() ); if ( !pOwner ) return false; CTFPlayer *pTFPlayer = ToTFPlayer( pTarget ); if ( !pTFPlayer ) return false; bool bStealthed = pTFPlayer->m_Shared.InCond( TF_COND_STEALTHED ); bool bDisguised = pTFPlayer->m_Shared.InCond( TF_COND_DISGUISED ); // We can heal teammates and enemies that are disguised as teammates if ( !bStealthed && ( pTFPlayer->InSameTeam( pOwner ) || ( bDisguised && pTFPlayer->m_Shared.GetDisguiseTeam() == pOwner->GetTeamNumber() ) ) ) { return true; } return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CWeaponMedigun::CouldHealTarget( CBaseEntity *pTarget ) { CTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() ); if ( !pOwner ) return false; if ( pTarget->IsPlayer() && pTarget->IsAlive() && !HealingTarget(pTarget) ) return AllowedToHealTarget( pTarget ); return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponMedigun::MaintainTargetInSlot() { CTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() ); if ( !pOwner ) return; CBaseEntity *pTarget = m_hHealingTarget; Assert( pTarget ); // Make sure the guy didn't go out of range. bool bLostTarget = true; Vector vecSrc = pOwner->Weapon_ShootPosition( ); Vector vecTargetPoint = pTarget->WorldSpaceCenter(); Vector vecPoint; // If it's brush built, use absmins/absmaxs pTarget->CollisionProp()->CalcNearestPoint( vecSrc, &vecPoint ); float flDistance = (vecPoint - vecSrc).Length(); if ( flDistance < GetStickRange() ) { if ( m_flNextTargetCheckTime > gpGlobals->curtime ) return; m_flNextTargetCheckTime = gpGlobals->curtime + 1.0f; trace_t tr; CMedigunFilter drainFilter( pOwner ); Vector vecAiming; pOwner->EyeVectors( &vecAiming ); Vector vecEnd = vecSrc + vecAiming * GetTargetRange(); UTIL_TraceLine( vecSrc, vecEnd, (MASK_SHOT & ~CONTENTS_HITBOX), pOwner, DMG_GENERIC, &tr ); // Still visible? if ( tr.m_pEnt == pTarget ) return; UTIL_TraceLine( vecSrc, vecTargetPoint, MASK_SHOT, &drainFilter, &tr ); // Still visible? if (( tr.fraction == 1.0f) || (tr.m_pEnt == pTarget)) return; // If we failed, try the target's eye point as well UTIL_TraceLine( vecSrc, pTarget->EyePosition(), MASK_SHOT, &drainFilter, &tr ); if (( tr.fraction == 1.0f) || (tr.m_pEnt == pTarget)) return; } // We've lost this guy if ( bLostTarget ) { RemoveHealingTarget(); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponMedigun::FindNewTargetForSlot() { CTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() ); if ( !pOwner ) return; Vector vecSrc = pOwner->Weapon_ShootPosition( ); if ( m_hHealingTarget ) { RemoveHealingTarget(); } // In Normal mode, we heal players under our crosshair Vector vecAiming; pOwner->EyeVectors( &vecAiming ); // Find a player in range of this player, and make sure they're healable. Vector vecEnd = vecSrc + vecAiming * GetTargetRange(); trace_t tr; UTIL_TraceLine( vecSrc, vecEnd, (MASK_SHOT & ~CONTENTS_HITBOX), pOwner, DMG_GENERIC, &tr ); if ( tr.fraction != 1.0 && tr.m_pEnt ) { if ( CouldHealTarget( tr.m_pEnt ) ) { #ifdef GAME_DLL pOwner->SpeakConceptIfAllowed( MP_CONCEPT_MEDIC_STARTEDHEALING ); if ( tr.m_pEnt->IsPlayer() ) { CTFPlayer *pTarget = ToTFPlayer( tr.m_pEnt ); pTarget->SpeakConceptIfAllowed( MP_CONCEPT_HEALTARGET_STARTEDHEALING ); } // Start the heal target thinking. SetContextThink( &CWeaponMedigun::HealTargetThink, gpGlobals->curtime, s_pszMedigunHealTargetThink ); #endif m_hHealingTarget.Set( tr.m_pEnt ); m_flNextTargetCheckTime = gpGlobals->curtime + 1.0f; } } } #ifdef GAME_DLL //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponMedigun::HealTargetThink( void ) { // Verify that we still have a valid heal target. CBaseEntity *pTarget = m_hHealingTarget; if ( !pTarget || !pTarget->IsAlive() ) { SetContextThink( NULL, 0, s_pszMedigunHealTargetThink ); return; } CTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() ); if ( !pOwner ) return; float flTime = gpGlobals->curtime - pOwner->GetTimeBase(); if ( flTime > 5.0f || !AllowedToHealTarget(pTarget) ) { RemoveHealingTarget( false ); } SetNextThink( gpGlobals->curtime + 0.2f, s_pszMedigunHealTargetThink ); } #endif //----------------------------------------------------------------------------- // Purpose: Returns a pointer to a healable target //----------------------------------------------------------------------------- bool CWeaponMedigun::FindAndHealTargets( void ) { CTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() ); if ( !pOwner ) return false; bool bFound = false; // Maintaining beam to existing target? CBaseEntity *pTarget = m_hHealingTarget; if ( pTarget && pTarget->IsAlive() ) { MaintainTargetInSlot(); } else { FindNewTargetForSlot(); } CBaseEntity *pNewTarget = m_hHealingTarget; if ( pNewTarget && pNewTarget->IsAlive() ) { CTFPlayer *pTFPlayer = ToTFPlayer( pNewTarget ); #ifdef GAME_DLL // HACK: For now, just deal with players if ( pTFPlayer ) { if ( pTarget != pNewTarget && pNewTarget->IsPlayer() ) { pTFPlayer->m_Shared.Heal( pOwner, GetHealRate() ); } pTFPlayer->m_Shared.RecalculateChargeEffects( false ); } if ( m_flReleaseStartedAt && m_flReleaseStartedAt < (gpGlobals->curtime + 0.2) ) { // When we start the release, everyone we heal rockets to full health pNewTarget->TakeHealth( pNewTarget->GetMaxHealth(), DMG_GENERIC ); } #endif bFound = true; // Charge up our power if we're not releasing it, and our target // isn't receiving any benefit from our healing. if ( !m_bChargeRelease ) { if ( pTFPlayer ) { int iBoostMax = floor( pTFPlayer->m_Shared.GetMaxBuffedHealth() * 0.95); if ( weapon_medigun_charge_rate.GetFloat() ) { float flChargeAmount = gpGlobals->frametime / weapon_medigun_charge_rate.GetFloat(); CALL_ATTRIB_HOOK_FLOAT( flChargeAmount, mult_medigun_uberchargerate ); if ( TFGameRules() && TFGameRules()->InSetup() ) { // Build charge at triple rate during setup flChargeAmount *= 3.0f; } else if ( pNewTarget->GetHealth() >= iBoostMax ) { // Reduced charge for healing fully healed guys flChargeAmount *= 0.5f; } int iTotalHealers = pTFPlayer->m_Shared.GetNumHealers(); if ( iTotalHealers > 1 ) { flChargeAmount /= (float)iTotalHealers; } float flNewLevel = min( m_flChargeLevel + flChargeAmount, 1.0 ); #ifdef GAME_DLL if ( flNewLevel >= 1.0 && m_flChargeLevel < 1.0 ) { pOwner->SpeakConceptIfAllowed( MP_CONCEPT_MEDIC_CHARGEREADY ); if ( pTFPlayer ) { pTFPlayer->SpeakConceptIfAllowed( MP_CONCEPT_HEALTARGET_CHARGEREADY ); } } #endif m_flChargeLevel = flNewLevel; } } } } return bFound; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponMedigun::AddCharge( float flAmount ) { float flChargeRate = 1.0f; CALL_ATTRIB_HOOK_FLOAT( flChargeRate, mult_medigun_uberchargerate ); if ( !flChargeRate ) // Can't earn uber. return; float flNewLevel = min( m_flChargeLevel + flAmount, 1.0 ); #ifdef GAME_DLL CTFPlayer *pPlayer = GetTFPlayerOwner(); CTFPlayer *pHealingTarget = ToTFPlayer( m_hHealingTarget ); if ( !m_bChargeRelease && flNewLevel >= 1.0 && m_flChargeLevel < 1.0 ) { if ( pPlayer ) { pPlayer->SpeakConceptIfAllowed( MP_CONCEPT_MEDIC_CHARGEREADY ); } if ( pHealingTarget ) { pHealingTarget->SpeakConceptIfAllowed( MP_CONCEPT_HEALTARGET_CHARGEREADY ); } } #endif m_flChargeLevel = flNewLevel; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponMedigun::ItemHolsterFrame( void ) { BaseClass::ItemHolsterFrame(); DrainCharge(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponMedigun::DrainCharge( void ) { // If we're in charge release mode, drain our charge if ( m_bChargeRelease ) { CTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() ); if ( !pOwner ) return; float flChargeAmount = gpGlobals->frametime / weapon_medigun_chargerelease_rate.GetFloat(); m_flChargeLevel = max( m_flChargeLevel - flChargeAmount, 0.0 ); if ( !m_flChargeLevel ) { m_bChargeRelease = false; m_flReleaseStartedAt = 0; #ifdef GAME_DLL /* if ( m_bHealingSelf ) { m_bHealingSelf = false; pOwner->m_Shared.StopHealing( pOwner ); } */ pOwner->m_Shared.RecalculateChargeEffects(); #endif } } } //----------------------------------------------------------------------------- // Purpose: Overloaded to handle the hold-down healing //----------------------------------------------------------------------------- void CWeaponMedigun::ItemPostFrame( void ) { CTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() ); if ( !pOwner ) return; // If we're lowered, we're not allowed to fire if ( CanAttack() == false ) { RemoveHealingTarget( true ); return; } #if !defined( CLIENT_DLL ) if ( AppliesModifier() ) { m_DamageModifier.SetModifier( weapon_medigun_damage_modifier.GetFloat() ); } #endif // Try to start healing m_bAttacking = false; if ( pOwner->GetMedigunAutoHeal() ) { if ( pOwner->m_nButtons & IN_ATTACK ) { if ( m_bCanChangeTarget ) { RemoveHealingTarget(); #if defined( CLIENT_DLL ) m_bPlayingSound = false; StopHealSound(); #endif // can't change again until we release the attack button m_bCanChangeTarget = false; } } else { m_bCanChangeTarget = true; } if ( m_bHealing || ( pOwner->m_nButtons & IN_ATTACK ) ) { PrimaryAttack(); m_bAttacking = true; } } else { if ( /*m_bChargeRelease || */ pOwner->m_nButtons & IN_ATTACK ) { PrimaryAttack(); m_bAttacking = true; } else if ( m_bHealing ) { // Detach from the player if they release the attack button. RemoveHealingTarget(); } } if ( pOwner->m_nButtons & IN_ATTACK2 ) { SecondaryAttack(); } WeaponIdle(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CWeaponMedigun::Lower( void ) { // Stop healing if we are if ( m_bHealing ) { RemoveHealingTarget( true ); m_bAttacking = false; #ifdef CLIENT_DLL UpdateEffects(); #endif } return BaseClass::Lower(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponMedigun::RemoveHealingTarget( bool bSilent ) { CTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() ); if ( !pOwner ) return; #ifdef GAME_DLL if ( m_hHealingTarget ) { // HACK: For now, just deal with players if ( m_hHealingTarget->IsPlayer() ) { CTFPlayer *pTFPlayer = ToTFPlayer( m_hHealingTarget ); pTFPlayer->m_Shared.StopHealing( pOwner ); pTFPlayer->m_Shared.RecalculateChargeEffects( false ); if ( !bSilent ) { pOwner->SpeakConceptIfAllowed( MP_CONCEPT_MEDIC_STOPPEDHEALING, pTFPlayer->IsAlive() ? "healtarget:alive" : "healtarget:dead" ); pTFPlayer->SpeakConceptIfAllowed( MP_CONCEPT_HEALTARGET_STOPPEDHEALING ); } } } // Stop thinking - we no longer have a heal target. SetContextThink( NULL, 0, s_pszMedigunHealTargetThink ); #endif m_hHealingTarget.Set( NULL ); // Stop the welding animation if ( m_bHealing && !bSilent ) { SendWeaponAnim( ACT_MP_ATTACK_STAND_POSTFIRE ); pOwner->DoAnimationEvent( PLAYERANIMEVENT_ATTACK_POST ); } #ifndef CLIENT_DLL m_DamageModifier.RemoveModifier(); #endif m_bHealing = false; } //----------------------------------------------------------------------------- // Purpose: Attempt to heal any player within range of the medikit //----------------------------------------------------------------------------- void CWeaponMedigun::PrimaryAttack( void ) { CTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() ); if ( !pOwner ) return; if ( !CanAttack() ) return; #ifdef GAME_DLL /* // Start boosting ourself if we're not if ( m_bChargeRelease && !m_bHealingSelf ) { pOwner->m_Shared.Heal( pOwner, GetHealRate() * 2 ); m_bHealingSelf = true; } */ #endif #if !defined (CLIENT_DLL) if ( tf_medigun_lagcomp.GetBool() ) lagcompensation->StartLagCompensation( pOwner, pOwner->GetCurrentCommand() ); #endif if ( FindAndHealTargets() ) { // Start the animation if ( !m_bHealing ) { #ifdef GAME_DLL pOwner->SpeakWeaponFire(); #endif SendWeaponAnim( ACT_MP_ATTACK_STAND_PREFIRE ); pOwner->DoAnimationEvent( PLAYERANIMEVENT_ATTACK_PRE ); } m_bHealing = true; } else { RemoveHealingTarget(); } #if !defined (CLIENT_DLL) if ( tf_medigun_lagcomp.GetBool() ) lagcompensation->FinishLagCompensation( pOwner ); #endif } //----------------------------------------------------------------------------- // Purpose: Burn charge level to generate invulnerability //----------------------------------------------------------------------------- void CWeaponMedigun::SecondaryAttack( void ) { CTFPlayer *pOwner = ToTFPlayer( GetOwnerEntity() ); if ( !pOwner ) return; if ( !CanAttack() ) return; // Ensure they have a full charge and are not already in charge release mode if ( m_flChargeLevel < 1.0 || m_bChargeRelease ) { #ifdef CLIENT_DLL // Deny, flash if ( !m_bChargeRelease && m_flFlashCharge <= 0 ) { m_flFlashCharge = 10; pOwner->EmitSound( "Player.DenyWeaponSelection" ); } #endif return; } if ( pOwner->HasTheFlag() ) { #ifdef GAME_DLL CSingleUserRecipientFilter filter( pOwner ); TFGameRules()->SendHudNotification( filter, HUD_NOTIFY_NO_INVULN_WITH_FLAG ); #endif pOwner->EmitSound( "Player.DenyWeaponSelection" ); return; } // Start super charge m_bChargeRelease = true; m_flReleaseStartedAt = 0;//gpGlobals->curtime; #ifdef GAME_DLL CTF_GameStats.Event_PlayerInvulnerable( pOwner ); pOwner->m_Shared.RecalculateChargeEffects(); pOwner->SpeakConceptIfAllowed( MP_CONCEPT_MEDIC_CHARGEDEPLOYED ); if ( m_hHealingTarget && m_hHealingTarget->IsPlayer() ) { CTFPlayer *pTFPlayer = ToTFPlayer( m_hHealingTarget ); pTFPlayer->m_Shared.RecalculateChargeEffects(); pTFPlayer->SpeakConceptIfAllowed( MP_CONCEPT_HEALTARGET_CHARGEDEPLOYED ); } IGameEvent * event = gameeventmanager->CreateEvent( "player_chargedeployed" ); if ( event ) { event->SetInt( "userid", pOwner->GetUserID() ); gameeventmanager->FireEvent( event, true ); // don't send to clients } #endif } //----------------------------------------------------------------------------- // Purpose: Idle tests to see if we're facing a valid target for the medikit // If so, move into the "heal-able" animation. // Otherwise, move into the "not-heal-able" animation. //----------------------------------------------------------------------------- void CWeaponMedigun::WeaponIdle( void ) { if ( HasWeaponIdleTimeElapsed() ) { // Loop the welding animation if ( m_bHealing ) { SendWeaponAnim( ACT_VM_PRIMARYATTACK ); return; } return BaseClass::WeaponIdle(); } } #if defined( CLIENT_DLL ) //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponMedigun::StopHealSound( bool bStopHealingSound, bool bStopNoTargetSound ) { if ( bStopHealingSound ) { StopSound( GetHealSound() ); CLocalPlayerFilter filter; EmitSound( filter, entindex(), "WeaponMedigun.HealingDetach" ); } if ( bStopNoTargetSound ) { StopSound( "WeaponMedigun.NoTarget" ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponMedigun::ManageChargeEffect( void ) { bool bOwnerTaunting = false; if ( GetTFPlayerOwner() && ( GetTFPlayerOwner()->m_Shared.InCond( TF_COND_TAUNTING ) == true || GetTFPlayerOwner()->m_Shared.InCond( TF_COND_STUNNED ) == true) ) { bOwnerTaunting = true; } if ( GetTFPlayerOwner() && bOwnerTaunting == false && m_bHolstered == false && ( m_flChargeLevel >= 1.0f || m_bChargeRelease == true ) ) { C_BaseEntity *pEffectOwner = GetWeaponForEffect(); if ( pEffectOwner && m_pChargeEffect == NULL ) { const char *pszEffectName = ConstructTeamParticle( "medicgun_invulnstatus_fullcharge_%s", GetTFPlayerOwner()->GetTeamNumber() ); m_pChargeEffect = pEffectOwner->ParticleProp()->Create( pszEffectName, PATTACH_POINT_FOLLOW, "muzzle" ); m_hChargeEffectHost = pEffectOwner; } if ( m_pChargedSound == NULL ) { CLocalPlayerFilter filter; CSoundEnvelopeController &controller = CSoundEnvelopeController::GetController(); m_pChargedSound = controller.SoundCreate( filter, entindex(), "WeaponMedigun.Charged" ); controller.Play( m_pChargedSound, 1.0, 100 ); } } else { C_BaseEntity *pEffectOwner = m_hChargeEffectHost.Get(); if ( m_pChargeEffect != NULL ) { if ( pEffectOwner ) { pEffectOwner->ParticleProp()->StopEmission( m_pChargeEffect ); m_hChargeEffectHost = NULL; } m_pChargeEffect = NULL; } if ( m_pChargedSound != NULL ) { CSoundEnvelopeController::GetController().SoundDestroy( m_pChargedSound ); m_pChargedSound = NULL; } } } //----------------------------------------------------------------------------- // Purpose: // Input : updateType - //----------------------------------------------------------------------------- void CWeaponMedigun::OnDataChanged( DataUpdateType_t updateType ) { BaseClass::OnDataChanged( updateType ); if ( m_bUpdateHealingTargets ) { UpdateEffects(); m_bUpdateHealingTargets = false; } // Think? if ( m_bHealing ) { ClientThinkList()->SetNextClientThink( GetClientHandle(), CLIENT_THINK_ALWAYS ); } else { ClientThinkList()->SetNextClientThink( GetClientHandle(), CLIENT_THINK_NEVER ); if ( m_bPlayingSound ) { m_bPlayingSound = false; StopHealSound( true, false ); } // Are they holding the attack button but not healing anyone? Give feedback. if ( IsActiveByLocalPlayer() && GetOwner() && GetOwner()->IsAlive() && m_bAttacking && GetOwner() == C_BasePlayer::GetLocalPlayer() && CanAttack() == true ) { if ( gpGlobals->curtime >= m_flNextBuzzTime ) { CLocalPlayerFilter filter; EmitSound( filter, entindex(), "WeaponMedigun.NoTarget" ); m_flNextBuzzTime = gpGlobals->curtime + 0.5f; // only buzz every so often. } } else { StopHealSound( false, true ); // Stop the "no target" sound. } } ManageChargeEffect(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponMedigun::ClientThink() { C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer(); if ( !pLocalPlayer ) return; // Don't show it while the player is dead. Ideally, we'd respond to m_bHealing in OnDataChanged, // but it stops sending the weapon when it's holstered, and it gets holstered when the player dies. CTFPlayer *pFiringPlayer = ToTFPlayer( GetOwnerEntity() ); if ( !pFiringPlayer || pFiringPlayer->IsPlayerDead() || pFiringPlayer->IsDormant() ) { ClientThinkList()->SetNextClientThink( GetClientHandle(), CLIENT_THINK_NEVER ); if ( m_bPlayingSound ) { m_bPlayingSound = false; StopHealSound(); } return; } // If the local player is the guy getting healed, let him know // who's healing him, and their charge level. if( m_hHealingTarget != NULL ) { if ( pLocalPlayer == m_hHealingTarget ) { pLocalPlayer->SetHealer( pFiringPlayer, m_flChargeLevel ); } if ( !m_bPlayingSound ) { m_bPlayingSound = true; CLocalPlayerFilter filter; EmitSound( filter, entindex(), GetHealSound() ); } } if ( m_bOldChargeRelease != m_bChargeRelease ) { m_bOldChargeRelease = m_bChargeRelease; ForceHealingTargetUpdate(); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CWeaponMedigun::UpdateEffects( void ) { CTFPlayer *pFiringPlayer = ToTFPlayer( GetOwnerEntity() ); if ( !pFiringPlayer ) return; C_BaseEntity *pEffectOwner = m_hHealingTargetEffect.hOwner.Get(); // Remove all the effects if ( m_hHealingTargetEffect.pEffect && pEffectOwner ) { pEffectOwner->ParticleProp()->StopEmission( m_hHealingTargetEffect.pEffect ); pEffectOwner->ParticleProp()->StopEmission( m_hHealingTargetEffect.pCustomEffect ); } m_hHealingTargetEffect.hOwner = NULL; m_hHealingTargetEffect.pTarget = NULL; m_hHealingTargetEffect.pEffect = NULL; m_hHealingTargetEffect.pCustomEffect = NULL; pEffectOwner = GetWeaponForEffect(); // Don't add targets if the medic is dead if ( !pEffectOwner || pFiringPlayer->IsPlayerDead() ) return; // Add our targets // Loops through the healing targets, and make sure we have an effect for each of them if ( m_hHealingTarget ) { if ( m_hHealingTargetEffect.pTarget == m_hHealingTarget ) return; const char *pszFormat = IsReleasingCharge() ? "medicgun_beam_%s_invun" : "medicgun_beam_%s"; const char *pszEffectName = ConstructTeamParticle( pszFormat, GetTeamNumber() ); CNewParticleEffect *pEffect = pEffectOwner->ParticleProp()->Create( pszEffectName, PATTACH_POINT_FOLLOW, "muzzle" ); pEffectOwner->ParticleProp()->AddControlPoint( pEffect, 1, m_hHealingTarget, PATTACH_ABSORIGIN_FOLLOW, NULL, Vector(0,0,50) ); CEconItemDefinition *pStatic = m_Item.GetStaticData(); if ( pStatic ) { EconItemVisuals *pVisuals = pStatic->GetVisuals( GetTeamNumber() ); if ( pVisuals ) { const char *pszCustomEffectName = pVisuals->custom_particlesystem; if ( pszCustomEffectName[0] != '\0' ) { CNewParticleEffect *pCustomEffect = pEffectOwner->ParticleProp()->Create( pszCustomEffectName, PATTACH_POINT_FOLLOW, "muzzle" ); pEffectOwner->ParticleProp()->AddControlPoint( pCustomEffect, 1, m_hHealingTarget, PATTACH_ABSORIGIN_FOLLOW, NULL, Vector(0,0,50) ); m_hHealingTargetEffect.pCustomEffect = pCustomEffect; } } } m_hHealingTargetEffect.hOwner = pEffectOwner; m_hHealingTargetEffect.pTarget = m_hHealingTarget; m_hHealingTargetEffect.pEffect = pEffect; } } #endif <|start_filename|>src/game/shared/econ/econ_wearable.h<|end_filename|> //========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //========================================================================// #ifndef ECON_WEARABLE_H #define ECON_WEARABLE_H #ifdef _WIN32 #pragma once #endif #ifdef CLIENT_DLL #include "particles_new.h" #endif #define MAX_WEARABLES_SENT_FROM_SERVER 5 #define PARTICLE_MODIFY_STRING_SIZE 128 #if defined( CLIENT_DLL ) #define CEconWearable C_EconWearable #endif //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- class CEconWearable : public CEconEntity { DECLARE_CLASS( CEconWearable, CEconEntity ); DECLARE_NETWORKCLASS(); public: virtual void Spawn( void ); virtual bool IsWearable( void ) { return true; } virtual int GetSkin(void); virtual void SetParticle(const char* name); virtual void UpdateWearableBodyGroups( CBasePlayer *pPlayer ); virtual void GiveTo( CBaseEntity *pEntity ); #ifdef GAME_DLL virtual void Equip( CBasePlayer *pPlayer ); virtual void UnEquip( CBasePlayer *pPlayer ); virtual void SetExtraWearable( bool bExtraWearable ) { m_bExtraWearable = bExtraWearable; } virtual bool IsExtraWearable( void ) { return m_bExtraWearable; } #else virtual void OnDataChanged(DataUpdateType_t type); virtual ShadowType_t ShadowCastType( void ); virtual bool ShouldDraw( void ); #endif protected: #ifdef GAME_DLL CNetworkVar( bool, m_bExtraWearable ); #else bool m_bExtraWearable; #endif private: #ifdef GAME_DLL CNetworkString(m_ParticleName, PARTICLE_MODIFY_STRING_SIZE); #else char m_ParticleName[PARTICLE_MODIFY_STRING_SIZE]; CNewParticleEffect *m_pUnusualParticle; #endif }; #endif <|start_filename|>src/game/client/tf/tf_notificationmanager.cpp<|end_filename|> #include "cbase.h" #include "tf_notificationmanager.h" #include "tf_mainmenu.h" #include "filesystem.h" #include "script_parser.h" #include "tf_gamerules.h" #include "tf_hud_notification_panel.h" //#include "public\steam\matchmakingtypes.h" static CTFNotificationManager g_TFNotificationManager; CTFNotificationManager *GetNotificationManager() { return &g_TFNotificationManager; } CON_COMMAND_F(tf2c_updateserverlist, "Check for the messages", FCVAR_DEVELOPMENTONLY) { GetNotificationManager()->UpdateServerlistInfo(); } ConVar tf2c_updatefrequency("tf2c_updatefrequency", "15", FCVAR_DEVELOPMENTONLY, "Updatelist update frequency (seconds)"); bool ServerLessFunc(const int &lhs, const int &rhs) { return lhs < rhs; } //----------------------------------------------------------------------------- // Purpose: constructor //----------------------------------------------------------------------------- CTFNotificationManager::CTFNotificationManager() : CAutoGameSystemPerFrame("CTFNotificationManager") { if (!filesystem) return; m_bInited = false; Init(); } CTFNotificationManager::~CTFNotificationManager() { } //----------------------------------------------------------------------------- // Purpose: Initializer //----------------------------------------------------------------------------- bool CTFNotificationManager::Init() { if (!m_bInited) { m_SteamHTTP = steamapicontext->SteamHTTP(); m_mapServers.SetLessFunc(ServerLessFunc); fUpdateLastCheck = tf2c_updatefrequency.GetFloat() * -1; bCompleted = false; m_bInited = true; hRequest = 0; MatchMakingKeyValuePair_t filter; Q_strncpy(filter.m_szKey, "gamedir", sizeof(filter.m_szKey)); Q_strncpy(filter.m_szValue, "tf2vintage", sizeof(filter.m_szKey)); // change "tf2vintage" to engine->GetGameDirectory() before the release m_vecServerFilters.AddToTail(filter); } return true; } void CTFNotificationManager::Update(float frametime) { if (!MAINMENU_ROOT->InGame() && gpGlobals->curtime - fUpdateLastCheck > tf2c_updatefrequency.GetFloat()) { fUpdateLastCheck = gpGlobals->curtime; UpdateServerlistInfo(); } } //----------------------------------------------------------------------------- // Purpose: Event handler //----------------------------------------------------------------------------- void CTFNotificationManager::FireGameEvent(IGameEvent *event) { } void CTFNotificationManager::UpdateServerlistInfo() { ISteamMatchmakingServers *pMatchmaking = steamapicontext->SteamMatchmakingServers(); if ( !pMatchmaking || pMatchmaking->IsRefreshing( hRequest ) ) return; MatchMakingKeyValuePair_t *pFilters; int nFilters = GetServerFilters(&pFilters); hRequest = pMatchmaking->RequestInternetServerList( engine->GetAppID(), &pFilters, nFilters, this ); } gameserveritem_t CTFNotificationManager::GetServerInfo(int index) { return m_mapServers[index]; }; void CTFNotificationManager::ServerResponded(HServerListRequest hRequest, int iServer) { gameserveritem_t *pServerItem = steamapicontext->SteamMatchmakingServers()->GetServerDetails(hRequest, iServer); int index = m_mapServers.Find(iServer); if (index == m_mapServers.InvalidIndex()) { m_mapServers.Insert(iServer, *pServerItem); //Msg("%i SERVER %s (%s): PING %i, PLAYERS %i/%i, MAP %s\n", iServer, pServerItem->GetName(), pServerItem->m_NetAdr.GetQueryAddressString(), //pServerItem->m_nPing, pServerItem->m_nPlayers, pServerItem->m_nMaxPlayers, pServerItem->m_szMap); } else { m_mapServers[index] = *pServerItem; } } void CTFNotificationManager::RefreshComplete(HServerListRequest hRequest, EMatchMakingServerResponse response) { MAINMENU_ROOT->SetServerlistSize(m_mapServers.Count()); MAINMENU_ROOT->OnServerInfoUpdate(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- uint32 CTFNotificationManager::GetServerFilters(MatchMakingKeyValuePair_t **pFilters) { *pFilters = m_vecServerFilters.Base(); return m_vecServerFilters.Count(); } char* CTFNotificationManager::GetVersionString() { char verString[30]; if (g_pFullFileSystem->FileExists("version.txt")) { FileHandle_t fh = filesystem->Open("version.txt", "r", "MOD"); int file_len = filesystem->Size(fh); char* GameInfo = new char[file_len + 1]; filesystem->Read((void*)GameInfo, file_len, fh); GameInfo[file_len] = 0; // null terminator filesystem->Close(fh); Q_snprintf(verString, sizeof(verString), GameInfo + 8); delete[] GameInfo; } char *szResult = (char*)malloc(sizeof(verString)); Q_strncpy(szResult, verString, sizeof(verString)); return szResult; }
AnthonyPython/TF2Vintage_razorback
<|start_filename|>Makefile<|end_filename|> .PHONY: fmt fmt: poetry run isort . poetry run black . .PHONY: chk chk: poetry run isort -c . poetry run black --check --diff .
jobteaser-oss/PyAthena
<|start_filename|>examples/export-4.html<|end_filename|> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>ADR Documents</title> <style type="text/css"> html { color: #333; background: #fff; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; text-rendering: optimizelegibility; } /* 如果你的项目仅支持 IE9+ | Chrome | Firefox 等,推荐在 <html> 中添加 .borderbox 这个 class */ html.borderbox *, html.borderbox *:before, html.borderbox *:after { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } /* 内外边距通常让各个浏览器样式的表现位置不同 */ body, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, code, form, fieldset, legend, input, textarea, p, blockquote, th, td, hr, button, article, aside, details, figcaption, figure, footer, header, menu, nav, section { margin: 0; padding: 0; } /* 重设 HTML5 标签, IE 需要在 js 中 createElement(TAG) */ article, aside, details, figcaption, figure, footer, header, menu, nav, section { display: block; } /* HTML5 媒体文件跟 img 保持一致 */ audio, canvas, video { display: inline-block; } /* 要注意表单元素并不继承父级 font 的问题 */ body, button, input, select, textarea { font: 300 1em/1.8 PingFang SC, Lantinghei SC, Microsoft Yahei, Hiragino Sans GB, Microsoft Sans Serif, WenQuanYi Micro Hei, sans-serif; } button::-moz-focus-inner, input::-moz-focus-inner { padding: 0; border: 0; } /* 去掉各Table cell 的边距并让其边重合 */ table { border-collapse: collapse; border-spacing: 0; } /* 去除默认边框 */ fieldset, img { border: 0; } /* 块/段落引用 */ blockquote { position: relative; color: #999; font-weight: 400; border-left: 1px solid #1abc9c; padding-left: 1em; margin: 1em 3em 1em 2em; } @media only screen and ( max-width: 640px ) { blockquote { margin: 1em 0; } } /* Firefox 以外,元素没有下划线,需添加 */ acronym, abbr { border-bottom: 1px dotted; font-variant: normal; } /* 添加鼠标问号,进一步确保应用的语义是正确的(要知道,交互他们也有洁癖,如果你不去掉,那得多花点口舌) */ abbr { cursor: help; } /* 一致的 del 样式 */ del { text-decoration: line-through; } address, caption, cite, code, dfn, em, th, var { font-style: normal; font-weight: 400; } /* 去掉列表前的标识, li 会继承,大部分网站通常用列表来很多内容,所以应该当去 */ ul, ol { list-style: none; } /* 对齐是排版最重要的因素, 别让什么都居中 */ caption, th { text-align: left; } q:before, q:after { content: ''; } /* 统一上标和下标 */ sub, sup { font-size: 75%; line-height: 0; position: relative; } :root sub, :root sup { vertical-align: baseline; /* for ie9 and other modern browsers */ } sup { top: -0.5em; } sub { bottom: -0.25em; } /* 让链接在 hover 状态下显示下划线 */ a { color: #1abc9c; } a:hover { text-decoration: underline; } .typo a { border-bottom: 1px solid #1abc9c; } .typo a:hover { border-bottom-color: #555; color: #555; text-decoration: none; } /* 默认不显示下划线,保持页面简洁 */ ins, a { text-decoration: none; } /* 专名号:虽然 u 已经重回 html5 Draft,但在所有浏览器中都是可以使用的, * 要做到更好,向后兼容的话,添加 class="typo-u" 来显示专名号 * 关于 <u> 标签:http://www.whatwg.org/specs/web-apps/current-work/multipage/text-level-semantics.html#the-u-element * 被放弃的是 4,之前一直搞错 http://www.w3.org/TR/html401/appendix/changes.html#idx-deprecated * 一篇关于 <u> 标签的很好文章:http://html5doctor.com/u-element/ */ u, .typo-u { text-decoration: underline; } /* 标记,类似于手写的荧光笔的作用 */ mark { background: #fffdd1; border-bottom: 1px solid #ffedce; padding: 2px; margin: 0 5px; } /* 代码片断 */ pre, code, pre tt { font-family: Courier, 'Courier New', monospace; } pre { background: #f8f8f8; border: 1px solid #ddd; padding: 1em 1.5em; display: block; -webkit-overflow-scrolling: touch; } /* 一致化 horizontal rule */ hr { border: none; border-bottom: 1px solid #cfcfcf; margin-bottom: 0.8em; height: 10px; } /* 底部印刷体、版本等标记 */ small, .typo-small, /* 图片说明 */ figcaption { font-size: 0.9em; color: #888; } strong, b { font-weight: bold; color: #000; } /* 可拖动文件添加拖动手势 */ [draggable] { cursor: move; } .clearfix:before, .clearfix:after { content: ""; display: table; } .clearfix:after { clear: both; } .clearfix { zoom: 1; } /* 强制文本换行 */ .textwrap, .textwrap td, .textwrap th { word-wrap: break-word; word-break: break-all; } .textwrap-table { table-layout: fixed; } /* 提供 serif 版本的字体设置: iOS 下中文自动 fallback 到 sans-serif */ .serif { font-family: Palatino, Optima, Georgia, serif; } /* 保证块/段落之间的空白隔行 */ .typo p, .typo pre, .typo ul, .typo ol, .typo dl, .typo form, .typo hr, .typo table, .typo-p, .typo-pre, .typo-ul, .typo-ol, .typo-dl, .typo-form, .typo-hr, .typo-table, blockquote { margin-bottom: 1.2em } h1, h2, h3, h4, h5, h6 { font-family: PingFang SC, Verdana, Helvetica Neue, Microsoft Yahei, Hiragino Sans GB, Microsoft Sans Serif, WenQuanYi Micro Hei, sans-serif; font-weight: 100; color: #000; line-height: 1.35; } /* 标题应该更贴紧内容,并与其他块区分,margin 值要相应做优化 */ .typo h1, .typo h2, .typo h3, .typo h4, .typo h5, .typo h6, .typo-h1, .typo-h2, .typo-h3, .typo-h4, .typo-h5, .typo-h6 { margin-top: 1.2em; margin-bottom: 0.6em; line-height: 1.35; } .typo h1, .typo-h1 { font-size: 2em; } .typo h2, .typo-h2 { font-size: 1.8em; } .typo h3, .typo-h3 { font-size: 1.6em; } .typo h4, .typo-h4 { font-size: 1.4em; } .typo h5, .typo h6, .typo-h5, .typo-h6 { font-size: 1.2em; } /* 在文章中,应该还原 ul 和 ol 的样式 */ .typo ul, .typo-ul { margin-left: 1.3em; list-style: disc; } .typo ol, .typo-ol { list-style: decimal; margin-left: 1.9em; } .typo li ul, .typo li ol, .typo-ul ul, .typo-ul ol, .typo-ol ul, .typo-ol ol { margin-bottom: 0.8em; margin-left: 2em; } .typo li ul, .typo-ul ul, .typo-ol ul { list-style: circle; } /* 同 ul/ol,在文章中应用 table 基本格式 */ .typo table th, .typo table td, .typo-table th, .typo-table td, .typo table caption { border: 1px solid #ddd; padding: 0.5em 1em; color: #666; } .typo table th, .typo-table th { background: #fbfbfb; } .typo table thead th, .typo-table thead th { background: #f1f1f1; } .typo table caption { border-bottom: none; } /* 去除 webkit 中 input 和 textarea 的默认样式 */ .typo-input, .typo-textarea { -webkit-appearance: none; border-radius: 0; } .typo-em, .typo em, legend, caption { color: #000; font-weight: inherit; } /* 着重号,只能在少量(少于100个字符)且全是全角字符的情况下使用 */ .typo-em { position: relative; } .typo-em:after { position: absolute; top: 0.65em; left: 0; width: 100%; overflow: hidden; white-space: nowrap; content: "・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・"; } /* Responsive images */ .typo img { max-width: 100%; } header { position: fixed; z-index: 2; z-index: 1024; top: 0; left: 0; width: 100%; height: 60px; background-color: #fff; box-shadow: 0 0 4px rgba(0,0,0,0.5); text-transform: uppercase; font-size: 20px } header .logo { display: inline-block; padding-left: 37px; float: left; text-decoration: none; color: #333; line-height: 60px; background-repeat: no-repeat; background-position: left center } header nav { text-align: right; font-size: 0 } header nav ul { display: inline-block; padding: 0; list-style: none } header nav li { display: inline } header nav a { display: inline-block; padding: 0 15px; color: #333; text-decoration: none; font-size: 20px; line-height: 60px; transition: opacity .2s } header nav a.current { color: #9600ff } header nav a:hover { opacity: .75 } .content { padding-top: 100px; } #toc { width: 30%; max-width: 420px; max-height: 85%; float: left; margin: 25px 0px 20px 0px; position: fixed !important; overflow: auto; -webkit-overflow-scrolling: touch; overflow-scrolling: touch; box-sizing: border-box; z-index: 1; left: 0; top: 40px; bottom: 0; padding: 20px; } #toc > ul { list-style: none; padding: 20px 40px 0 40px; margin: 0; border-bottom: 1px solid #eee } #toc > ul > li > ul { padding-left: 40px; } #toc a { display: block; padding: 10px 0; text-decoration: none; color: #333; border-bottom: 1px solid #eee; transition: opacity .2s } #toc a.current { color: #9600ff } #toc a:hover { opacity: .75 } .main { width: 70%; max-width: 980px; float: left; padding-left: 30%; top: 160px; position: relative; } </style> </head> <body> <header> <div class="container"> <a href="https://github.com/phodal/adr" class="logo">ADR</a> <nav> <ul> <li><a href="https://github.com/phodal/adr">GitHub</a></li> </ul> </nav> </div> </header> <div class="content"> <div id="toc" class="tocify"> <ul> <li><a href="#architecture-decision-record-use-adrs">Architecture Decision Record: Use ADRs</a> <ul> <li><a href="#context">Context</a></li> <li><a href="#decision">Decision</a></li> <li><a href="#status">Status</a></li> <li><a href="#consequences">Consequences</a></li> </ul></li> <li><a href="#architecture-decision-record-configuration">Architecture Decision Record: Configuration</a> <ul> <li><a href="#context-1">Context</a></li> <li><a href="#decision-1">Decision</a></li> <li><a href="#status-1">Status</a></li> <li><a href="#consequences-1">Consequences</a></li> </ul></li> <li><a href="#architecture-decision-record-datomic-based-configuration">Architecture Decision Record: Datomic-based Configuration</a> <ul> <li><a href="#context-2">Context</a> <ul> <li><a href="#config-as-database">Config as Database</a></li> <li><a href="#configuration-as-ontology">Configuration as Ontology</a></li> <li><a href="#implementation-options">Implementation Options</a></li> <li><a href="#rdf">RDF</a> <ul> <li><a href="#benefits-for-arachne">Benefits for Arachne</a></li> <li><a href="#tradeoffs-for-arachne-with-mitigations">Tradeoffs for Arachne (with mitigations)</a></li> </ul></li> <li><a href="#datomic">Datomic</a> <ul> <li><a href="#benefits-for-arachne-1">Benefits for Arachne</a></li> <li><a href="#tradeoffs-for-arachne-with-mitigations-1">Tradeoffs for Arachne (with mitigations)</a></li> </ul></li> </ul></li> <li><a href="#decision-2">Decision</a></li> <li><a href="#status-2">Status</a></li> <li><a href="#consequences-2">Consequences</a></li> </ul></li> <li><a href="#architecture-decision-record-module-structure--loading">Architecture Decision Record: Module Structure &amp; Loading</a> <ul> <li><a href="#context-3">Context</a></li> <li><a href="#decision-3">Decision</a></li> <li><a href="#status-3">Status</a></li> <li><a href="#consequences-3">Consequences</a></li> </ul></li> <li><a href="#architecture-decision-record-user-facing-configuration">Architecture Decision Record: User Facing Configuration</a> <ul> <li><a href="#context-4">Context</a> <ul> <li><a href="#option-raw-datomic-txdata">Option: Raw Datomic Txdata</a></li> <li><a href="#option-custom-edn-data-formats">Option: Custom EDN data formats</a></li> <li><a href="#option-code-based-configuration">Option: Code-based configuration</a></li> </ul></li> <li><a href="#decision-4">Decision</a></li> <li><a href="#status-4">Status</a></li> <li><a href="#consequences-4">Consequences</a></li> </ul></li> <li><a href="#architecture-decision-record-core-runtime">Architecture Decision Record: Core Runtime</a> <ul> <li><a href="#context-5">Context</a></li> <li><a href="#decision-5">Decision</a> <ul> <li><a href="#components">Components</a></li> <li><a href="#arachne-runtime">Arachne Runtime</a></li> <li><a href="#startup-procedure">Startup Procedure</a></li> </ul></li> <li><a href="#status-5">Status</a></li> <li><a href="#consequences-5">Consequences</a></li> </ul></li> <li><a href="#architecture-decision-record-configuration-updates">Architecture Decision Record: Configuration Updates</a> <ul> <li><a href="#context-6">Context</a> <ul> <li><a href="#prior-art">Prior Art</a></li> </ul></li> <li><a href="#decision-6">Decision</a></li> <li><a href="#status-6">Status</a></li> <li><a href="#consequences-6">Consequences</a></li> </ul></li> <li><a href="#architecture-decision-record-abstract-modules">Architecture Decision Record: Abstract Modules</a> <ul> <li><a href="#context-7">Context</a> <ul> <li><a href="#what-does-it-mean-to-use-a-module">What does it mean to use a module?</a></li> </ul></li> <li><a href="#decision-7">Decision</a> <ul> <li><a href="#concrete-example">Concrete Example</a></li> </ul></li> <li><a href="#status-7">Status</a></li> <li><a href="#consequences-7">Consequences</a></li> </ul></li> <li><a href="#architecture-decision-record-configuration-ontology">Architecture Decision Record: Configuration Ontology</a> <ul> <li><a href="#context-8">Context</a></li> <li><a href="#decision-8">Decision</a></li> <li><a href="#status-8">Status</a></li> <li><a href="#consequences-8">Consequences</a></li> </ul></li> <li><a href="#architecture-decision-record-persistent-configuration">Architecture Decision Record: Persistent Configuration</a> <ul> <li><a href="#context-9">Context</a> <ul> <li><a href="#goals">Goals</a></li> </ul></li> <li><a href="#decision-9">Decision</a></li> <li><a href="#status-9">Status</a></li> <li><a href="#consequences-9">Consequences</a></li> </ul></li> <li><a href="#architecture-decision-record-asset-pipeline">Architecture Decision Record: Asset Pipeline</a> <ul> <li><a href="#context-10">Context</a> <ul> <li><a href="#development-vs-production">Development vs Production</a></li> <li><a href="#deployment--distribution">Deployment &amp; Distribution</a></li> <li><a href="#entirely-static-sites">Entirely Static Sites</a></li> </ul></li> <li><a href="#decision-10">Decision</a></li> <li><a href="#status-10">Status</a></li> <li><a href="#consequences-10">Consequences</a></li> </ul></li> <li><a href="#architecture-decision-record-enhanced-validation">Architecture Decision Record: Enhanced Validation</a> <ul> <li><a href="#context-11">Context</a></li> <li><a href="#decision-11">Decision</a> <ul> <li><a href="#configuration-validation">Configuration Validation</a></li> <li><a href="#runtime-validation">Runtime Validation</a></li> </ul></li> <li><a href="#status-11">Status</a></li> <li><a href="#consequences-11">Consequences</a></li> </ul></li> <li><a href="#architecture-decision-record-error-reporting">Architecture Decision Record: Error Reporting</a> <ul> <li><a href="#context-12">Context</a></li> <li><a href="#decision-12">Decision</a> <ul> <li><a href="#creating-errors">Creating Errors</a></li> <li><a href="#displaying-errors">Displaying Errors</a></li> </ul></li> <li><a href="#status-12">Status</a></li> <li><a href="#consequences-12">Consequences</a></li> </ul></li> <li><a href="#architecture-decision-record-project-templates">Architecture Decision Record: Project Templates</a> <ul> <li><a href="#context-13">Context</a> <ul> <li><a href="#lein-templates">Lein templates</a></li> <li><a href="#rails-templates">Rails templates</a></li> </ul></li> <li><a href="#decision-13">Decision</a> <ul> <li><a href="#maven-distribution">Maven Distribution</a></li> </ul></li> <li><a href="#status-13">Status</a></li> <li><a href="#consequences-13">Consequences</a> <ul> <li><a href="#contrast-with-rails">Contrast with Rails</a></li> </ul></li> </ul></li> <li><a href="#architecture-decision-record-data-abstraction-model">Architecture Decision Record: Data Abstraction Model</a> <ul> <li><a href="#context-14">Context</a> <ul> <li><a href="#other-use-cases">Other use cases</a></li> <li><a href="#modeling--manipulation">Modeling &amp; Manipulation</a></li> <li><a href="#existing-solutions-orms">Existing solutions: ORMs</a></li> <li><a href="#database-migrations">Database &quot;migrations&quot;</a></li> </ul></li> <li><a href="#decision-14">Decision</a> <ul> <li><a href="#adapters">Adapters</a></li> </ul> <ul> <li><a href="#limitations-and-drawbacks">Limitations and Drawbacks</a></li> <li><a href="#modeling">Modeling</a> <ul> <li><a href="#modeling-entity-types">Modeling: Entity Types</a></li> <li><a href="#attribute-definitions">Attribute Definitions</a> <ul> <li><a href="#value-types">Value Types</a></li> </ul></li> <li><a href="#validation">Validation</a></li> <li><a href="#schema--migration-operations">Schema &amp; Migration Operations</a></li> </ul></li> <li><a href="#entity-manipulation">Entity Manipulation</a> <ul> <li><a href="#data-representation">Data Representation</a></li> <li><a href="#persistence-operations">Persistence Operations</a></li> <li><a href="#capability-model">Capability Model</a></li> </ul></li> </ul></li> <li><a href="#status-14">Status</a></li> <li><a href="#consequences-14">Consequences</a></li> </ul></li> <li><a href="#architecture-decision-record-database-migrations">Architecture Decision Record: Database Migrations</a> <ul> <li><a href="#context-15">Context</a> <ul> <li><a href="#prior-art-1">Prior Art</a></li> <li><a href="#scenarios">Scenarios</a></li> </ul></li> <li><a href="#decision-15">Decision</a> <ul> <li><a href="#migration-types">Migration Types</a></li> <li><a href="#structure--usage">Structure &amp; Usage</a> <ul> <li><a href="#parallel-migrations">Parallel Migrations</a></li> </ul></li> <li><a href="#chimera-migrations--entity-types">Chimera Migrations &amp; Entity Types</a></li> <li><a href="#applying-migrations">Applying Migrations</a></li> <li><a href="#databases-without-migrations">Databases without migrations</a></li> <li><a href="#migration-rollback">Migration Rollback</a></li> </ul></li> <li><a href="#status-15">Status</a></li> <li><a href="#consequences-15">Consequences</a></li> </ul></li> <li><a href="#architecture-decision-record-simplification-of-chimera-model">Architecture Decision Record: Simplification of Chimera Model</a> <ul> <li><a href="#context-16">Context</a></li> <li><a href="#decision-16">Decision</a></li> <li><a href="#status-16">Status</a></li> <li><a href="#consequences-16">Consequences</a></li> </ul></li> </ul> </div> <div class="main typo"> <h1 id=architecture-decision-record-use-adrs>Architecture Decision Record: Use ADRs</h1> <h2 id=context-nan>Context</h2> <p>Arachne has several very explicit goals that make the practice and discipline of architecture very important:</p> <ul> <li>We want to think deeply about all our architectural decisions, exploring all alternatives and making a careful, considered, well-researched choice.</li> <li>We want to be as transparent as possible in our decision-making process.</li> <li>We don't want decisions to be made unilaterally in a vacuum. Specifically, we want to give our steering group the opportunity to review every major decision.</li> <li>Despite being a geographically and temporally distributed team, we want our contributors to have a strong shared understanding of the technical rationale behind decisions.</li> <li>We want to be able to revisit prior decisions to determine fairly if they still make sense, and if the motivating circumstances or conditions have changed.</li> </ul> <h2 id=decision-nan>Decision</h2> <p>We will document every architecture-level decision for Arachne and its core modules with an <a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">Architecture Decision Record</a>. These are a well structured, relatively lightweight way to capture architectural proposals. They can serve as an artifact for discussion, and remain as an enduring record of the context and motivation of past decisions.</p> <p>The workflow will be:</p> <ol> <li>A developer creates an ADR document outlining an approach for a particular question or problem. The ADR has an initial status of &quot;proposed.&quot;</li> <li>The developers and steering group discuss the ADR. During this period, the ADR should be updated to reflect additional context, concerns raised, and proposed changes.</li> <li>Once consensus is reached, ADR can be transitioned to either an &quot;accepted&quot; or &quot;rejected&quot; state.</li> <li>Only after an ADR is accepted should implementing code be committed to the master branch of the relevant project/module.</li> <li>If a decision is revisited and a different conclusion is reached, a new ADR should be created documenting the context and rationale for the change. The new ADR should reference the old one, and once the new one is accepted, the old one should (in its &quot;status&quot; section) be updated to point to the new one. The old ADR should not be removed or otherwise modified except for the annotation pointing to the new ADR.</li> </ol> <h2 id=status-nan>Status</h2> <p>Accepted</p> <h2 id=consequences-nan>Consequences</h2> <ol> <li>Developers must write an ADR and submit it for review before selecting an approach to any architectural decision -- that is, any decision that affects the way Arachne or an Arachne application is put together at a high level.</li> <li>We will have a concrete artifact around which to focus discussion, before finalizing decisions.</li> <li>If we follow the process, decisions will be made deliberately, as a group.</li> <li>The master branch of our repositories will reflect the high-level consensus of the steering group.</li> <li>We will have a useful persistent record of why the system is the way it is.</li> </ol> <h1 id=architecture-decision-record-configuration>Architecture Decision Record: Configuration</h1> <h2 id=context-nan>Context</h2> <p>Arachne has a number of goals.</p> <ol> <li><p>It needs to be <em>modular</em>. Different software packages, written by different developers, should be usable and swappable in the same application with a minimum of effort.</p></li> <li><p>Arachne applications need to be <em>transparent</em> and <em>introspectable</em>. It should always be as clear as possible what is going on at any given moment, and why the application is behaving in the way it does.</p></li> <li><p>As a general-purpose web framework, it needs to provide a strong set of default settings which are also highly overridable, and <em>configurable</em> to suit the unique needs of users.</p></li> </ol> <p>Also, it is a good development practice (particularly in Clojure) to code to a specific information model (that is, data) rather than to particular functions or APIs. Along with other benefits, this helps separate (avoids &quot;complecting&quot;) the intended operation and its implementation.</p> <p>Documenting the full rationale for this &quot;data first&quot; philosophy is beyond the scope of this document, but some resources that explain it (among other things) are:</p> <ul> <li><a href="http://www.infoq.com/presentations/Simple-Made-Easy">Simple Made Easy</a> - <NAME></li> <li><a href="https://vimeo.com/77199361">Narcissistic Design</a> - <NAME></li> <li><a href="https://malcolmsparks.com/posts/data-beats-functions.html">Data Beats Functions</a> - Malcolm Sparks</li> <li><a href="https://www.youtube.com/watch?v=3oQTSP4FngY">Always Be Composing</a> - <NAME></li> <li><a href="http://www.lispcast.com/data-functions-macros-why">Data &gt; Functions &gt; Macros</a> - Eric Normand</li> </ul> <p>Finally, one weakness of many existing Clojure libraries, especially web development libraries, is the way in which they overload the Clojure runtime (particularly vars and reified namespaces) to store information about the webapp. Because both the Clojure runtime and many web application entities (e.g servers) are stateful, this causes a variety of issues, particularly with reloading namespaces. Therefore, as much as possible, we would like to avoid entangling information about an Arachne application with the Clojure runtime itself.</p> <h2 id=decision-nan>Decision</h2> <p>Arachne will take the &quot;everything is data&quot; philosophy to its logical extreme, and encode as much information about the application as possible in a single, highly general data structure. This will include not just data that is normally thought of as &quot;config&quot; data, but the structure and definition of the application itself. Everything that does not have to be arbitrary executable code will be reflected in the application config value.</p> <p>Some concrete examples include (but are not limited to):</p> <ul> <li>Dependency injection components</li> <li>Runtime entities (servers, caches, connections, pools, etc)</li> <li>HTTP routes and middleware</li> <li>Persistence schemas and migrations</li> <li>Locations of static and dynamic assets</li> </ul> <p>This configuration value will have a <em>schema</em> that defines what types of entities can exist in the configuration, and what their expected properties are.</p> <p>Each distinct module will have the ability to contribute to the schema and define entity types specific to its own domain. Modules may interact by referencing entity types and properties defined in other modules.</p> <p>Although it has much in common with a fully general in-memory database, the configuration value will be a single immutable value, not a stateful data store. This will avoid many of the complexities of state and change, and will eliminate the temptation to use the configuration itself as dynamic storage for runtime data.</p> <h2 id=status-nan>Status</h2> <p>Proposed</p> <h2 id=consequences-nan>Consequences</h2> <ul> <li>Applications will be defined comprehensively and declaratively by a rich data structure, before the application even starts.</li> <li>The config schema provides an explicit, reliable contract and set of extension points, which can be used by other modules to modify entities or behaviors.</li> <li>It will be easy to understand and inspect an application by inspecting or querying its configuration. It will be possible to write tools to make exploring and visualizing applications even easier.</li> <li>Developers will need to carefully decide what types of things are appropriate to encode statically in the configuration, and what must be dynamic at runtime.</li> </ul> <h1 id=architecture-decision-record-datomic-based-configuration>Architecture Decision Record: Datomic-based Configuration</h1> <h2 id=context-nan>Context</h2> <p><a href="adr-002-configuration.md">ADR-002</a> indicates that we will store the entire application config in a single rich data structure with a schema.</p> <h3 id=config-as-database-nan>Config as Database</h3> <p>This implies that it should be possible to easily search, query and update the configuration value. It also implies that the configuration value is general enough to store arbitrary data; we don't know what kinds of things users or module authors will need to include.</p> <p>If what we need is a system that allows you to define, query, and update arbitrary data with a schema, then we are looking for a database.</p> <p>Required data store characteristics:</p> <ol> <li>It must be available under a permissive open source license. Anything else will impose unwanted restrictions on who can use Arachne.</li> <li>It can operate embedded in a JVM process. We do not want to force users to install anything else or run multiple processes just to get Arachne to work.</li> <li>The database must be serializable. It must be possible to write the entire configuration to disk, and then reconstitute it in the same exact state in a separate process.</li> <li>Because modules build up the schema progressively, the schema must be inherently extensible. It should be possible for modules to progressively add both new entity types and new attributes to existing entity types.</li> <li>It should be usable from Clojure without a painful impedance mismatch.</li> </ol> <h3 id=configuration-as-ontology-nan>Configuration as Ontology</h3> <p>As an extension of the rationale discussed in <a href="adr-002-configuration.md">ADR-002</a>, it is useful to enumerate the possible use cases of the configuration and configuration schema together.</p> <ul> <li>The configuration is read by the application during bootstrap and controls the behavior of the application.</li> <li>The configuration schema defines what types of values the application can or will read to modify its structure and behavior at boot time and run time.</li> <li>The configuration is how an application author communicates their intent about how their application should fit together and run, at a higher, more conceptual level than code.</li> <li>The configuration schema is how module authors communicate to application authors what settings, entities and structures are available for them to use in their applications.</li> <li>The configuration schema is how module authors communicate to other potential module authors what their extension points are; module extenders can safely read or write any entities/attributes declared by the modules upon which they depend.</li> <li>The configuration schema can be used to validate a particular configuration, and explain where and how it deviates from what is actually supported.</li> <li>The configuration can be exposed (via user interfaces of various types) to end users for analytics and debugging, explaining the structure of their application and why things are the way they are.</li> <li>A serialization of the configuration, together with a particular codebase (identified by a git SHA) form a precise, complete, 100% reproducible definition of the behavior of an application.</li> </ul> <p>To the extent that the configuration schema expresses and communicates the &quot;categories of being&quot; or &quot;possibility space&quot; of an application, it is a formal <a href="https://en.wikipedia.org/wiki/Ontology">Ontology</a>. This is a desirable characteristic, and to the degree that it is practical to do so, it will be useful to learn from or re-use existing work around formal ontological systems.</p> <h3 id=implementation-options-nan>Implementation Options</h3> <p>There are instances of four broad categories of data stores that match the first three of the data store characteristics defined above.</p> <ul> <li>Relational (Derby, HSQLDB, etc)</li> <li>Key/value (BerkelyDB, hashtables, etc)</li> <li>RDF/RDFs/OWL stores (Jena)</li> <li>Datomic-style (Datascript)</li> </ul> <p>We can eliminate relational solutions fairly quickly; SQL schemas are not generally extensible or flexible, failing condition #4. In addition, they do not fare well on #5 -- using SQL for queries and updates is not particularly fluent in Clojure.</p> <p>Similarly, we can eliminate key/value style data stores. In general, these do not have schemas at all (or at least, not the type of rich schema that provides a meaningful data contract or ontology, which is the point for Arachne.)</p> <p>This leaves solutions based on the RDF stack, and Datomic-style data stores. Both are viable options which would provide unique benefits for Arachne, and both have different drawbacks.</p> <p>Explaining the core technical characteristics of RDF/OWL and Datomic is beyond the scope of this document; please see the <a href="https://jena.apache.org/documentation/index.html">Jena</a> and <a href="http://docs.datomic.com">Datomic</a> documentation for more details. More information on RDF, OWL and the Semantic web in general:</p> <ul> <li><a href="https://en.wikipedia.org/wiki/Resource_Description_Framework">Wikipedia article on RDF</a></li> <li><a href="https://en.wikipedia.org/wiki/Web_Ontology_Language">Wikipedia article on OWL</a></li> <li><a href="http://www.w3.org/TR/owl-semantics/">OWL Semantics</a> standards document.</li> </ul> <h3 id=rdf-nan>RDF</h3> <p>The clear choice for a JVM-based, permissively licensed, standards-compliant RDF API is Apache Jena.</p> <h4 id=benefits-for-arachne-nan>Benefits for Arachne</h4> <ul> <li>OWL is a good fit insofar as Arachne's goal is to define an ontology of applications. The point of the configuration schema is first and foremost to serve as unambiguous communication regarding the types of entities that can exist in an application, and what the possible relationships between them are. By definition, this is defining an ontology, and is the exact use case which OWL is designed to address.</li> <li>Information model is a good fit for Clojure: tuples and declarative logic.</li> <li>Open and extensible by design.</li> <li>Well researched by very smart people, likely to avoid common mistakes that would result from building an ontology-like system ourselves.</li> <li>Existing technology, well known beyond the Clojure ecosystem. Existing tools could work with Arachne project configurations out of the box.</li> <li>The open-world assumption is a good fit for Arachne's per-module schema modeling, since modules cannot know what other modules might be present in the application.</li> <li>We're likely to want to introduce RDFs/OWL to the application anyway, at some point, as an abstract entity meta-schema (note: this has not been firmly decided yet.)</li> </ul> <h4 id=tradeoffs-for-arachne-with-mitigations-nan>Tradeoffs for Arachne (with mitigations)</h4> <ul> <li>OWL is complex. Learning to use it effectively is a skill in its own right and it might be asking a lot to require of module authors.</li> <li>OWLs representation of some common concepts can be verbose and/or convoluted in ways that would make schema more difficult to read/write. (e.g, Restriction classes)</li> <li>OWL is not a schema. Although the open world assumption is valid and good when writing ontologies, it means that OWL inferencing is incapable of performing many of the kind of validations we would want to apply once we do have a complete configuration and want to check it for correctness. For example, open-world reasoning can never validate a <code>owl:minCardinality</code> rule. <ul> <li>Mitigation: Although OWL inferencing cannot provide closed-world validation of a given RDF dataset, such tools do exist. Some mechanisms for validating a particular closed set of RDF triples include: <ol> <li>Writing SPARQL queries that catch various types of validation errors.</li> <li>Deriving validation errors using Jena's rules engine.</li> <li>Using an existing RDF validator such as <a href="https://jena.apache.org/documentation/tools/eyeball-getting-started.html">Eyeball</a> (although, unfortunately, Eyeball does not seem to be well maintained.)</li> </ol></li> <li>For Clojure, it would be possible to validate a given OWL class by generating a specification using <code>clojure.spec</code> that could be applied to concrete instances of the class in their map form.</li> </ul></li> <li>Jena's API is aggressively object oriented and at odds with Clojure idioms. <ul> <li>Mitigation: Write a data-oriented wrapper (note: I have a working proof of concept already.)</li> </ul></li> <li>SPARQL is a string-based query language, as opposed to a composable data API. <ul> <li>Mitigation: It is possible to hook into Jena's ARQ query engine at the object layer, and expose a data-oriented API from there, with SPARQL semantics but an API similar to Datomic datalog.</li> </ul></li> <li>OWL inferencing is known to have performance issues with complex inferences. While Arachne configurations are tiny (as knowledge bases go), and we are unlikely to use the more esoteric derivations, it is unknown whether this will cause problems with the kinds of ontologies we do need. <ul> <li>Mitigation: We could restrict ourselves to the OWL DL or even OWL Lite sub-languages, which have more tractable inferencing rules.</li> </ul></li> <li>Jena's APIs are such that it is impossible to write an immutable version of a RDF model (at least without breaking most of Jena's API.) It's trivial to write a data-oriented wrapper, but intractable to write a persistent immutable one.</li> </ul> <h3 id=datomic-nan>Datomic</h3> <p>Note that Datomic itself does not satisfy the first requirement; it is closed-source, proprietary software. There <em>is</em> an open source project, Datascript, which emulates Datomic's APIs (without any of the storage elements). Either one would work for Arachne, since Arachne only needs the subset of features they both support. In, fact, if Arachne goes the Datomic-inspired route, we would probably want to support <em>both</em>: Datomic, for those who have an existing investment there, and Datascript for those who desire open source all the way.</p> <h4 id=benefits-for-arachne-nan>Benefits for Arachne</h4> <ul> <li>Well known to most Clojurists</li> <li>Highly idiomatic to use from Clojure</li> <li>There is no question that it would be performant and technically suitable for Arachne-sized data.</li> <li>Datomic's schema is a real validating schema; data transacted to Datomic must always be valid.</li> <li>Datomic Schema is open and extensible.</li> </ul> <h4 id=tradeoffs-for-arachne-with-mitigations-nan>Tradeoffs for Arachne (with mitigations)</h4> <ul> <li>The expressivity of Datomic's schema is anemic compared to RDFs/OWL; for example, it has no built-in notion of types. It is focused towards data storage and integrity rather than defining a public ontology, which would be useful for Arachne. <ul> <li>Mitigation: If we did want something more ontologically focused, it is possible to build an ontology system on top of Datomic using meta-attributes and Datalog rules. Examples of such systems already exist.</li> </ul></li> <li>If we did build our own ontology system on top of Datomic (or use an existing one) we would still be responsible for &quot;getting it right&quot;, ensuring that it meets any potential use case for Arachne while maintaining internal and logical consistency. <ul> <li>Mitigation: we could still use the work that has been done in the OWL world and re-implement a subset of axioms and derivations on top of Datomic.</li> </ul></li> <li>Any ontological system built on top of Datomic would be novel to module authors, and therefore would require careful, extensive documentation regarding its capabilities and usage.</li> <li>To satisfy users of Datomic as well as those who have a requirement for open source, it will be necessary to abstract across both Datomic and Datascript. <ul> <li>Mitigation: This work is already done (provided users stay within the subset of features that is supported by both products.)</li> </ul></li> </ul> <h2 id=decision-nan>Decision</h2> <p>The steering group decided the RDF/OWL approach is too high-risk to wrap in Clojure and implement at this time, while the rewards are mostly intangible &quot;openness&quot; and &quot;interoperability&quot; rather than something that will help move Arachne forward in the short term.</p> <p>Therefore, we will use a Datomic style schema for Arachne's configuration.</p> <p>Users may use either Datomic Pro, Datomic Free or Datascript at runtime in their applications. We will provide a &quot;multiplexer&quot; configuration implementation that utilizes both, and asserts that the results are equal: this can be used by module authors to ensure they stay within the subset of features supported by both platforms.</p> <p>Before Arachne leaves &quot;alpha&quot; status (that is, before it is declared ready for experimental production use or for the release of third-party modules), we will revisit the question of whether OWL would be more appropriate, and whether we have encountered issues that OWL would have made easier. If so, and if time allows, we reserve the option to either refactor the configuration layer to use Jena as a primary store (porting existing modules), or provide an OWL view/rendering of an ontology stored in Datomic.</p> <h2 id=status-nan>Status</h2> <p>Proposed</p> <h2 id=consequences-nan>Consequences</h2> <ul> <li>It will be possible to write schemas that precisely define the configuration data that modules consume.</li> <li>The configuration system will be open and extensible to additional modules by adding additional attributes and meta-attributes.</li> <li>The system will not provide an ontologically oriented view of the system's data without additional work.</li> <li>Additional work will be required to validate configuration with respect to requirements that Datomic does not support natively (e.g, required attributes.)</li> <li>Every Arachne application must include either Datomic Free, Datomic Pro or Datascript as a dependency.</li> <li>We will need to keep our eyes open to look for situations where a more formal ontology system might be a better choice.</li> </ul> <h1 id=architecture-decision-record-module-structure--loading>Architecture Decision Record: Module Structure &amp; Loading</h1> <h2 id=context-nan>Context</h2> <p>Arachne needs to be as modular as possible. Not only do we want the community to be able to contribute new abilities and features that integrate well with the core and with eachother, we want some of the basic functionality of Arachne to be swappable for alternatives as well.</p> <p><a href="adr-002-configuration.md">ADR-002</a> specifies that one role of modules is to contribute schema to the application config. Other roles of modules would include providing code (as any library does), and querying and updating the config during the startup process. Additionally, since modules can depend upon each other, they must specify which modules they depend upon.</p> <p>Ideally there will be as little overhead as possible for creating and consuming modules.</p> <p>Some of the general problems associated with plugin/module systems include:</p> <ul> <li>Finding and downloading the implementation of the module.</li> <li>Discovering and activating the correct set of installed modules.</li> <li>Managing module versions and dependencies.</li> </ul> <p>There are some existing systems for modularity in the Java ecosystem. The most notable is OSGi, which provides not only a module system addressing the concerns above, but also service runtime with classpath isolation, dynamic loading and unloading and lazy activation.</p> <p>OSGi (and other systems of comparable scope) are overkill for Arachne. Although they come with benefits, they are very heavyweight and carry a high complexity burden, not just for Arachne development but also for end users. Specifically, Arachne applications will be drastically simpler if (at runtime) they exist as a straightforward codebase in a single classloader space. Features like lazy loading and dynamic start-stop are likewise out of scope; the goal is for an Arachne runtime itself to be lightweight enough that starting and stopping when modules change is not an issue.</p> <h2 id=decision-nan>Decision</h2> <p>Arachne will not be responsible for packaging, distribution or downloading of modules. These jobs will be delegated to an external dependency management &amp; packaging tool. Initially, that tool will be Maven/Leiningen/Boot, or some other tool that works with Maven artifact repositories, since that is currently the standard for JVM projects.</p> <p>Modules that have a dependency on another module must specify a dependency using Maven (or other dependency management tool.)</p> <p>Arachne will provide no versioning system beyond what the packaging tool provides.</p> <p>Each module JAR will contain a special <code>arachne-modules.edn</code> file at the root of its classpath. This data file (when read) contains a sequence of <em>module definition maps</em>.</p> <p>Each module definition map contains the following information:</p> <ul> <li>The formal name of the module (as a namespaced symbol.)</li> <li>A list of dependencies of the module (as a set of namespaced symbols.) Module dependencies must form a directed acyclic graph; circular dependencies are not allowed.</li> <li>A namespace qualified symbol that resolves to the module's <em>schema function.</em> A schema function is a function with no arguments that returns transactable data containing the schema of the module.</li> <li>A namespace qualified symbol that resolves to the module's <em>configure function</em>. A configure function is a function that takes a configuration value and returns an updated configuration.</li> </ul> <p>When an application is defined, the user must specify a set of module names to use (exact mechanism TBD.) Only the specified modules (and their dependencies) will be considered by Arachne. In other words, merely including a module as a dependency in the package manager is not sufficient to activate it and cause it to be used in an application.</p> <h2 id=status-nan>Status</h2> <p>Proposed</p> <h2 id=consequences-nan>Consequences</h2> <ul> <li>Creating a basic module is lightweight, requiring only: <ul> <li>writing a short EDN file</li> <li>writing a function that returns schema</li> <li>writing a function that queries and/or updates a configuration</li> </ul></li> <li>From a user's point of view, consuming modules will use the same familiar mechanisms as consuming a library.</li> <li>Arachne is not responsible for getting code on the classpath; that is a separate concern.</li> <li>We will need to think of a straightforward, simple way for application authors to specify the modules they want to be active.</li> <li>Arachne is not responsible for any complexities of publishing, downloading or versioning modules</li> <li>Module versioning has all of the drawbacks of the package manager's (usually Maven), including the pain of resolving conflicting versions. This situation with respect to dependency version management will be effectively the same as it is now with Clojure libraries.</li> <li>A single dependency management artifact can contain several Arachne modules (whether this is ever desirable is another question.)</li> <li>Although Maven is currently the default dependency/packaging tool for the Clojure ecosystem, Arachne is not specified to use only Maven. If an alternative system gains traction, it will be possible to package and publish Arachne modules using that.</li> </ul> <h1 id=architecture-decision-record-user-facing-configuration>Architecture Decision Record: User Facing Configuration</h1> <h2 id=context-nan>Context</h2> <p>Per <a href="adr-003-config-implementation.md">ADR-003</a>, Arachne uses Datomic-shaped data for configuration. Although this is a flexible, extensible data structure which is a great fit for programmatic manipulation, in its literal form it is quite verbose.</p> <p>It is quite difficult to understand the structure of Datomic data by reading its native textual representation, and it is similarly hard to write, containing enough repeated elements that copying and pasting quickly becomes the default.</p> <p>One of Arachne's core values is ease of use and a fluent experience for developers. Since much of a developer's interaction with Arachne will be writing to the config, it is of paramount importance that there be some easy way to create configuration data.</p> <p>The question is, what is the best way for developers of Arachne applications to interact with their application's configuration?</p> <h4 id=option-raw-datomic-txdata-nan>Option: Raw Datomic Txdata</h4> <p>This would require end users to write Datomic transaction data by hand in order to configure their application.</p> <p>This is the &quot;simplest&quot; option, and has the fewest moving parts. However, as mentioned above, it is very far from ideal for human interactions.</p> <h4 id=option-custom-edn-data-formats-nan>Option: Custom EDN data formats</h4> <p>In this scenario, users would write EDN data in some some nested structure of maps, sets, seqs and primitives. This is currently the most common way to configure Clojure applications.</p> <p>Each module would then need to provide a mapping from the EDN config format to the underlying Datomic-style config data.</p> <p>Because Arachne's configuration is so much broader, and defines so much more of an application than a typical application config file, it is questionable if standard nested EDN data would be a good fit for representing it.</p> <h4 id=option-code-based-configuration-nan>Option: Code-based configuration</h4> <p>Another option would be to go in the direction of some other frameworks, such as Ruby on Rails, and have the user-facing configuration be <em>code</em> rather than data.</p> <p>It should be noted that the primary motivation for having a data-oriented configuration language, that it makes it easier to interact with programmatically, doesn't really apply in Arachne's case. Since applications are always free to interact richly with Arachne's full configuration database, the ability to programmatically manipulate the precursor data is moot. As such, one major argument against a code-based configuration strategy does not apply.</p> <h2 id=decision-nan>Decision</h2> <p>Developers will have the option of writing configuration using either native Datomic-style, data, or code-based <em>configuration scripts</em>. Configuration scripts are Clojure files which, when evaluated, update a configuration stored in an atom currently in context (using a dynamically bound var.)</p> <p>Configuration scripts are Clojure source files in a distinct directory that by convention is <em>outside</em> the application's classpath: configuration code is conceptually and physically separate from application code. Conceptually, loading the configuration scripts could take place in an entirely different process from the primary application, serializing the resulting config before handing it to the runtime application.</p> <p>To further emphasize the difference between configuration scripts and runtime code, and because they are not on the classpath, configuration scripts will not have namespaces and will instead include each other via Clojure's <code>load</code> function.</p> <p>Arachne will provide code supporting the ability of module authors to write &quot;configuration DSLs&quot; for users to invoke from their configuration scripts. These DSLs will emphasize making it easy to create appropriate entities in the configuration. In general, DSL forms will have an imperative style: they will convert their arguments to configuration data and immediately transact it to the context configuration.</p> <p>As a trivial example, instead of writing the verbose configuration data:</p> <pre><code class="language-clojure">{:arachne/id :my.app/server :arachne.http.server/port 8080 :arachne.http.server/debug true} </code></pre> <p>You could write the corresponding DSL:</p> <pre><code class="language-clojure">(server :id :my.app/server, :port 8080, :debug true) </code></pre> <p>Note that this is an illustrative example and does not represent the actual DSL or config for the HTTP module.</p> <p>DSLs should make heavy use of Spec to make errors as comprehensible as possible.</p> <h2 id=status-nan>Status</h2> <p>Proposed</p> <h2 id=consequences-nan>Consequences</h2> <ul> <li>It will be possible for end users to define their configuration without writing config data by hand.</li> <li>Users will have access to the full power of the Clojure programming language when configuring their application. This grants a great deal of power and flexibility, but also the risk of users doing inadvisable things in their config scripts (e.g, non-repeatable side effects.)</li> <li>Module authors will bear the responsibility of providing an appropriate, user-friendly DSL interface to their configuration data.</li> <li>DSLs can compose; any module can reference and re-use the DSL definitions included in modules upon which it depends.</li> </ul> <h1 id=architecture-decision-record-core-runtime>Architecture Decision Record: Core Runtime</h1> <h2 id=context-nan>Context</h2> <p>At some point, every Arachne application needs to start; to bootstrap itself from a static project or deployment artifact, initialize what needs initializing, and begin servicing requests, connecting to databases, processing data, etc.</p> <p>There are several logically inherent subtasks to this bootstrapping process, which can be broken down as follows.</p> <ul> <li>Starting the JVM <ul> <li>Assembling the project's dependencies</li> <li>Building a JVM classpath</li> <li>Starting a JVM</li> </ul></li> <li>Arachne Specific <ul> <li>Reading the initial user-supplied configuration (i.e, the configuration scripts from <a href="adr-005-user-facing-config.md">ADR-005</a>)</li> <li>Initializing the Arachne configuration given a project's set of modules (described in <a href="adr-002-configuration.md">ADR-002</a> and <a href="adr-004-module-loading.md">ADR-004</a>)</li> </ul></li> <li>Application Specific <ul> <li>Instantiate user and module-defined objects that needs to exist at runtime.</li> <li>Start and stop user and module-defined services</li> </ul></li> </ul> <p>As discussed in <a href="adr-004-module-loading.md">ADR-004</a>, tasks in the &quot;starting the JVM&quot; category are not in-scope for Arachne; rather, they are offloaded to whatever build/dependency tool the project is using (usually either <a href="http://boot-clj.com">boot</a> or <a href="http://leiningen.org">leiningen</a>.)</p> <p>This leaves the Arachne and application-specific startup tasks. Arachne should provide an orderly, structured startup (and shutdown) procedure, and make it possible for modules and application authors to hook into it to ensure that their own code initializes, starts and stops as desired.</p> <p>Additionally, it must be possible for different system components to have dependencies on eachother, such that when starting, services start <em>after</em> the services upon which they depend. Stopping should occur in reverse-dependency order, such that a service is never in a state where it is running but one of its dependencies is stopped.</p> <h2 id=decision-nan>Decision</h2> <h4 id=components-nan>Components</h4> <p>Arachne uses the <a href="https://github.com/stuartsierra/component">Component</a> library to manage system components. Instead of requiring users to define a component system map manually, however, Arachne itself builds one based upon the Arachne config via <em>Configuration Entities</em> that appear in the configuration.</p> <p>Component entities may be added to the config directly by end users (via a initialization script as per <a href="adr-005-user-facing-config.md">ADR-005</a>), or by modules in their <code>configure</code> function (<a href="adr-004-module-loading.md">ADR-004</a>.)</p> <p>Component entities have attributes which indicates which other components they depend upon. Circular dependencies are not allowed; the component dependency structure must form a Directed Acyclic Graph (DAG.) The dependency attributes also specify the key that Component will use to <code>assoc</code> dependencies.</p> <p>Component entities also have an attribute that specifies a <em>component constructor function</em> (via a fully qualified name.) Component constructor functions must take two arguments: the configuration, and the entity ID of the component that is to be constructed. When invoked, a component constructor must return a runtime component object, to be used by the Component library. This may be any object that implements <code>clojure.lang.Associative</code>, and may also optionally satisfy Component's <code>Lifecycle</code> protocol.</p> <h4 id=arachne-runtime-nan>Arachne Runtime</h4> <p>The top-level entity in an Arachne system is a reified <em>Arachne Runtime</em> object. This object contains both the Component system object, and the configuration value upon which the runtime is based. It satisfies the <code>Lifecycle</code> protocol itself; when it is started or stopped, all of the component objects it contains are started or stopped in the appropriate order.</p> <p>The constructor function for a Runtime takes a configuration value and some number of &quot;roots&quot;; entity IDs or lookup refs of Component entities in the config. Only these root components and their transitive dependencies will be instantiated or added to the Component system. In other words, only component entities that are actually used will be instantiated; unused component entities defined in the config will be ignored.</p> <p>A <code>lookup</code> function will be provided to find the runtime object instance of a component, given its entity ID or lookup ref in the configuraiton.</p> <h4 id=startup-procedure-nan>Startup Procedure</h4> <p>Arachne will rely upon an external build tool (such as boot or leiningen.) to handle downloading dependencies, assembling a classpath, and starting a JVM.</p> <p>Once JVM with the correct classpath is running, the following steps are required to yield a running Arachne runtime:</p> <ol> <li>Determine a set of modules to use (the &quot;active modules&quot;)</li> <li>Build a configuration schema by querying each active module using its <code>schema</code> function (<a href="module-loading.md">ADR-004</a>)</li> <li>Update the config with initial configuration data from user init scripts (<a href="adr-005-user-facing-config.md">ADR-005</a>)</li> <li>In module dependency order, give each module a chance to query and update the configuration using its <code>configure</code> function (<a href="module-loading.md">ADR-004</a>)</li> <li>Create a new Arachne runtime, given the configuration and a set of root components.</li> <li>Call the runtime's <code>start</code> method.</li> </ol> <p>The Arachne codebase will provide entry points to automatically perform these steps for common development and production scenarios. Alternatively, they can always be be executed individually in a REPL, or composed in custom startup functions.</p> <h2 id=status-nan>Status</h2> <p>PROPOSED</p> <h2 id=consequences-nan>Consequences</h2> <ul> <li>It is possible to fully define the system components and their dependencies in an application's configuration. This is how Arachne achieves dependency injection and inversion of control.</li> <li>It is possible to explicitly create, start and stop Arachne runtimes.</li> <li>Multiple Arachne runtimes may co-exist in the same JVM (although they may conflict and fail to start if they both attempt to use a global resource such as a HTTP port)</li> <li>By specifying different root components when constructing a runtime, it is possible to run different types of Arachne applications based on the same Arachne configuration value.</li> </ul> <h1 id=architecture-decision-record-configuration-updates>Architecture Decision Record: Configuration Updates</h1> <h2 id=context-nan>Context</h2> <p>A core part of the process of developing an application is making changes to its configuration. With its emphasis on configuration, this is even more true of Arachne than with most other web frameworks.</p> <p>In a development context, developers will want to see these changes reflected in their running application as quickly as possible. Keeping the test/modify cycle short is an important goal.</p> <p>However, accommodating change is a source of complexity. Extra code would be required to handle &quot;update&quot; scenarios. Components are initialized with a particular configuration in hand. While it would be possible to require that every component support an <code>update</code> operation to receive an arbitrary new config, implementing this is non-trivial and would likely need to involve conditional logic to determine the ways in which the new configuration is different from the old. If any mistakes where made in the implementation of <code>update</code>, <em>for any component</em>, such that the result was not identical to a clean restart, it would be possible to put the system in an inconsistent, unreproducible state.</p> <p>The &quot;simplest&quot; approach is to avoid the issue and completely discard and rebuild the Arachne runtime (<a href="adr-006-core-runtime">ADR-006</a>) every time the configuration is updated. Every modification to the config would be applied via a clean start, guaranteeing reproducibility and a single code path.</p> <p>However, this simple baseline approach has two major drawbacks:</p> <ol> <li>The shutdown, initialization, and startup times of the entire set of components will be incurred every time the configuration is updated.</li> <li>The developer will lose any application state stored in the components whenever the config is modified.</li> </ol> <p>The startup and shutdown time issues are potentially problematic because of the general increase to cycle time. However, it might not be too bad depending on exactly how long it takes sub-components to start. Most commonly-used components take only a few milliseconds to rebuild and restart. This is a cost that most Component workflows absorb without too much trouble.</p> <p>The second issue is more problematic. Not only is losing state a drain on overall cycle speed, it is a direct source of frustration, causing developers to repeat the same tasks over and over. It will mean that touching the configuration has a real cost, and will cause developers to be hesitant to do so.</p> <h3 id=prior-art-nan>Prior Art</h3> <p>There is a library designed to solve the startup/shutdown problem, in conjunction with Component: <a href="https://github.com/weavejester/suspendable">Suspendable</a>. It is not an ideal fit for Arachne, since it focuses on suspending and resuming the same Component instances rather than rebuilding, but its approach may be instructive.</p> <h2 id=decision-nan>Decision</h2> <p>Whenever the configuration changes, we will use the simple approach of stopping and discarding the entire old Arachne runtime (and all its components), and starting a new one.</p> <p>To mitigate the issue of lost state, Arachne will provide a new protocol called <code>Preservable</code> (name subject to change, pending a better one.) Components may optionally implement <code>Preservable</code>; it is not required. <code>Preservable</code> defines a single method, <code>preserve</code>.</p> <p>Whenever the configuration changes, the following procedure will be used:</p> <ol> <li>Call <code>stop</code> on the old runtime.</li> <li>Instantiate the new runtime.</li> <li>For all components in the new runtime which implement <code>Preservable</code>, invoke the <code>preserve</code> function, passing it the corresponding component from the old runtime (if there is one).</li> <li>The <code>preserve</code> function will selectively copy state out of the old, stopped component into the new, not-yet-started component. It should be careful not to copy any state that would be invalidated by a configuration change.</li> <li>Call <code>start</code> on the new runtime.</li> </ol> <p>Arachne will not provide a mitigation for avoiding the cost of stopping and starting individual components. If this becomes a pain point, we can explore solutions such as that offered by Suspendable.</p> <h2 id=status-nan>Status</h2> <p>PROPOSED</p> <h2 id=consequences-nan>Consequences</h2> <ul> <li>The basic model for handling changes to the config will be easy to implement and reason about.</li> <li>It will be possible to develop with stateful components without losing state after a configuration change.</li> <li>Only components which need preservable state need to worry about it.</li> <li>The default behavior will prioritize correctness.</li> <li>It is <em>possible</em> to write a bad <code>preserve</code> method which copies elements of the old configuration.</li> <li>However, because all copies are explicit, it should be easy to avoid writing bad <code>preserve</code> methods.</li> </ul> <h1 id=architecture-decision-record-abstract-modules>Architecture Decision Record: Abstract Modules</h1> <h2 id=context-nan>Context</h2> <p>One design goal of Arachne is to have modules be relatively easily swappable. Users should not be permanently committed to particular technical choices, but instead should have some flexibility in choosing their preferred tech, as long as it exists in the form of an Arachne module.</p> <p>Some examples of the alternative implementations that people might wish to use for various parts of their application:</p> <ul> <li>HTTP Server: Pedestal or Ring</li> <li>Database: Datomic, an RDBMS or one of many NoSQL options.</li> <li>HTML Templating: Hiccup, Enlive, StringTemplate, etc.</li> <li>Client-side code: ClojureScript, CoffeeScript, Elm, etc.</li> <li>Authentication: Password-based, OpenID, Facebook, Google, etc.</li> <li>Emailing: SMTP, one of many third-party services.</li> </ul> <p>This is only a representative sample; the actual list is unbounded.</p> <p>The need for this kind of flexibility raises some design concerns:</p> <p><strong>Capability</strong>. Users should always be able to leverage the full power of their chosen technology. That is, they should not have to code to the &quot;least common denominator&quot; of capability. If they use Datomic Pro, for example, they should be able to write Datalog and fully utilize the in-process Peer model, not be restricted to an anemic &quot;ORM&quot; that is also compatible with RDBMSs.</p> <p><strong>Uniformity</strong>. At tension with capability is the desire for uniformity; where the feature set of two alternatives is <em>not</em> particularly distinct, it is desirable to use a common API, so that implementations can be swapped out with little or no effort. For example, the user-facing API for sending a single email should (probably) not care whether it is ultimately sent via a local Sendmail server or a third-party service.</p> <p><strong>Composition</strong>. Modules should also <em>compose</em> as much as possible, and they should be as general as possible in their dependencies to maximize the number of compatible modules. In this situation, it is actually desirable to have a &quot;least common denominator&quot; that modules can have a dependency on, rather than depending on specific implementations. For example, many modules will need to persist data and ultimately will need to work in projects that use Datomic or SQL. Rather than providing multiple versions, one for Datomic users and another for SQL, it would be ideal if they could code against a common persistence abstraction, and therefore be usable in <em>any</em> project with a persistence layer.</p> <h3 id=what-does-it-mean-to-use-a-module-nan>What does it mean to use a module?</h3> <p>The following list enumerates the ways in which it is possible to &quot;use&quot; a module, either from a user application or from another module. (See <a href="ADR-004-module-loading.md">ADR-004</a>).</p> <ol> <li>You can call code that the module provides (the same as any Clojure library.)</li> <li>You can extend a protocol that the module provides (the same as any Clojure library.)</li> <li>You can read the attributes defined in the module from the configuration.</li> <li>You can write configuration data using the attributes defined in the module.</li> </ol> <p>These tools allow the definition of modules with many different kinds of relationships to each other. Speaking loosely, these relationships can correspond to other well-known patterns in software development including composition, mixins, interface/implementation, inheritance, etc.</p> <h2 id=decision-nan>Decision</h2> <p>In order to simultaneously meet the needs for capability, uniformity and composition, Arachne's core modules will (as appropriate) use the pattern of <em>abstract modules</em>.</p> <p>Abstract modules define certain attributes (and possibly also corresponding init script DSLs) that describe entities in a particular domain, <em>without</em> providing any runtime implementation which uses them. Then, other modules can &quot;implement&quot; the abstract module, reading the abstract entities and doing something concrete with them at runtime, as well as defining their own more specific attributes.</p> <p>In this way, user applications and dependent modules can rely either on the common, abstract module or the specific, concrete module as appropriate. Coding against the abstract module will yield a more generic &quot;least common denominator&quot; experience, while coding against a specific implementor will give more access to the unique distinguishing features of that particular technology, at the cost of generality.</p> <p>Similar relationships should hold in the library code which modules expose (if any.) An abstract module, for example, would be free to define a protocol, intended to be implemented concretely by code in an implementing module.</p> <p>This pattern is fully extensible; it isn't limited to a single level of abstraction. An abstract module could itself be a narrowing or refinement of another, even more general abstract module.</p> <h3 id=concrete-example-nan>Concrete Example</h3> <p>As mentioned above, Arachne would like to support both Ring and Pedestal as HTTP servers. Both systems have a number of things in common:</p> <ul> <li>The concept of a &quot;server&quot; running on a port.</li> <li>The concept of a URL path/route</li> <li>The concept of a terminal &quot;handler&quot; function which receives a request and returns a response.</li> </ul> <p>They also have some key differences:</p> <ul> <li>Ring composes &quot;middleware&quot; functions, whereas Pedestal uses &quot;interceptor&quot; objects</li> <li>Asynchronous responses are handled differently</li> </ul> <p>Therefore, it makes sense to define an abstract HTTP module which defines the basic domain concepts; servers, routes, handlers, etc. Many dependent modules and applications will be able to make real use of this subset.</p> <p>Then, there will be the two modules which provide concrete implementations; one for Pedestal, one for Ring. These will contain the code that actually reads the configuration, and at runtime builds appropriate routing tables, starts server instances, etc. Applications which wish to make direct use of a specific feature like Pedestal interceptors may freely do so, using attributes defined by the Pedestal module.</p> <h2 id=status-nan>Status</h2> <p>PROPOSED</p> <h2 id=consequences-nan>Consequences</h2> <ul> <li>If modules or users want to program against a &quot;lowest common denominator&quot; abstraction, they may do so, at the cost of the ability to use the full feature set of a library.</li> <li>If modules or users want to use the full feature set of a library, they may do so, at the cost of being able to transparently replace it with something else.</li> <li>There will be a larger number of different Arachne modules available, and their relationships will be more complex.</li> <li>Careful thought and architecture will need to go into the factoring of modules, to determine what the correct general elements are.</li> </ul> <h1 id=architecture-decision-record-configuration-ontology>Architecture Decision Record: Configuration Ontology</h1> <h2 id=context-nan>Context</h2> <p>In <a href="adr-003-config-implementation.md">ADR-003</a> it was decided to use a Datomic-based configuration, the alternative being something more semantically or ontologically descriptive such as RDF+OWL.</p> <p>Although we elected to use Datomic, Datomic does not itself offer much ontological modeling capacity. It has no built-in notion of types/classes, and its attribute specifications are limited to what is necessary for efficient storage and indexing, rather than expressive or validative power.</p> <p>Ideally, we want modules to be able to communicate additional information about the structure and intent of their domain model, including:</p> <ul> <li>Types of entities which can exist</li> <li>Relationships between those types</li> <li>Logical constraints on the values of attributes: <ul> <li>more fine grained cardinality; optional/required attributes</li> <li>valid value ranges</li> <li>target entity type (for ref attributes)</li> </ul></li> </ul> <p>This additional data could serve three purposes:</p> <ul> <li>Documentation about the intended purpose and structure of the configuration defined by a module.</li> <li>Deeper, more specific validation of user-supplied configuration values</li> <li>Machine-readable integration point for tools which consume and produce Arachne configurations.</li> </ul> <h2 id=decision-nan>Decision</h2> <ul> <li>We will add meta-attributes to the schema of every configuration, expressing basic ontological relationships.</li> <li>These attributes will be semantically compatible with OWL (such that we could conceivably in the future generate an OWL ontology from a config schema)</li> <li>The initial set of these attributes will be minimal, and targeted towards the information necessary to generate rich schema diagrams <ul> <li>classes and superclass</li> <li>attribute domain</li> <li>attribute range (for ref attributes)</li> <li>min and max cardinality</li> </ul></li> <li>Arachne core will provide some (optional) utility functions for schema generation, to make writing module schemas less verbose.</li> </ul> <h2 id=status-nan>Status</h2> <p>PROPOSED</p> <h2 id=consequences-nan>Consequences</h2> <ul> <li>Arachne schemas will reify the concept of entity type and the possible relationships between entities of various types.</li> <li>We will have an approach for adding additional semantic attributes in the future, as it makes sense to do so.</li> <li>We will not be obligated to define an entire ontology up front</li> <li>Modules usage of the defined ontology is not technically enforced. Some, (such as entity type relationships) will be the strong convention and possibly required for tool support; others (such as min and max cardinality) will be optional.</li> <li>We will preserve the possibility for interop with OWL in the future.</li> </ul> <h1 id=architecture-decision-record-persistent-configuration>Architecture Decision Record: Persistent Configuration</h1> <h2 id=context-nan>Context</h2> <p>While many Arachne applications will use a transient config which is rebuilt from its initialization scripts every time an instance is started, some users might wish instead to store their config persistently in a full Datomic instance.</p> <p>There are a number of possible benefits to this approach:</p> <ul> <li>Deployments from the same configuration are highly reproducible</li> <li>Organizations can maintain an immutable persistent log of configuration changes over time.</li> <li>External tooling can be used to persistently build and define configurations, up to and including full &quot;drag and drop&quot; architecture or application design.</li> </ul> <p>Doing this introduces a number of additional challenges:</p> <ul> <li><p><strong>Initialization Scripts</strong>: Having a persistent configuration introduces the question of what role initialization scripts play in the setup. Merely having a persistent config does not make it easier to modify by hand - quite the opposite. While an init script could be used to create the configuration, it's not clear how they would be updated from that point (absent a full config editor UI.)</p> <p>Re-running a modified configuration script on an existing configuration poses challenges as well; it would require that all scripts be idempotent, so as not to create spurious objects on subsequent runs. Also, scripts would then need to support some concept of retraction.</p></li> <li><p><strong>Scope &amp; Naming</strong>: It is extremely convenient to use <code>:db.unique/identity</code> attributes to identify particular entities in a configuration and configuration init scripts. This is not only convenient, but <em>required</em> if init scripts are to be idempotent, since this is the only mechanism by which Datomic can determine that a new entity is &quot;the same&quot; as an older entity in the system.</p> <p>However, if there are multiple different configurations in the same database, there is the risk that some of these unique values might be unintentionally the same and &quot;collide&quot;, causing inadvertent linkages between what ought to be logically distinct configurations.</p> <p>While this can be mitigated in the simple case by ensuring that every config uses its own unique namespace, it is still something to keep in mind.</p></li> <li><p><strong>Configuration Copying &amp; Versioning</strong> Although Datomic supports a full history, that history is linear. Datomic does not currently support &quot;forking&quot; or maintaining multiple concurrent versions of the same logical data set.</p> <p>This does introduce complexities when thinking about &quot;modifying&quot; a configuration, while still keeping the old one. This kind of &quot;fork&quot; would require a deep clone of all the entities in the config, <em>as well as</em> renaming all of the <code>:db.unique/identity</code> attrs.</p> <p>Renaming identity attributes compounds the complexity, since it implies that either idents cannot be hardcoded in initialization scripts, or the same init script cannot be used to generate or update two different configurations.</p></li> <li><p><strong>Environment-specific Configuration</strong>: Some applications need slightly different configurations for different instances of the &quot;same&quot; application. For instance, some software needs to be told what its own IP address is. While it makes sense to put this data in the configuration, this means that there would no longer be a single configuration, but N distinct (yet 99% identical) configurations.</p> <p>One solution would be to not store this data in the configuration (instead picking it up at runtime from an environment variable or secondary config file), but multiplying the sources of configuration runs counter to Arachne's overriding philosophy of putting everything in the configuration to start with.</p></li> <li><p><strong>Relationship with module load process</strong>: Would the stored configuration represent only the &quot;initial&quot; configuration, before being updated by the active modules? Or would it represent the complete configuration, after all the modules have completed their updates?</p> <p>Both alternatives present issues.</p> <p>If only the user-supplied, initial config is stored, then the usefulness of the stored config is diminished, since it does not provide a comprehensive, complete view of the configuration.</p> <p>On the other hand, if the complete, post-module config is persisted, it raises more questions. What happens if the user edits the configuration in ways that would cause modules to do something different with the config? Is it possible to run the module update process multiple times on the same config? If so, how would &quot;old&quot; or stale module-generated values be removed?</p></li> </ul> <h4 id=goals-nan>Goals</h4> <p>We need a technical approach with good answers to the challenges described above, that enables a clean user workflow. As such, it is useful to enumerate the specific activities that it would be useful for a persistent config implementation to support:</p> <ul> <li>Define a new configuration from an init script.</li> <li>Run an init script on an existing configuration, updating it.</li> <li>Edit an existing configuration using the REPL.</li> <li>Edit an existing configuration using a UI.</li> <li>Clone a configuration</li> <li>Deploy based on a specific configuration</li> </ul> <p>At the same time, we need to be careful not to overly complicate things for the common case; most applications will still use the pattern of generating a configuration from an init script immediately before running an application using it.</p> <h2 id=decision-nan>Decision</h2> <p>We will not attempt to implement a concrete strategy for config persistence at this time; it runs the risk of becoming a quagmire that will halt forward momentum.</p> <p>Instead, we will make a minimal set of choices and observations that will enable forward progress while preserving the ability to revisit the issue of persistent configuration at some point in the future.</p> <ol> <li>The configuration schema itself should be compatible with having several configurations present in the same persistent database. Specifically:</li> </ol> <ul> <li>Each logical configuration should have its own namespace, which will be used as the namespace of all <code>:db.unique/identity</code> values, ensuring their global uniqueness.</li> <li>There is a 'configuration' entity that reifies a config, its possible root components, how it was constructed, etc.</li> <li>The entities in a configuration must form a connected graph. That is, every entity in a configuration must be reachable from the base 'config' entity. This is required to have any ability to identify the config as a whole within for any purpose.</li> </ul> <ol start="2"> <li><p>The current initial <em>tooling</em> for building configurations (including the init scripts) will focus on building configurations from scratch. Tooling capable of &quot;editing&quot; an existing configuration is sufficiently different, with a different set of requirements and constraints, that it needs its own design process.</p></li> <li><p>Any future tooling for storing, viewing and editing configurations will need to explicitly determine whether it wants to work with the configuration before or after processing by the modules, since there is a distinct set of tradeoffs.</p></li> </ol> <h2 id=status-nan>Status</h2> <p>PROPOSED</p> <h2 id=consequences-nan>Consequences</h2> <ol> <li>We can continue making forward progress on the &quot;local&quot; configuration case.</li> <li>Storing persistent configurations remains possible.</li> <li>It is immediately possible to save configurations for repeatability and debugging purposes. <ul> <li>The editing of persistent configs is what will be more difficult.</li> </ul></li> <li>When we want to edit persistent configurations, we will need to analyze the specific use cases to determine the best way to do so, and develop tools specific to those tasks.</li> </ol> <h1 id=architecture-decision-record-asset-pipeline>Architecture Decision Record: Asset Pipeline</h1> <h2 id=context-nan>Context</h2> <p>In addition to handling arbitrary HTTP requests, we would like for Arachne to make it easy to serve up certain types of well-known resources, such as static HTML, images, CSS, and JavaScript.</p> <p>These &quot;static assets&quot; can generally be served to users as files directly, without processing at the time they are served. However, it is extremely useful to provide <em>pre-processing</em>, to convert assets in one format to another format prior to serving them. Examples of such transformations include:</p> <ul> <li>SCSS/LESS to CSS</li> <li>CoffeeScript to JavaScript</li> <li>ClojureScript to JavaScript</li> <li>Full-size images to thumbnails</li> <li>Compress files using gzip</li> </ul> <p>Additionally, in some cases, several such transformations might be required, on the same resource. For example, a file might need to be converted from CoffeeScript to JavaScript, then minified, then gzipped.</p> <p>In this case, asset transformations form a logical pipeline, applying a set of transformations in a known order to resources that meet certain criteria.</p> <p>Arachne needs a module that defines a way to specify what assets are, and what transformations ought to apply and in what order. Like everything else, this system needs to be open to extension by other modules, to provide custom processing steps.</p> <h3 id=development-vs-production-nan>Development vs Production</h3> <p>Regardless of how the asset pipeline is implemented, it must provide a good development experience such that the developer can see their changes immediately. When the user modifies an asset file, it should be automatically reflected in the running application in near realtime. This keeps development cycle times low, and provides a fluid, low-friction development experience that allows developers to focus on their application.</p> <p>Production usage, however, has a different set of priorities. Being able to reflect changes is less important; instead, minimizing processing cost and response time is paramount. In production, systems will generally want to do as much processing as they can ahead of time (during or before deployment), and then cache aggressively.</p> <h3 id=deployment--distribution-nan>Deployment &amp; Distribution</h3> <p>For development and simple deployments, Arachne should be capable of serving assets itself. However, whatever technique it uses to implement the asset pipeline, it should also be capable of sending the final assets to a separate cache or CDN such that they can be served statically with optimal efficiency. This may be implemented as a separate module from the core asset pipeline, however.</p> <h3 id=entirely-static-sites-nan>Entirely Static Sites</h3> <p>There is a large class of websites which actually do not require any dynamic behavior at all; they can be built entirely from static assets (and associated pre-processing.) Examples of frameworks that cater specifically to this type of &quot;static site generation&quot; include Jekyll, Middleman, Brunch, and many more.</p> <p>By including the asset pipeline module, and <em>not</em> the HTTP or Pedestal modules, Arachne also ought to be able to function as a capable and extensible static site generator.</p> <h2 id=decision-nan>Decision</h2> <p>Arachne will use Boot to provide an abstract asset pipeline. Boot has built-in support for immutable Filesets, temp directory management, and file watchers.</p> <p>As with everything in Arachne, the pipeline will be specified as pure data in the configuration, specifying inputs, outputs, and transformations explicitly.</p> <p>Modules that participate in the asset pipeline will develop against a well-defined API built around Boot Filesets.</p> <h2 id=status-nan>Status</h2> <p>PROPOSED</p> <h2 id=consequences-nan>Consequences</h2> <ul> <li>The asset pipeline will be fully specified as data in the Arachne configuration.</li> <li>Adding Arachne support for an asset transformation will involve writing a relatively straightforward wrapper adapting the library to work on boot Filesets.</li> <li>We will need to program against some of Boot's internal APIs, although Alan and Micha have suggested they would be willing to factor out the Fileset support to a separate library.</li> </ul> <h1 id=architecture-decision-record-enhanced-validation>Architecture Decision Record: Enhanced Validation</h1> <h2 id=context-nan>Context</h2> <p>As much as possible, an Arachne application should be defined by its configuration. If something is wrong with the configuration, there is no way that an application can be expected to work correctly.</p> <p>Therefore, it is desirable to validate that a configuration is correct to the greatest extent possible, at the earliest possible moment. This is important for two distinct reasons:</p> <ul> <li>Ease of use and developer friendliness. Config validation can return helpful errors that point out exactly what's wrong instead of deep failures with lengthy debug sessions.</li> <li>Program correctness. Some types of errors in configs might not be discovered at all during testing or development, and aggressively failing on invalid configs will prevent those issues from affecting end users in production.</li> </ul> <p>There are two &quot;kinds&quot; of config validation.</p> <p>The first is ensuring that a configuration as data is structurally correct; that it adheres to its own schema. This includes validating types and cardinalities as expressed by the Arachne's core ontology system.</p> <p>The second is ensuring that the Arachne Runtime constructed from a given configuration is correct; that the runtime component instances returned by component constructors are of the correct type and likely to work.</p> <h2 id=decision-nan>Decision</h2> <p>Arachne will perform both kinds of validation. To disambiguate them (since they are logically distinct), we will term the structural/schema validation &quot;configuration validation&quot;, while the validation of the runtime objects will be &quot;runtime validation.&quot;</p> <p>Both styles of validation should be extensible by modules, so modules can specify additional validations, where necessary.</p> <h4 id=configuration-validation-nan>Configuration Validation</h4> <p>Configuration validation is ensuring that an Arachne configuration object is consistent with itself and with its schema.</p> <p>Because this is ultimately validating a set of Datomic style <code>eavt</code> tuples, the natural form for checking tuple data is Datalog queries and query rules, to search for and locate data that is &quot;incorrect.&quot;</p> <p>Each logical validation will have its own &quot;validator&quot;, a function which takes a config, queries it, and either returns or throws an exception. To validate a config, it is passed through every validator as the final step of building a module.</p> <p>The set of validators is open, and defined in the configuration itself. To add new validators, a module can transact entities for them during its configuration building phase.</p> <h4 id=runtime-validation-nan>Runtime Validation</h4> <p>Runtime validation occurs after a runtime is instantiated, but before it is started. Validation happens on the component level; each component may be subject to validation.</p> <p>Unlike Configuration validation, Runtime validation uses Spec. What specs should be applied to each component are defined in the configuration using a keyword-valued attribute. Specs may be defined on individual component entities, or to the <em>type</em> of a component entity. When a component is validated, it is validated using all the specs defined for it or any of its supertypes.</p> <h2 id=status-nan>Status</h2> <p>PROPOSED</p> <h2 id=consequences-nan>Consequences</h2> <ul> <li>Validations have the opportunity to find errors and return clean error messages</li> <li>Both the structure of the config and the runtime instances can be validated</li> <li>The configuration itself describes how it will be validated</li> <li>Modules have complete flexibility to add new validations</li> <li>Users can write custom validations</li> </ul> <h1 id=architecture-decision-record-error-reporting>Architecture Decision Record: Error Reporting</h1> <h2 id=context-nan>Context</h2> <p>Historically, error handling has not been Clojure's strong suit. For the most part, errors take the form of a JVM exception, with a long stack trace that includes a lot of Clojure's implementation as well as stack frames that pertain directly to user code.</p> <p>Additionally, prior to the advent of <code>clojure.spec</code>, Clojure errors were often &quot;deep&quot;: a very generic error (like a NullPointerException) would be thrown from far within a branch, rather than eagerly validating inputs.</p> <p>There are Clojure libraries which make an attempt to improve the situation, but they typically do it by overriding Clojure's default exception printing functions across the board, and are sometimes &quot;lossy&quot;, dropping information that could be desirable to a developer.</p> <p>Spec provides an opportunity to improve the situation across the board, and with Arachne we want to be on the leading edge of providing helpful error messages that point straight to the problem, minimize time spent trying to figure out what's going on, and let developers get straight back to working on what matters to them.</p> <p>Ideally, Arachne's error handling should exhibit the following qualities:</p> <ul> <li>Never hide possibly relevant information.</li> <li>Allow module developers to be as helpful as possible to people using their tools.</li> <li>Provide rich, colorful, multi-line detailed explanations of what went wrong (when applicable.)</li> <li>Be compatible with existing Clojure error-handling practices for errors thrown from libraries that Arachne doesn't control.</li> <li>Not violate expectations of experienced Clojure programmers.</li> <li>Be robust enough not to cause additional problems.</li> <li>Not break existing logging tools for production use.</li> </ul> <h2 id=decision-nan>Decision</h2> <p>We will separate the problems of creating rich exceptions, and catching them and displaying them to the user.</p> <h3 id=creating-errors-nan>Creating Errors</h3> <p>Whenever a well-behaved Arachne module needs to report an error, it should throw an info-bearing exception. This exception should be formed such that it is handled gracefully by any JVM tooling; the message should be terse but communicative, containing key information with no newlines.</p> <p>However, in the <code>ex-data</code>, the exception will also contain much more detailed information, that can be used (in the correct context) to provide much more detailed or verbose errors. Specifically, it may contain the following keys:</p> <ul> <li><code>:arachne.error/message</code> - The short-form error message (the same as the Exception message.)</li> <li><code>:arachne.error/explanation</code> - a long-form error message, complete with newlines and formatting.</li> <li><code>:arachne.error/suggestions</code> - Zero or more suggestions on how the error might be fixed.</li> <li><code>:arachne.error/type</code> - a namespaced keyword that uniquely identifies the type of error.</li> <li><code>:arachne.error/spec</code> - The spec that failed (if applicable)</li> <li><code>:arachne.error/failed-data</code> - The data that failed to match the spec (if applicable)</li> <li><code>:arachne.error/explain-data</code> - An explain-data for the spec that failed (if applicable).</li> <li><code>:arachne.error/env</code> - A map of the locals in the env at the time the error was thrown.</li> </ul> <p>Exceptions may, of course, contain additional data; these are the common keys that tools can use to more effectively render errors.</p> <p>There will be a suite of tools, provided with Arachne's core, for conveniently generating errors that match this pattern.</p> <h3 id=displaying-errors-nan>Displaying Errors</h3> <p>We will use a pluggable &quot;error handling system&quot;, where users can explicitly install an exception handler other than the default.</p> <p>If the user does not install any exception handlers, errors will be handled the same way as they are by default (usually, dumped with the message and stack trace to <code>System/err</code>.) This will not change.</p> <p>However, Arachne will also provide a function that a user can invoke in their main process, prior to doing anything else. Invoking this function will install a set of default exception handlers that will handle errors in a richer, more Arachne-specific way. This includes printing out the long-form error, or even (eventually) popping open a graphical data browser/debugger (if applicable.)</p> <h2 id=status-nan>Status</h2> <p>PROPOSED</p> <h2 id=consequences-nan>Consequences</h2> <ul> <li>Error handling will follow well-known JVM patterns.</li> <li>If users want, they can get much richer errors than baseline exception handling.</li> <li>The &quot;enhanced&quot; exception handling is optional and will not be present in production.</li> </ul> <h1 id=architecture-decision-record-project-templates>Architecture Decision Record: Project Templates</h1> <h2 id=context-nan>Context</h2> <p>When starting a new project, it isn't practical to start completely from scratch, every time. We would like to have a varity of &quot;starting point&quot; projects, for different purposes.</p> <h3 id=lein-templates-nan>Lein templates</h3> <p>In the Clojure space, Leiningen Templates fill this purpose. These are sets of special string-interpolated files that are &quot;rendered&quot; into a working project using special tooling.</p> <p>However, they have two major drawbacks:</p> <ul> <li>They only work when using Leiningen as a build tool.</li> <li>The template files are are not actually valid source files, which makes them difficult to maintain. Changes need to be manually copied over to the templates.</li> </ul> <h3 id=rails-templates-nan>Rails templates</h3> <p>Rails also provides a complete project templating solution. In Rails, the project template is a <code>template.rb</code> file which contains DSL forms that specify operations to perform on a fresh project. These operations include creating files, modifying a projects dependencies, adding Rake tasks, and running specific <em>generators</em>.</p> <p>Generators are particularly interesting, because the idea is that they can generate or modify stubs for files pertaining to a specific part of the application (e.g, a new model or a new controller), and they can be invoked <em>at any point</em>, not just initial project creation.</p> <h2 id=decision-nan>Decision</h2> <p>To start with, Arachne templates will be standard git repositories containing an Arachne project. They will use no special syntax, and will be valid, runnable projects out of the box.</p> <p>In order to allow users to create their own projects, these template projects will include a <code>rename</code> script. The <code>rename</code> script will recursively rename an entire project directory to something that the user chooses, and will delete <code>.git</code> and re-run <code>git init</code>,</p> <p>Therefore, the process to start a new Arachne project will be:</p> <ol> <li>Choose an appropriate project template.</li> <li>Clone its git repository from Github</li> <li>Run the <code>rename</code> script to rename the project to whatever you wish</li> <li>Start a repl, and begin editing.</li> </ol> <h3 id=maven-distribution-nan>Maven Distribution</h3> <p>There are certain development environments where there is not full access to the open internet (particularly in certain governmental applications.) Therefore, accessing GitHub can prove difficult. However, in order to support developers, these organizations often run their own Maven mirrors.</p> <p>As a convenience to users in these situations, when it is necessary, we can build a wrapper that can compress and install a project directory as a Maven artifact. Then, using standard Maven command line tooling, it will be possible to download and decompress the artifact into a local filesystem directory, and proceed as normal.</p> <h2 id=status-nan>Status</h2> <p>PROPOSED</p> <h2 id=consequences-nan>Consequences</h2> <ul> <li>It will take only a few moments for users to create new Arachne projects.</li> <li>It will be straightforward to build, curate, test and maintain multiple different types of template projects.</li> <li>The only code we will need to write to support templates is the &quot;rename&quot; script.</li> <li>The rename script will need to be capable of renaming all the code and files in the template, with awareness of the naming requirements and conventions for Clojure namespaces and code.</li> <li>Template projects themselves can be built continuously using CI</li> </ul> <h3 id=contrast-with-rails-nan>Contrast with Rails</h3> <p>One way that this approach is inferior to Rails templates is that this approach is &quot;atomic&quot;; templating happens once, and it happens for the whole project. Rails templates can be composed of many different generators, and generators can be invoked at any point over a project's lifecycle to quickly stub out new functionality.</p> <p>This also has implications for maintenance; because Rails generators are updated along with each Rails release, the template itself is more stable, wheras Arachne templates would need to be updated every single time Arachne itself changes. This imposes a maintenance burden on templates maintained by the core team, and risks poor user experience for users who find and try to use an out-of-date third-party template.</p> <p>However, there is is mitigating difference between Arachne and Rails, which relates directly to the philosophy and approach of the two projects.</p> <p>In Rails, the project <em>is</em> the source files, and the project directory layout. If you ask &quot;where is a controller?&quot;, you can answer by pointing to the relevant <code>*.rb</code> file in the <code>app/controllers</code> directory. So in Rails, the task &quot;create a new controller&quot; <em>is equivalent to</em> creating some number of new files in the appropriate places, containing the appropriate code. Hence the importance of generators.</p> <p>In Arachne, by contrast, the project is not ultimately defined by its source files and directory structure; it is defined by the config. Of course there <em>are</em> source files and a directory structure, and there will be some conventions about how to organize them, but they are not the very definition of a project. Instead, a project's <em>Configuration</em> is the canonical definition of what a project is and what it does. If you ask &quot;where is a controller?&quot; in Arachne, the only meaningful answer is to point to data in the configuration. And the task &quot;create a controller&quot; means inserting the appropriate data into the config (usually via the config DSL.)</p> <p>As a consequence, Arachne can focus less on code generation, and more on generating <em>config</em> data. Instead of providing a <em>code</em> generator which writes source files to the project structure, Arachne can provide <em>config</em> generators which users can invoke (with comparable effort) in their config scripts.</p> <p>As such, Arachne templates will typically be very small. In Arachne, code generation is an antipattern. Instead of making it easy to generate code, Arachne focuses on building abstractions that let users specify their intent directly, in a terse manner.</p> <h1 id=architecture-decision-record-data-abstraction-model>Architecture Decision Record: Data Abstraction Model</h1> <h2 id=context-nan>Context</h2> <p>Most applications need to store and manipulate data. In the current state of the art in Clojure, this is usually done in a straightforward, ad-hoc way. Users write schema, interact with their database, and parse data from user input into a persistence format using explicit code.</p> <p>This is acceptable, if you're writing a custom, concrete application from scratch. But it will not work for Arachne. Arachne's modules need to be able to read and write domain data, while also being compatible with multiple backend storage modules.</p> <p>For example a user/password based authentication module needs to be able to read and write user records to the application database, and it should work whether a user is using a Datomic, SQL or NoSQL database.</p> <p>In other words, Arachne cannot function well in a world in which every module is required to interoperate directly against one of several alternative modules. Instead, there needs to be a way for modules to &quot;speak a common language&quot; for data manipulation and persistence.</p> <h3 id=other-use-cases-nan>Other use cases</h3> <p>Data persistence isn't the only concern. There are many other situations where having a common, abstract data model is highly useful. These include:</p> <ul> <li>quickly defining API endpoints based on a data model</li> <li>HTML &amp; mobile form generation</li> <li>generalized data validation tools</li> <li>unified administration &amp; metrics tools</li> </ul> <h3 id=modeling--manipulation-nan>Modeling &amp; Manipulation</h3> <p>There are actually two distinct concepts at play; data <em>modeling</em> and data <em>manipulation</em>.</p> <p><strong>Modeling</strong> is the activity of defining the abstract shape of the data; essentially, it is writing schema, but in a way that is not specific to any concrete implementation. Modules can then use the data model to generate concrete schema, generate API endpoints, forms, validate data, etc.</p> <p><strong>Manipulation</strong> is the activity of using the model to create, read update or delete actual data. For an abstract data manipulation layer, this generally means a polymorphic API that supports some common set of implementations, which can be extended to concrete CRUD operations</p> <h3 id=existing-solutions-orms-nan>Existing solutions: ORMs</h3> <p>Most frameworks have some answer to this problem. Rails has ActiveRecord, Elixir has Ecto, old-school Java has Hibernate, etc. In every case, they try to paper over what it looks like to access the actual database, and provide an idiomatic API in the language to read and persist data. This language-level API is uniformly designed to make the database &quot;easy&quot; to use, but also has the effect of providing a common abstraction point for extensions.</p> <p>Unfortunately, ORMs also exhibit a common set of problems. By their very nature, they are an extra level of indirection. They provide abstraction, but given how complex databases are the abstraction is always &quot;leaky&quot; in significant ways. Using them effectively requires a thorough understanding not only of the ORM's APIs, but also the underlying database implementation, and what the ORM is doing to map the data from one format to another.</p> <p>ORMs are also tied more or less tightly to the relational model. Attempts to extend ActiveRecord (for example) to non-relational data stores have had varying levels of success.</p> <h3 id=database-migrations-nan>Database &quot;migrations&quot;</h3> <p>One other function is to make sure that the concrete database schema matches the abstract data model that the application is using. Most ORMs implement this using some form of &quot;database migrations&quot;, which serve as a repeatable series of all changes made to a database. Ideally, these are not redundant with the abstract data model, to avoid repeating the same information twice and also to ensure consistency.</p> <h2 id=decision-nan>Decision</h2> <p>Arachne will provide a lightweight model for data abstraction and persistence, oriented around the Entity/Attribute mode. To avoid word salad and acronyms loaded with baggage and false expectations, we will give it a semantically clean name. We will be free to define this name, and set expectations around what it is and how it is to be used. I suggest &quot;Chimera&quot;, as it is in keeping with the Greek mythology theme and has several relevant connotations.</p> <p>Chimera consists of two parts:</p> <ul> <li>An entity model, to allow application authors to easily specify the shape of their domain data in their Arachne configuration.</li> <li>A set of persistence operations, oriented around plain Clojure data (maps, sets and vectors) that can be implemented meaningfully against multiple types of adapters. Individual operations are granular and can be both consumed and provided á la carte; adapters that don't support certain behaviors can omit them (at the cost of compatibility with modules that need them.)</li> </ul> <p>Although support for any arbitrary database cannot be guaranteed, the persistence operations are designed to support a majority of commonly used systems, including relational SQL databases, document stores, tuple stores, Datomic, or other &quot;NoSQL&quot; type systems.</p> <p>At the data model level, Chimera should be a powerful, easy to use way to specify the structure of your data, as data. Modules can then read this data and expose new functionality driven by the application domain model. It needs to be flexible enough that it can be &quot;projected&quot; as schema into diverse types of adapters, and customizable enough that it can be configured to adapt to existing database installations.</p> <h4 id=adapters-nan>Adapters</h4> <p>Chimera <em>Adapters</em> are Arachne modules which take the abstract data structures and operations defined by Chimera, and extend them to specific databases or database APIs such as JDBC, Datomic, MongoDB, etc.</p> <p>When applicable, there can also be &quot;abstract adapters&quot; that do the bulk of the work of adapting Chimera to some particular genre of database. For example, most key/value stores have similar semantics and core operations: there will likely be a &quot;Key/Value Adapter&quot; that does the bulk of the work for adapting Chimera's operations to key/value storage, and then several thin <em>concrete</em> adapters that implement the actual get/put commands for Cassandra, DynamoDB, Redis, etc.</p> <h3 id=limitations-and-drawbacks-nan>Limitations and Drawbacks</h3> <p>Chimera is designed to make a limited set of common operations <em>possible</em> to write generically. It is not and cannot ever be a complete interface to every database. Application developers <em>can</em> and <em>should</em> understand and use the native APIs of their selected database, or use a dedicated wrapper module that exposes the full power of their selected technology. Chimera represents only a single dimension of functionality; the entity/attribute model. By definition, it cannot provide access to the unique and powerful features that different databases provide and which their users ought to leverage.</p> <p>It is also important to recognize that there are problems (even problems that modules might want to tackle) for which Chimera's basic entity/attribute model is simply not a good fit. If the entity model isn't a good fit, &lt;u&gt;do not use&lt;/u&gt; Chimera. Instead, find (or write) an Arachne module that defines a data modeling abstraction better suited for the task at hand.</p> <p>Examples of applications that might not be a good fit for Chimera include:</p> <ul> <li>Extremely sparse or &quot;wide&quot; data</li> <li>Dynamic data which cannot have pre-defined attributes or structure</li> <li>Unstructured heterogeneous data (such as large binary or sampling data)</li> <li>Data that cannot be indexed and requires distributed or streaming data processing to handle effectively</li> </ul> <h3 id=modeling-nan>Modeling</h3> <p>The data model for an Arachne application is, like everything else, data in the Configuration. Chimera defines a set of DSL forms that application authors can use to define data models programmatically, and of course modules can also read, write and modify these definitions as part of their normal configuration process.</p> <p>Note: The configuration schema, including the schema for the data model, is <em>itself</em> defined using Chimera. This requires some special bootstrapping in the core module. It also implies that Arachne core has a dependency on Chimera. This does not mean that modules are required to use Chimera or that Chimera has some special status relative to other conceivable data models; it just means that it is a good fit for modeling the kind of data that needs to be stored in the configuration.</p> <h4 id=modeling-entity-types-nan>Modeling: Entity Types</h4> <p><em>Entity types</em> are entities that define the structure and content for a <em>domain entity</em>. Entity types specify a set of optional and required <em>attributes</em> that entities of that type must have.</p> <p>Entity types may have one or more supertypes. Semantically, supertypes imply that any entity which is an instance of the subtype is also an instance of the supertype. Therefore, the set of attributes that are valid or required for an entity are the attributes of its types and all ancestor types.</p> <p>Entity types define only data structures. They are not objects or classes; they do not define methods or behaviors.</p> <p>In addition to defining the structure of entities themselves, entity types can have additional config attributes that serve as implementation-specific hints. For example, an entity type could have an attribute to override the name of the SQL table used for persistence. This config attribute would be defined and used by the SQL module, not by Chimera itself.</p> <p>The basic attributes of the entity type, as defined by Chimera, are:</p> <ul> <li>The name of the type (as a namespace-qualified keyword)</li> <li>Any supertypes it may have</li> <li>What attributes can be applied to entities of this type</li> </ul> <h4 id=attribute-definitions-nan>Attribute Definitions</h4> <p>Attribute Definition entities define what types of values can be associated with an entity. They specify:</p> <ol> <li>The name of the attribute (as a namespace-qualified keyword)</li> <li>The min and max cardinality of an attribute (thereby specifying whether it is required or optional)</li> <li>The type of allowed values (see the section on <em>Value Types</em> below)</li> <li>Whether the attribute is a <em>key</em>. The values of a key attribute are expected to be globally unique, guaranteed to be present, and serve as a way to find specific entities, no matter what the underlying storage mechanism.</li> <li>Whether the attribute is <em>indexed</em>. This is primarily a hint to the underlying database implementation.</li> </ol> <p>Like entity types, attribute definitions may have any number of additional attributes, to modify behavior in an implementation-specific way.</p> <h5 id=value-types-nan>Value Types</h5> <p>The value of an attribute may be one of three types:</p> <ol> <li><p>A <strong>reference</strong> is a value that is itself an entity. The attribute must specify the entity type of the target entity.</p></li> <li><p>A <strong>component</strong> is a reference, with the added semantic implication that the value entity is a logical &quot;part&quot; of the parent entity. It will be retrieved automatically, along with the parent, and will also be deleted/retracted along with the parent entity.</p></li> <li><p>A <strong>primitive</strong> is a simple, atomic value. Primitives may be one of several defined types, which map more or less directly to primitive types on the JVM:</p> <ul> <li>Boolean (JVM <code>java.lang.Boolean</code>)</li> <li>String (JVM <code>java.lang.String</code>)</li> <li>Keyword (Clojure <code>clojure.lang.Keyword</code>)</li> <li>64 bit integer (JVM <code>java.lang.Long</code>)</li> <li>64 bit floating point decimal (JVM <code>java.lang.Double</code>)</li> <li>Arbitrary precision integer (JVM <code>java.math.BigInteger</code>)</li> <li>Arbitrary precision decimal (JVM <code>java.math.BigDecimal</code>)</li> <li>Instant (absolute time with millisecond resolution) (JVM <code>java.util.Date</code>)</li> <li>UUID (JVM <code>java.util.UUID</code>)</li> <li>Bytes (JVM byte array). Since not all storages support binary data, and might need to serialize it with base64, this should be fairly small.</li> </ul> <p>This set of primitives represent a reasonable common denominator that is supportable on most target databases. Note that the set is not closed: modules can specify new primitive types that are logically &quot;subtypes&quot; of the generic primitives. Entirely new types can also be defined (with the caveat that they will only work with adapters for which an implementation has been defined.)</p></li> </ol> <h4 id=validation-nan>Validation</h4> <p>All attribute names are namespace-qualified keywords. If there are specs registered using those keywords, they can be used to validate the corresponding values.</p> <p>Clojure requires that a namespace be loaded before the specs defined in it are globally registered. To ensure that all relevant specs are loaded before an application runs, Chimera provides config attributes that specify namespaces containing specs. Arachne will ensure that these namespaces are loaded first, so module authors can ensure that their specs are loaded before they are needed.</p> <p>Chimera also provides a <code>generate-spec</code> operation which programmatically builds a spec for a given entity type, that can validate a full entity map of that type.</p> <h4 id=schema--migration-operations-nan>Schema &amp; Migration Operations</h4> <p>In order for data persistence to actually work, the schema of a particular database instance (at least, for those that have schema) needs to be compatible with the application's data model, as defined by Chimera's entity types and attributes.</p> <p>See <a href="adr-016-db-migrations.md">ADR-16</a> for an in-depth discussion of database migrations work, and the ramifications for how a Chimera data model is declared in the configuration.</p> <h3 id=entity-manipulation-nan>Entity Manipulation</h3> <p>The previous section discussed the data <em>model</em>, and how to define the general shape and structure of entities in an application. Entity <em>manipulation</em> refers to how the operations available to create, read, update, delete specific <em>instances</em> of those entities.</p> <h4 id=data-representation-nan>Data Representation</h4> <p>Domain entities are represented, in application code, as simple Clojure maps. In their function as Chimera entities, they are pure data; not objects. They are not required to support any additional protocols.</p> <p>Entity keys are restricted to being namespace-qualified keywords, which correspond with the attribute names defined in configuration (see <em>Attribute Definitions</em> above). Other keys will be ignored in Chimera's operations. Values may be any Clojure value, subject to spec validation before certain operations.</p> <p>Cardinality-many attributes <em>must</em> use a Clojure sequence, even if there is only one value.</p> <p>Reference values are represented in one of two ways; as a nested map, or as a <em>lookup reference</em>.</p> <p>Nested maps are straightforward. For example:</p> <pre><code>{:myapp.person/id 123 :myapp.person/name &quot;Bill&quot; :myapp.person/friends [{:myapp.person/id 42 :myapp.person/name &quot;Joe&quot;}]} </code></pre> <p>Lookup references are special values that identify an attribute (which must be a key) and value to indicate the target reference. Chimera provides a tagged literal specifially for lookup references.</p> <pre><code>{:myapp.person/id 123 :myapp.person/name &quot;Bill&quot; :myapp.person/friends [#chimera.key[:myapp.person/id 42]]} </code></pre> <p>All Chimera operations that return data should use one of these representations.</p> <p>Both representations are largely equivalent, but there is an important note about passing nested maps to persistence operations: the intended semantics for any nested maps must be the same as the parent map. For example, you cannot call <code>create</code> and expect the top-level entity to be created while the nested entity is updated.</p> <p>Entities do <em>not</em> need to explicitly declare their entity type. Types may be derived from inspecting the set of keys and comparing it to the Entity Types defined in the configuration.</p> <h4 id=persistence-operations-nan>Persistence Operations</h4> <p>The following basic operations are defined:</p> <ul> <li><code>get</code> - Given an attribute name and value, return a set of matching entity maps from the database. Results are not guaranteed to be found unless the attribute is indexed. Results may be truncated if there are more than can be efficiently returned.</li> <li><code>create</code> - Given a full entity map, transactionally store it in the database. Adapters <em>may</em> throw an error if an entity with the same key attribute and value already exists.</li> <li><code>update</code> - Given a map of attributes and values update each of the attributes provided attributes to have new values. The map must contain at least one key attribute. Also takes a set of attribute names which will be deleted/retracted from the entity. Adapters <em>may</em> throw an error if no entity exists for the given key.</li> <li><code>delete</code> - Given a key attribute and a value, remove the entity and all its attributes and components.</li> </ul> <p>All these operations should be transactional if possible. Adapters which cannot provide transactional behavior for these operations should note this fact clearly in their documentation, so their users do not make false assumptions about the integrity of their systems.</p> <p>Each of these operations has its own protocol which may be required by modules, or satisfied by adapters à la carte. Thus, a module that does not require the full set of operations can still work with an adapter, as long as it satisfies the operations that it <em>does</em> need.</p> <p>This set of operations is not exhaustive; other modules and adapters are free to extend Chimera and define additional operations, with different or stricter semantics. These operations are those that it is possible to implement consistently, in a reasonably performant way, against a &quot;broad enough&quot; set of very different types of databases.</p> <p>To make it possible for them to be composed more flexibly, operations are expressed as data, not as direct methods.</p> <h4 id=capability-model-nan>Capability Model</h4> <p>Adapters must specify a list of what operations they support. Modules should validate this list at runtime, to ensure the adapter works with the operations that they require.</p> <p>In addition to specifying whether an operation is supported or not, adapters must specify whether they support the operation idempotently and/or transactionally.</p> <h2 id=status-nan>Status</h2> <p>PROPOSED</p> <h2 id=consequences-nan>Consequences</h2> <ul> <li>Users and modules can define the shape and structure of their domain data in a way that is independent of any particular database or type of database.</li> <li>Modules can perform basic data persistence tasks in a database-agnostic way.</li> <li>Modules will be restricted to a severely limited subset of data persistence functionality, relative to using any database natively.</li> <li>The common data persistence layer is optional, and can be easily bypassed when it is not a good fit.</li> <li>The set of data persistence operations is open for extension.</li> <li>Because spec-able namespaced keywords are used pervasively, it will be straightforward to leverage Spec heavily for validation, testing, and seed data generation.</li> </ul> <h1 id=architecture-decision-record-database-migrations>Architecture Decision Record: Database Migrations</h1> <h2 id=context-nan>Context</h2> <p>In general, Arachne's philosophy embraces the concepts of immutability and reproducibility; rather than <em>changing</em> something, replace it with something new. Usually, this simplifies the mental model and reduces the number of variables, reducing the ways in which things can go wrong.</p> <p>But there is one area where this approach just can't work: administering changes to a production database. Databases must have a stable existence across time. You can't throw away all your data every time you want to make a change.</p> <p>And yet, some changes in the database do need to happen. Data models change. New fields are added. Entity relationships are refactored.</p> <p>The challenge is to provide a way to provide measured, safe, reproducible change across time which is <em>also</em> compatible with Arachne's target of defining and describing all relevant parts of an application (including it's data model (and therefore schema)) in a configuration.</p> <p>Compounding the challenge is the need to build a system that can define concrete schema for different types of databases, based on a common data model (such as Chimera's, as described in <a href="adr-015-data-abstraction-model.md">ADR-15</a>.)</p> <h3 id=prior-art-nan>Prior Art</h3> <p>Several systems to do this already exist. The best known is probably Rails' <a href="http://guides.rubyonrails.org/active_record_migrations.html">Active Record Migrations</a>, which is oriented around making schema changes to a relational database.</p> <p>Another solution of interest is <a href="http://www.liquibase.org">Liquibase</a>, a system which reifies database changes as data and explicitly applies them to a relation database.</p> <h3 id=scenarios-nan>Scenarios</h3> <p>There are a variety of &quot;user stories&quot; to accomodate. Some examples include:</p> <ol> <li>You are a new developer on a project, and want to create a local database that will work with the current HEAD of the codebase, for local development.</li> <li>You are responsible for the production deployment of your project, and your team has a new software version ready to go, but it requires some new fields to be added to the database before the new code will run.</li> <li>You want to set up a staging environment that is an exact mirror of your current production system.</li> <li>You and a fellow developer are merging your branches for different features. You both made different changes to the data model, and you need to be sure they are compatible after the merge.</li> <li>You recognize that you made a mistake earlier in development, and stored a currency value as a floating point number. You need to create a new column in the database which uses a fixed-point type, and copy over all the existing values, using rounding logic that you've agreed on with domain experts.</li> </ol> <h2 id=decision-nan>Decision</h2> <p>Chimera will explicitly define the concept of a migration, and reify migrations as entities in the configuration.</p> <p>A migration represents an atomic set of changes to the schema of a database. For any given database instance, either a migration has logically been applied, or it hasn't. Migrations have unique IDs, expressed as namespace-qualified keywords.</p> <p>Every migration has one or more &quot;parent&quot; migrations (except for a single, special &quot;initial&quot; migration, which has no parent). A migration may not be applied to a database unless all of its parents have already been applied.</p> <p>Migrations are also have a <em>signature</em>. The signature is an MD5 checksum of the <em>actual content</em> of the migration as it is applied to the database (whether that be txdata for Datomic, a string for SQL DDL, a JSON string, etc.) This is used to ensure that a migration is not &quot;changed&quot; after it has already been applied to some persistent database.</p> <p>Adapters are responsible for exposing an implementation of migrations (and accompanying config DSL) that is appropriate for the database type.</p> <p>Chimera Adapters must additionally satisfy two runtime operations:</p> <ul> <li><code>has-migration?</code> - takes ID and signature of a particular migration, and returns true if the migration has been successfully applied to the database. This implies that databases must be &quot;migration aware&quot; and store the IDs/signatures of migrations that have already been applied.</li> <li><code>migrate</code> - given a specific migration, run the migration and record that the migration has been applied.</li> </ul> <h3 id=migration-types-nan>Migration Types</h3> <p>There are four basic types of migrations.</p> <ol> <li><strong>Native migrations</strong>. These are instances of the migration type directly implemented by a database adapter, and are specific to the type of DB being used. For example, a native migration against a SQL database would be implemented (primarily) via a SQL string. A native migration can only be used by adapters of the appropriate type.</li> <li><strong>Chimera migrations</strong>. These define migrations using Chimera's entity/attribute data model. They are abstract, and should work against multiple different types of adapters. Chimera migrations should be supported by all Chimera adapters.</li> <li><strong>Sentinel migrations</strong>. These are used to coordinate manual changes to an existing database with the code that requires them. They will always fail to automatically apply to an existing database: the database admin must add the migration record explicitly after they perform the manual migration task. <em>(Note, actually implementing these can be deferred until if or when they are needed)</em>.</li> </ol> <h3 id=structure--usage-nan>Structure &amp; Usage</h3> <p>Because migrations may have one or more parents, migrations form a directed acyclic graph.</p> <p>This is appropriate, and combines well with Arachne's composability model. A module may define a sequence of migrations that build up a data model, and extending modules can branch from any point to build their own data model that shares structure with it. Modules may also depend upon a chain of migrations specified in two dependent modules, to indicate that it requires both of them.</p> <p>In the configuration, a Chimera <strong>database component</strong> may depend on any number of migration components. These migrations, and all their ancestors, form a &quot;database definition&quot;, and represent the complete schema of a concrete database instance (as far as Chimera is concerned.)</p> <p>When a database component is started and connects to the underlying data store, it verifies that all the specifies migrations have been applied. If they have not, it fails to start. This guarantees the safety of an Arachne system; a given application simply will not start if it is not compatible with the specified database.</p> <h5 id=parallel-migrations-nan>Parallel Migrations</h5> <p>This does create an opportunity for problems: if two migrations which have no dependency relatinship (&quot;parallel migrations&quot;) have operations that are incompatible, or would yield different results depending on the order in which they are applied, then these operations &quot;conflict&quot; and applying them to a database could result in errors or non-deterministic behavior.</p> <p>If the parallel migrations are both Chimera migrations, then Arachne is aware of their internal structure and can detect the conflict and refuse to start or run the migrations, before it actually touches the database.</p> <p>Unfortunately, Arachne cannot detect conflicting parallel migrations for other migration types. It is the responsibility of application developers to ensure that parallel migrations are logically isolate and can coexist in the same database without conflict.</p> <p>Therefore, it is advisable in general for public modules to only use Chimera migrations. In addition to making them as broadly compatible as possible, and will also make it more tractable for application authors to avoid conflicting parallel migrations, since they only have to worry about those that they themselves create.</p> <h3 id=chimera-migrations--entity-types-nan>Chimera Migrations &amp; Entity Types</h3> <p>One drawback of using Chimera migrations is that you cannot see a full entity type defined in one place, just from reading a config DSL script. This cannot be avoided: in a real, living application, entities are defined over time, in many different migrations as the application grows, not all at once. Each Chimera migration contains only a fragment of the full data model.</p> <p>However, this poses a usability problem; both for developers, and for machine consumption. There are many reasons for developers or modules to view or query the entity type model as a &quot;point in time&quot; snapshot, rather than just a series of incremental changes.</p> <p>To support this use case, the Chimera module creates a flat entity type model for each database by &quot;rolling up&quot; the individual Chimera entity definition forms into a single, full data structure graph. This &quot;canonical entity model&quot; can then be used to render schema diagrams for users, or be queried by other modules.</p> <h3 id=applying-migrations-nan>Applying Migrations</h3> <p>When and how to invoke an Adapter's <code>migrate</code> function is not defined, since different teams will wish to do it in different ways.</p> <p>Some possibilities include:</p> <ol> <li>The application calls &quot;migrate&quot; every time it is started (this is only advisable if the database has excellent support for transactional and atomic migrations.) In this scenario, developers only need to worry about deploying the code.</li> <li>The devops team can manually invoke the &quot;migrate&quot; function for each new configuration, prior to deployment.</li> <li>In a continuous-deployment setup, a CI server could run a battery of tests against a clone of the production database and invoke &quot;migrate&quot; automatically if they pass.</li> <li>The development team can inspect the set of migrations and generate a set of native SQL or txdata statements for handoff to a dedicated DBA team for review and commit prior to deployment.</li> </ol> <h3 id=databases-without-migrations-nan>Databases without migrations</h3> <p>Not every application wants to use Chimera's migration system. Some situations where migrations may not be a good fit include:</p> <ul> <li>You prefer to manage your own database schema.</li> <li>You are working with an existing database that predates Arachne.</li> <li>You need to work with a database administered by a separate team.</li> </ul> <p>However, you still may wish to utilize Chimera's entity model, and leverage modules that define Chimera migrations.</p> <p>To support this, Chimera allows you to (in the configuration) designate a database component as &quot;<strong>assert-only</strong>&quot;. Assert-only databases never have migrations applied, and they do not require the database to track any concept of migrations. Instead, they inspect the Chimera entity model (after rolling up all declared migrations) and assert that the database <em>already</em> has compatible schema installed. If it does, everything starts up as normal; if it does not, the component fails to start.</p> <p>Of course, the schema that Chimera expects most likely will not be an exact match for what is present in the database. To accomodate this, Chimera adapters defines a set of <em>override</em> configuration entities (and accompanying DSL). Users can apply these overrides to change the behavior of the mappings that Chimera uses to query and store data.</p> <p>Note that Chimera Overrides are incompatible with actually running migrations: they can be used only on an &quot;assert-only&quot; database.</p> <h3 id=migration-rollback-nan>Migration Rollback</h3> <p>Generalized rollback of migrations is intractable, given the variety of databases Chimera intends to support. Use one of the following strategies instead:</p> <ul> <li>For development and testing, be constantly creating and throwing away new databases.</li> <li>Back up your database before running a migration</li> <li>If you can't afford the downtime or data loss associated with restoring a backup, manually revert the changes from the unwanted migration.</li> </ul> <h2 id=status-nan>Status</h2> <p>PROPOSED</p> <h2 id=consequences-nan>Consequences</h2> <ul> <li>Users can define a data model in their configuration</li> <li>The data model can be automatically reflected in the database</li> <li>Data model changes are explicitly modeled across time</li> <li>All migrations, entity types and schema elements are represented in an Arachne app's configuration</li> <li>Given the same configuration, a database built using migrations can be reliably reproduced.</li> <li>A configuration using migrations will contain an entire, perfectly reproducible history of the database.</li> <li>Migrations are optional, and Chimera's data model can be used against existing databases</li> </ul> <h1 id=architecture-decision-record-simplification-of-chimera-model>Architecture Decision Record: Simplification of Chimera Model</h1> <p>Note: this ADR supersedes some aspects of <a href="adr-015-data-abstraction-model.md">ADR-15</a> and <a href="adr-016-db-migrations.md">ADR-16</a>.</p> <h2 id=context-nan>Context</h2> <p>The Chimera data model (as described in ADR-15 and ADR-16) includes the concepts of <em>entity types</em> in the domain data model: a defined entity type may have supertypes, and inherits all the attributes of a given supertype</p> <p>This is quite expressive, and is a good fit for certain types of data stores (such as Datomic, graph databases, and some object stores.) It makes it possible to compose types, and re-use attributes effectively.</p> <p>However, it leads to a number of conceptual problems, as well as implementation complexities. These issues include but are not limited to:</p> <ul> <li>There is a desire for some types to be &quot;abstract&quot;, in that they exist purely to be extended and are not intented to be reified in the target database (e.g, as a table.) In the current model it is ambiguous whether this is the case or not.</li> <li>A singe <code>extend-type</code> migration operation may need to create multiple columns in multiple tables, which some databases do not support transactionally.</li> <li>When doing a lookup by attribute that exists in multiple types, it is ambiguous which type is intended.</li> <li>In a SQL database, how to best model an extended type becomes ambiguous: copying the column leads to &quot;denormalization&quot;, which might not be desired. On the other hand, creating a separate table for the shared columns leads to more complex queries with more joins.</li> </ul> <p>All of these issues can be resolved or worked around. But they add a variable amount of complexity cost to every Chimera adapter, and create a domain with large amounts of ambigous behavior that must be resolved (and which might not be discovered until writing a particular adapter.)</p> <h2 id=decision-nan>Decision</h2> <p>The concept of type extension and attribute inheritance does not provide benefits proportional to the cost.</p> <p>We will remove all concept of supertypes, subtypes and attribute inheritance from Chimera's data model.</p> <p>Chimera's data model will remain &quot;flat&quot;. In order to achieve attribute reuse for data stores for which that is idiomatic (such as Datomic), multiple Chimera attributes can be mapped to a single DB-level attribute in the adapter mapping metadata.</p> <h2 id=status-nan>Status</h2> <p>PROPOSED</p> <h2 id=consequences-nan>Consequences</h2> <ul> <li>Adapters will be significantly easier to implement.</li> <li>An attribute will need to be repeated if it is present on different domain entity types, even if it is semantically similar.</li> <li>Users may need to explicitly map multiple Chimera attributes back to the same underlying DB attr/column if they want to maintain an idiomatic data model for their database.</li> </ul> </div> </div> </body> </html> <|start_filename|>examples/export-2.html<|end_filename|> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>ADR Documents</title> <style type="text/css"> html { color: #333; background: #fff; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; text-rendering: optimizelegibility; } /* 如果你的项目仅支持 IE9+ | Chrome | Firefox 等,推荐在 <html> 中添加 .borderbox 这个 class */ html.borderbox *, html.borderbox *:before, html.borderbox *:after { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } /* 内外边距通常让各个浏览器样式的表现位置不同 */ body, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, code, form, fieldset, legend, input, textarea, p, blockquote, th, td, hr, button, article, aside, details, figcaption, figure, footer, header, menu, nav, section { margin: 0; padding: 0; } /* 重设 HTML5 标签, IE 需要在 js 中 createElement(TAG) */ article, aside, details, figcaption, figure, footer, header, menu, nav, section { display: block; } /* HTML5 媒体文件跟 img 保持一致 */ audio, canvas, video { display: inline-block; } /* 要注意表单元素并不继承父级 font 的问题 */ body, button, input, select, textarea { font: 300 1em/1.8 PingFang SC, Lantinghei SC, Microsoft Yahei, Hiragino Sans GB, Microsoft Sans Serif, WenQuanYi Micro Hei, sans-serif; } button::-moz-focus-inner, input::-moz-focus-inner { padding: 0; border: 0; } /* 去掉各Table cell 的边距并让其边重合 */ table { border-collapse: collapse; border-spacing: 0; } /* 去除默认边框 */ fieldset, img { border: 0; } /* 块/段落引用 */ blockquote { position: relative; color: #999; font-weight: 400; border-left: 1px solid #1abc9c; padding-left: 1em; margin: 1em 3em 1em 2em; } @media only screen and ( max-width: 640px ) { blockquote { margin: 1em 0; } } /* Firefox 以外,元素没有下划线,需添加 */ acronym, abbr { border-bottom: 1px dotted; font-variant: normal; } /* 添加鼠标问号,进一步确保应用的语义是正确的(要知道,交互他们也有洁癖,如果你不去掉,那得多花点口舌) */ abbr { cursor: help; } /* 一致的 del 样式 */ del { text-decoration: line-through; } address, caption, cite, code, dfn, em, th, var { font-style: normal; font-weight: 400; } /* 去掉列表前的标识, li 会继承,大部分网站通常用列表来很多内容,所以应该当去 */ ul, ol { list-style: none; } /* 对齐是排版最重要的因素, 别让什么都居中 */ caption, th { text-align: left; } q:before, q:after { content: ''; } /* 统一上标和下标 */ sub, sup { font-size: 75%; line-height: 0; position: relative; } :root sub, :root sup { vertical-align: baseline; /* for ie9 and other modern browsers */ } sup { top: -0.5em; } sub { bottom: -0.25em; } /* 让链接在 hover 状态下显示下划线 */ a { color: #1abc9c; } a:hover { text-decoration: underline; } .typo a { border-bottom: 1px solid #1abc9c; } .typo a:hover { border-bottom-color: #555; color: #555; text-decoration: none; } /* 默认不显示下划线,保持页面简洁 */ ins, a { text-decoration: none; } /* 专名号:虽然 u 已经重回 html5 Draft,但在所有浏览器中都是可以使用的, * 要做到更好,向后兼容的话,添加 class="typo-u" 来显示专名号 * 关于 <u> 标签:http://www.whatwg.org/specs/web-apps/current-work/multipage/text-level-semantics.html#the-u-element * 被放弃的是 4,之前一直搞错 http://www.w3.org/TR/html401/appendix/changes.html#idx-deprecated * 一篇关于 <u> 标签的很好文章:http://html5doctor.com/u-element/ */ u, .typo-u { text-decoration: underline; } /* 标记,类似于手写的荧光笔的作用 */ mark { background: #fffdd1; border-bottom: 1px solid #ffedce; padding: 2px; margin: 0 5px; } /* 代码片断 */ pre, code, pre tt { font-family: Courier, 'Courier New', monospace; } pre { background: #f8f8f8; border: 1px solid #ddd; padding: 1em 1.5em; display: block; -webkit-overflow-scrolling: touch; } /* 一致化 horizontal rule */ hr { border: none; border-bottom: 1px solid #cfcfcf; margin-bottom: 0.8em; height: 10px; } /* 底部印刷体、版本等标记 */ small, .typo-small, /* 图片说明 */ figcaption { font-size: 0.9em; color: #888; } strong, b { font-weight: bold; color: #000; } /* 可拖动文件添加拖动手势 */ [draggable] { cursor: move; } .clearfix:before, .clearfix:after { content: ""; display: table; } .clearfix:after { clear: both; } .clearfix { zoom: 1; } /* 强制文本换行 */ .textwrap, .textwrap td, .textwrap th { word-wrap: break-word; word-break: break-all; } .textwrap-table { table-layout: fixed; } /* 提供 serif 版本的字体设置: iOS 下中文自动 fallback 到 sans-serif */ .serif { font-family: Palatino, Optima, Georgia, serif; } /* 保证块/段落之间的空白隔行 */ .typo p, .typo pre, .typo ul, .typo ol, .typo dl, .typo form, .typo hr, .typo table, .typo-p, .typo-pre, .typo-ul, .typo-ol, .typo-dl, .typo-form, .typo-hr, .typo-table, blockquote { margin-bottom: 1.2em } h1, h2, h3, h4, h5, h6 { font-family: PingFang SC, Verdana, Helvetica Neue, Microsoft Yahei, Hiragino Sans GB, Microsoft Sans Serif, WenQuanYi Micro Hei, sans-serif; font-weight: 100; color: #000; line-height: 1.35; } /* 标题应该更贴紧内容,并与其他块区分,margin 值要相应做优化 */ .typo h1, .typo h2, .typo h3, .typo h4, .typo h5, .typo h6, .typo-h1, .typo-h2, .typo-h3, .typo-h4, .typo-h5, .typo-h6 { margin-top: 1.2em; margin-bottom: 0.6em; line-height: 1.35; } .typo h1, .typo-h1 { font-size: 2em; } .typo h2, .typo-h2 { font-size: 1.8em; } .typo h3, .typo-h3 { font-size: 1.6em; } .typo h4, .typo-h4 { font-size: 1.4em; } .typo h5, .typo h6, .typo-h5, .typo-h6 { font-size: 1.2em; } /* 在文章中,应该还原 ul 和 ol 的样式 */ .typo ul, .typo-ul { margin-left: 1.3em; list-style: disc; } .typo ol, .typo-ol { list-style: decimal; margin-left: 1.9em; } .typo li ul, .typo li ol, .typo-ul ul, .typo-ul ol, .typo-ol ul, .typo-ol ol { margin-bottom: 0.8em; margin-left: 2em; } .typo li ul, .typo-ul ul, .typo-ol ul { list-style: circle; } /* 同 ul/ol,在文章中应用 table 基本格式 */ .typo table th, .typo table td, .typo-table th, .typo-table td, .typo table caption { border: 1px solid #ddd; padding: 0.5em 1em; color: #666; } .typo table th, .typo-table th { background: #fbfbfb; } .typo table thead th, .typo-table thead th { background: #f1f1f1; } .typo table caption { border-bottom: none; } /* 去除 webkit 中 input 和 textarea 的默认样式 */ .typo-input, .typo-textarea { -webkit-appearance: none; border-radius: 0; } .typo-em, .typo em, legend, caption { color: #000; font-weight: inherit; } /* 着重号,只能在少量(少于100个字符)且全是全角字符的情况下使用 */ .typo-em { position: relative; } .typo-em:after { position: absolute; top: 0.65em; left: 0; width: 100%; overflow: hidden; white-space: nowrap; content: "・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・"; } /* Responsive images */ .typo img { max-width: 100%; } header { position: fixed; z-index: 2; z-index: 1024; top: 0; left: 0; width: 100%; height: 60px; background-color: #fff; box-shadow: 0 0 4px rgba(0,0,0,0.5); text-transform: uppercase; font-size: 20px } header .logo { display: inline-block; padding-left: 37px; float: left; text-decoration: none; color: #333; line-height: 60px; background-repeat: no-repeat; background-position: left center } header nav { text-align: right; font-size: 0 } header nav ul { display: inline-block; padding: 0; list-style: none } header nav li { display: inline } header nav a { display: inline-block; padding: 0 15px; color: #333; text-decoration: none; font-size: 20px; line-height: 60px; transition: opacity .2s } header nav a.current { color: #9600ff } header nav a:hover { opacity: .75 } .content { padding-top: 100px; } #toc { width: 30%; max-width: 420px; max-height: 85%; float: left; margin: 25px 0px 20px 0px; position: fixed !important; overflow: auto; -webkit-overflow-scrolling: touch; overflow-scrolling: touch; box-sizing: border-box; z-index: 1; left: 0; top: 40px; bottom: 0; padding: 20px; } #toc > ul { list-style: none; padding: 20px 40px 0 40px; margin: 0; border-bottom: 1px solid #eee } #toc > ul > li > ul { padding-left: 40px; } #toc a { display: block; padding: 10px 0; text-decoration: none; color: #333; border-bottom: 1px solid #eee; transition: opacity .2s } #toc a.current { color: #9600ff } #toc a:hover { opacity: .75 } .main { width: 70%; max-width: 980px; float: left; padding-left: 30%; top: 160px; position: relative; } </style> </head> <body> <header> <div class="container"> <a href="https://github.com/phodal/adr" class="logo">ADR</a> <nav> <ul> <li><a href="https://github.com/phodal/adr">GitHub</a></li> </ul> </nav> </div> </header> <div class="content"> <div id="toc" class="tocify"> <ul> <li><a href="#1-record-architecture-decisions">1. Record architecture decisions</a> <ul> <li><a href="#status">Status</a></li> <li><a href="#context">Context</a></li> <li><a href="#decision">Decision</a></li> <li><a href="#consequences">Consequences</a></li> </ul></li> <li><a href="#2-%E5%9B%A2%E9%98%9F%E4%B8%AD%E7%9A%84%E5%AF%86%E7%A0%81%E7%AE%A1%E7%90%86">2. 团队中的密码管理</a> <ul> <li><a href="#status-1">Status</a></li> <li><a href="#context-1">Context</a></li> <li><a href="#decision-1">Decision</a></li> <li><a href="#consequences-1">Consequences</a></li> </ul></li> <li><a href="#3-%E4%BD%BF%E7%94%A8-ssh-key-%E6%9B%BF%E6%8D%A2%E7%94%A8%E6%88%B7%E5%90%8D%E5%AF%86%E7%A0%81%E6%96%B9%E5%BC%8F%E7%99%BB%E5%BD%95">3. 使用 ssh key 替换用户名密码方式登录</a> <ul> <li><a href="#status-2">Status</a></li> <li><a href="#context-2">Context</a> <ul> <li><a href="#refs">Refs:</a></li> </ul></li> <li><a href="#decision-2">Decision</a></li> <li><a href="#consequences-2">Consequences</a></li> </ul></li> <li><a href="#4-ubuntu-vs-centos">4. Ubuntu vs CentOS</a> <ul> <li><a href="#status-3">Status</a></li> <li><a href="#context-3">Context</a></li> <li><a href="#decision-3">Decision</a></li> <li><a href="#consequences-3">Consequences</a></li> </ul></li> <li><a href="#5-%E4%BD%BF%E7%94%A8-slack-%E6%9B%BF%E4%BB%A3%E5%BE%AE%E4%BF%A1%E9%82%AE%E4%BB%B6%E5%92%8C%E7%9F%AD%E4%BF%A1">5. 使用 Slack 替代微信、邮件和短信</a> <ul> <li><a href="#status-4">Status</a></li> <li><a href="#context-4">Context</a></li> <li><a href="#decision-4">Decision</a> <ul> <li><a href="#slack-%E6%94%AF%E6%8C%81%E7%9A%84%E5%8A%9F%E8%83%BD">Slack 支持的功能</a></li> <li><a href="#%E7%A0%94%E5%8F%91%E9%83%A8%E9%A2%91%E9%81%93%E8%AE%BE%E8%AE%A1">研发部频道设计</a></li> <li><a href="#%E6%88%91%E4%BB%AC%E7%94%A8%E4%BA%86%E5%A6%82%E4%B8%8B%E7%AC%AC%E4%B8%89%E6%96%B9%E8%BD%AF%E4%BB%B6">我们用了如下第三方软件</a></li> <li><a href="#slack-vs-bearychat">Slack vs BearyChat</a></li> </ul></li> <li><a href="#consequences-4">Consequences</a></li> </ul></li> <li><a href="#6-%E4%BD%BF%E7%94%A8-git-%E6%9B%BF%E6%8D%A2-svn">6. 使用 Git 替换 SVN</a> <ul> <li><a href="#status-5">Status</a></li> <li><a href="#context-5">Context</a></li> <li><a href="#decision-5">Decision</a></li> <li><a href="#consequences-5">Consequences</a></li> </ul></li> <li><a href="#7-%E4%BD%BF%E7%94%A8-passpack-%E8%BF%9B%E8%A1%8C%E5%AF%86%E7%A0%81%E7%AE%A1%E7%90%86">7. 使用 PassPack 进行密码管理</a> <ul> <li><a href="#status-6">Status</a></li> <li><a href="#context-6">Context</a></li> <li><a href="#decision-6">Decision</a></li> <li><a href="#consequences-6">Consequences</a></li> </ul></li> <li><a href="#8-%E4%BD%BF%E7%94%A8%E5%A0%A1%E5%9E%92%E6%9C%BA%E5%8A%A0%E5%BC%BA%E6%9C%8D%E5%8A%A1%E5%99%A8%E5%AE%89%E5%85%A8">8. 使用堡垒机加强服务器安全</a> <ul> <li><a href="#status-7">Status</a></li> <li><a href="#context-7">Context</a></li> <li><a href="#decision-7">Decision</a></li> <li><a href="#consequences-7">Consequences</a></li> </ul></li> <li><a href="#9-%E7%BB%93%E6%9E%84%E5%8C%96-django-%E9%A1%B9%E7%9B%AE">9. 结构化 Django 项目</a> <ul> <li><a href="#status-8">Status</a></li> <li><a href="#context-8">Context</a></li> <li><a href="#decision-8">Decision</a></li> <li><a href="#consequences-8">Consequences</a></li> </ul></li> <li><a href="#10-git-%E5%9F%BA%E7%A1%80%E5%8F%8A%E9%A3%8E%E6%A0%BC%E6%8C%87%E5%8D%97">10. Git 基础及风格指南</a> <ul> <li><a href="#status-9">Status</a></li> <li><a href="#context-9">Context</a></li> <li><a href="#decision-9">Decision</a> <ul> <li><a href="#git-basics">git basics</a></li> <li><a href="#git-style-guide">git style guide</a> <ul> <li><a href="#branches">Branches</a></li> <li><a href="#commits">Commits</a></li> <li><a href="#messages">Messages</a></li> </ul></li> <li><a href="#refs">Refs</a></li> </ul></li> <li><a href="#consequences-9">Consequences</a></li> </ul></li> <li><a href="#11-apply-github-workflow-to-our-team">11. Apply Github workflow to our team</a> <ul> <li><a href="#status-10">Status</a></li> <li><a href="#context-10">Context</a></li> <li><a href="#decision-10">Decision</a> <ul> <li><a href="#github-workflow">Github workflow</a></li> </ul></li> <li><a href="#consequences-10">Consequences</a></li> </ul></li> <li><a href="#12-think-about-micro-service">12. Think about micro service</a> <ul> <li><a href="#status-11">Status</a></li> <li><a href="#context-11">Context</a></li> <li><a href="#decision-11">Decision</a></li> <li><a href="#consequences-11">Consequences</a></li> <li><a href="#refs-1">Refs</a> <ul> <li><a href="#why">Why</a></li> <li><a href="#how">How</a></li> <li><a href="#%E6%9C%8D%E5%8A%A1%E6%B3%A8%E5%86%8C">服务注册</a></li> <li><a href="#rest-api-vs-rpc">REST API vs RPC</a></li> </ul></li> </ul></li> <li><a href="#13-the-sense-of-done">13. The sense of Done</a> <ul> <li><a href="#status-12">Status</a></li> <li><a href="#context-12">Context</a></li> <li><a href="#decision-12">Decision</a></li> <li><a href="#consequences-12">Consequences</a></li> </ul></li> <li><a href="#14-how-to-restart-a-server">14. How to restart a server</a> <ul> <li><a href="#status-13">Status</a></li> <li><a href="#context-13">Context</a></li> <li><a href="#decision-13">Decision</a></li> <li><a href="#consequences-13">Consequences</a></li> </ul></li> <li><a href="#15-case-how-to-find-the-root-reason-of-high-load">15. Case: How to find the root reason of high load</a> <ul> <li><a href="#status-14">Status</a></li> <li><a href="#context-14">Context</a></li> <li><a href="#decision-14">Decision</a></li> <li><a href="#consequences-14">Consequences</a></li> </ul></li> <li><a href="#16-%E6%95%85%E9%9A%9C%E8%AE%B0%E5%BD%95%E6%8A%A5%E5%91%8A">16. 故障记录报告</a> <ul> <li><a href="#status-15">Status</a></li> <li><a href="#context-15">Context</a></li> <li><a href="#decision-15">Decision</a></li> <li><a href="#consequences-15">Consequences</a> <ul> <li><a href="#%E6%95%85%E9%9A%9C%E6%8A%A5%E5%91%8A%E6%A8%A1%E6%9D%BF">故障报告模板</a> <ul> <li><a href="#%E9%97%AE%E9%A2%98%E6%8F%8F%E8%BF%B0">问题描述</a></li> <li><a href="#%E6%97%B6%E9%97%B4%E7%BA%BF">时间线</a></li> <li><a href="#%E5%8E%9F%E5%9B%A0%E5%88%86%E6%9E%90">原因分析</a></li> <li><a href="#%E5%81%9A%E9%94%99%E7%9A%84%E4%BA%8B%E6%83%85">做错的事情</a></li> <li><a href="#%E5%81%9A%E5%AF%B9%E7%9A%84%E4%BA%8B%E6%83%85">做对的事情</a></li> <li><a href="#%E5%B0%86%E6%9D%A5%E5%A6%82%E4%BD%95%E9%81%BF%E5%85%8D%E6%AD%A4%E7%B1%BB%E4%BA%8B%E6%83%85%E5%86%8D%E6%AC%A1%E5%8F%91%E7%94%9F">将来如何避免此类事情再次发生</a></li> </ul></li> </ul></li> </ul></li> <li><a href="#17-incident-classify-and-recovery">17. Incident classify and recovery</a> <ul> <li><a href="#status-16">Status</a></li> <li><a href="#context-16">Context</a></li> <li><a href="#decision-16">Decision</a></li> <li><a href="#consequences-16">Consequences</a> <ul> <li><a href="#%E8%87%AA%E7%84%B6%E7%81%BE%E5%AE%B3">自然灾害</a></li> <li><a href="#%E6%9C%8D%E5%8A%A1%E8%BF%90%E8%90%A5%E5%95%86">服务运营商</a> <ul> <li><a href="#dns-%E8%A7%A3%E6%9E%90%E9%97%AE%E9%A2%98">DNS 解析问题</a></li> <li><a href="#aliyun-%E5%86%85%E9%83%A8%E9%97%AE%E9%A2%98">Aliyun 内部问题</a></li> <li><a href="#cdn-%E8%BF%90%E8%90%A5%E5%95%86">CDN 运营商</a></li> </ul></li> <li><a href="#%E5%A4%96%E9%83%A8%E4%BA%BA%E4%B8%BA">外部人为</a> <ul> <li><a href="#%E4%BA%BA%E4%B8%BA%E6%94%BB%E5%87%BB">人为攻击</a></li> <li><a href="#%E6%AD%A3%E5%B8%B8%E8%AF%B7%E6%B1%82">正常请求</a></li> </ul></li> <li><a href="#%E6%9E%B6%E6%9E%84%E5%86%85%E9%83%A8">架构内部</a> <ul> <li><a href="#%E6%95%B0%E6%8D%AE%E5%BA%93%E7%BA%A7%E6%95%85%E9%9A%9C">数据库级故障</a></li> <li><a href="#%E5%86%85%E9%83%A8%E7%BD%91%E7%BB%9C%E7%BA%A7%E5%88%AB">内部网络级别</a></li> <li><a href="#%E7%B3%BB%E7%BB%9F%E7%BA%A7%E5%88%AB%E6%95%85%E9%9A%9C">系统级别故障</a></li> <li><a href="#%E7%B3%BB%E7%BB%9F%E6%9C%8D%E5%8A%A1%E7%BA%A7%E5%88%AB%E6%95%85%E9%9A%9C">系统服务级别故障</a></li> <li><a href="#%E5%BA%94%E7%94%A8%E6%9C%8D%E5%8A%A1%E7%BA%A7%E5%88%AB%E6%95%85%E9%9A%9C">应用服务级别故障</a></li> <li><a href="#%E5%BA%94%E7%94%A8%E8%99%9A%E6%8B%9F%E7%8E%AF%E5%A2%83%E7%BA%A7%E5%88%AB%E6%95%85%E9%9A%9C">应用虚拟环境级别故障</a></li> <li><a href="#%E5%BA%94%E7%94%A8%E4%BB%A3%E7%A0%81%E7%BA%A7%E5%88%AB%E6%95%85%E9%9A%9C">应用代码级别故障</a></li> </ul></li> </ul></li> </ul></li> <li><a href="#18-ios-%E6%8C%81%E7%BB%AD%E5%8F%91%E5%B8%83">18. iOS 持续发布</a> <ul> <li><a href="#status-17">Status</a></li> <li><a href="#context-17">Context</a></li> <li><a href="#decision-17">Decision</a></li> <li><a href="#consequences-17">Consequences</a></li> </ul></li> <li><a href="#19-%E6%9C%8D%E5%8A%A1%E5%99%A8%E7%94%B3%E8%AF%B7%E4%B8%8E%E5%8D%87%E7%BA%A7---%E5%AE%B9%E9%87%8F%E8%AF%84%E4%BC%B0">19. 服务器申请与升级 - 容量评估</a> <ul> <li><a href="#status-18">Status</a></li> <li><a href="#context-18">Context</a></li> <li><a href="#decision-18">Decision</a></li> <li><a href="#consequences-18">Consequences</a></li> </ul></li> <li><a href="#20-%E6%97%A5%E5%BF%97%E7%AE%A1%E7%90%86">20. 日志管理</a> <ul> <li><a href="#status-19">Status</a></li> <li><a href="#context-19">Context</a></li> <li><a href="#decision-19">Decision</a></li> <li><a href="#consequences-19">Consequences</a></li> </ul></li> <li><a href="#21-redis-%E4%BD%BF%E7%94%A8%E6%8C%89%E4%B8%9A%E5%8A%A1%E5%88%86%E7%A6%BB%E5%B9%B6%E4%B8%8A%E4%BA%91">21. Redis 使用按业务分离并上云</a> <ul> <li><a href="#status-20">Status</a></li> <li><a href="#context-20">Context</a></li> <li><a href="#decision-20">Decision</a></li> <li><a href="#consequences-20">Consequences</a></li> </ul></li> <li><a href="#22-%E9%98%B2-ddos-%E6%94%BB%E5%87%BB">22. 防 DDOS 攻击</a> <ul> <li><a href="#status-21">Status</a></li> <li><a href="#context-21">Context</a></li> <li><a href="#decision-21">Decision</a></li> <li><a href="#consequences-21">Consequences</a></li> </ul></li> <li><a href="#23-%E5%BA%94%E7%94%A8%E6%80%A7%E8%83%BD%E7%9B%91%E6%8E%A7">23. 应用性能监控</a> <ul> <li><a href="#status-22">Status</a></li> <li><a href="#context-22">Context</a></li> <li><a href="#decision-22">Decision</a></li> <li><a href="#consequences-22">Consequences</a></li> </ul></li> <li><a href="#24-%E5%AE%9E%E6%97%B6%E9%94%99%E8%AF%AF%E8%B7%9F%E8%B8%AA">24. 实时错误跟踪</a> <ul> <li><a href="#status-23">Status</a></li> <li><a href="#context-23">Context</a></li> <li><a href="#decision-23">Decision</a> <ul> <li><a href="#%E4%BD%BF%E7%94%A8-sentry-%E5%AF%B9%E6%88%91%E4%BB%AC%E7%BA%BF%E4%B8%8A%E4%B8%BB%E8%A6%81%E4%B8%9A%E5%8A%A1%E5%81%9A%E5%BC%82%E5%B8%B8%E7%9B%91%E6%8E%A7">使用 Sentry 对我们线上主要业务做异常监控。</a></li> <li><a href="#%E8%A7%84%E8%8C%83%E5%8C%96%E5%BC%82%E5%B8%B8">规范化异常</a> <ul> <li><a href="#%E4%BD%BF%E7%94%A8%E5%BC%82%E5%B8%B8%E7%9A%84%E4%BC%98%E5%8A%BF">使用异常的优势</a></li> <li><a href="#%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86%E5%AE%9E%E8%B7%B5%E5%8E%9F%E5%88%99">异常处理实践原则</a></li> </ul></li> </ul></li> <li><a href="#consequences-23">Consequences</a></li> </ul></li> <li><a href="#25-%E6%8C%89-restful-%E9%A3%8E%E6%A0%BC%E8%AE%BE%E8%AE%A1%E6%9B%B4%E6%96%B0%E6%9C%8D%E5%8A%A1%E6%8E%A5%E5%8F%A3">25. 按 RESTful 风格设计更新服务接口</a> <ul> <li><a href="#status-24">Status</a></li> <li><a href="#context-24">Context</a></li> <li><a href="#decision-24">Decision</a></li> <li><a href="#consequences-24">Consequences</a></li> </ul></li> <li><a href="#26-%E6%96%87%E4%BB%B6%E6%9C%8D%E5%8A%A1%E4%B8%8E%E4%B8%9A%E5%8A%A1%E6%9C%8D%E5%8A%A1%E9%9A%94%E7%A6%BB">26. 文件服务与业务服务隔离</a> <ul> <li><a href="#status-25">Status</a></li> <li><a href="#context-25">Context</a></li> <li><a href="#decision-25">Decision</a></li> <li><a href="#consequences-25">Consequences</a></li> </ul></li> <li><a href="#27-%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97">27. 消息队列</a> <ul> <li><a href="#status-26">Status</a></li> <li><a href="#context-26">Context</a></li> <li><a href="#decision-26">Decision</a></li> <li><a href="#consequences-26">Consequences</a></li> </ul></li> <li><a href="#28-what-should-we-do-when-we-setup-a-new-server">28. What should we do when we setup a new server</a> <ul> <li><a href="#status-27">Status</a></li> <li><a href="#context-27">Context</a></li> <li><a href="#decision-27">Decision</a></li> <li><a href="#consequences-27">Consequences</a></li> </ul></li> <li><a href="#29-%E6%9C%AC%E5%9C%B0-hosts-%E7%AE%A1%E7%90%86">29. 本地 hosts 管理</a> <ul> <li><a href="#status-28">Status</a></li> <li><a href="#context-28">Context</a></li> <li><a href="#decision-28">Decision</a></li> <li><a href="#consequences-28">Consequences</a></li> </ul></li> <li><a href="#30-%E5%AE%B9%E9%87%8F%E8%AF%84%E4%BC%B0---%E5%AD%98%E5%82%A8">30. 容量评估 - 存储</a> <ul> <li><a href="#status-29">Status</a></li> <li><a href="#context-29">Context</a></li> <li><a href="#decision-29">Decision</a></li> <li><a href="#consequences-29">Consequences</a></li> </ul></li> <li><a href="#31-%E5%AE%B9%E9%87%8F%E8%AF%84%E4%BC%B0---%E5%86%85%E5%AD%98">31. 容量评估 - 内存</a> <ul> <li><a href="#status-30">Status</a></li> <li><a href="#context-30">Context</a></li> <li><a href="#decision-30">Decision</a></li> <li><a href="#consequences-30">Consequences</a></li> </ul></li> <li><a href="#32-tcp-%E9%95%BF%E8%BF%9E%E6%8E%A5%E9%AB%98%E5%8F%AF%E7%94%A8">32. TCP 长连接高可用</a> <ul> <li><a href="#status-31">Status</a></li> <li><a href="#context-31">Context</a></li> <li><a href="#decision-31">Decision</a></li> <li><a href="#consequences-31">Consequences</a></li> </ul></li> <li><a href="#33-%E5%AE%B9%E9%87%8F%E8%AF%84%E4%BC%B0---mysql">33. 容量评估 - MySQL</a> <ul> <li><a href="#status-32">Status</a></li> <li><a href="#context-32">Context</a></li> <li><a href="#decision-32">Decision</a> <ul> <li><a href="#%E5%92%8C-mysql-%E6%80%A7%E8%83%BD%E7%9B%B8%E5%85%B3%E7%9A%84%E5%87%A0%E4%B8%AA%E6%8C%87%E6%A0%87">和 MySQL 性能相关的几个指标</a></li> <li><a href="#%E5%BD%B1%E5%93%8D%E6%95%B0%E6%8D%AE%E5%BA%93%E6%80%A7%E8%83%BD%E7%9A%84%E5%9B%A0%E7%B4%A0%E5%8F%8A%E5%BA%94%E5%AF%B9%E6%96%B9%E5%BC%8F">影响数据库性能的因素及应对方式</a></li> </ul></li> <li><a href="#consequences-32">Consequences</a></li> </ul></li> <li><a href="#34-dns-%E7%AC%94%E8%AE%B0">34. DNS 笔记</a> <ul> <li><a href="#status-33">Status</a></li> <li><a href="#context-33">Context</a></li> <li><a href="#decision-33">Decision</a></li> <li><a href="#consequences-33">Consequences</a></li> </ul></li> <li><a href="#35-%E5%85%B3%E4%BA%8E%E7%81%BE%E9%9A%BE%E6%81%A2%E5%A4%8D">35. 关于灾难恢复</a> <ul> <li><a href="#status-34">Status</a></li> <li><a href="#context-34">Context</a> <ul> <li><a href="#%E5%9F%BA%E7%A1%80%E6%A6%82%E5%BF%B5">基础概念</a></li> <li><a href="#%E7%81%BE%E5%A4%87%E7%9A%84%E4%B8%A4%E9%A1%B9%E6%8C%87%E6%A0%87">灾备的两项指标</a></li> <li><a href="#%E4%B8%A4%E5%9C%B0%E4%B8%89%E4%B8%AD%E5%BF%83">两地三中心</a></li> </ul></li> <li><a href="#decision-34">Decision</a></li> <li><a href="#consequences-34">Consequences</a></li> </ul></li> <li><a href="#36-%E5%85%B3%E4%BA%8E-mysql-%E9%AB%98%E5%8F%AF%E7%94%A8">36. 关于 MySQL 高可用</a> <ul> <li><a href="#status-35">Status</a></li> <li><a href="#context-35">Context</a></li> <li><a href="#decision-35">Decision</a></li> <li><a href="#consequences-35">Consequences</a></li> </ul></li> <li><a href="#37-%E9%80%9A%E8%BF%87%E4%BB%A3%E7%90%86%E8%A7%A3%E5%86%B3%E7%99%BD%E5%90%8D%E5%8D%95%E9%97%AE%E9%A2%98">37. 通过代理解决白名单问题</a> <ul> <li><a href="#status-36">Status</a></li> <li><a href="#context-36">Context</a></li> <li><a href="#decision-36">Decision</a></li> <li><a href="#consequences-36">Consequences</a></li> </ul></li> <li><a href="#38-%E6%95%B0%E6%8D%AE%E8%84%B1%E6%95%8F">38. 数据脱敏</a> <ul> <li><a href="#status-37">Status</a></li> <li><a href="#context-37">Context</a></li> <li><a href="#decision-37">Decision</a></li> <li><a href="#consequences-37">Consequences</a></li> </ul></li> <li><a href="#39-%E7%A7%98%E9%92%A5%E7%AE%A1%E7%90%86">39. 秘钥管理</a> <ul> <li><a href="#status-38">Status</a></li> <li><a href="#context-38">Context</a></li> <li><a href="#decision-38">Decision</a></li> <li><a href="#consequences-38">Consequences</a></li> </ul></li> <li><a href="#40-agile---daily-standup-meeting">40. Agile - Daily standup meeting</a> <ul> <li><a href="#status-39">Status</a></li> <li><a href="#context-39">Context</a></li> <li><a href="#decision-39">Decision</a> <ul> <li><a href="#keynotes">Keynotes</a></li> </ul></li> <li><a href="#consequences-39">Consequences</a></li> </ul></li> <li><a href="#41-mysql-%E8%BF%81%E7%A7%BB-rds-%E6%80%BB%E7%BB%93">41. MySQL 迁移 RDS 总结</a> <ul> <li><a href="#status-40">Status</a></li> <li><a href="#context-40">Context</a></li> <li><a href="#decision-40">Decision</a></li> <li><a href="#consequences-40">Consequences</a></li> </ul></li> <li><a href="#42-agile---retrospective-meeting">42. Agile - Retrospective meeting</a> <ul> <li><a href="#status-41">Status</a></li> <li><a href="#context-41">Context</a></li> <li><a href="#decision-41">Decision</a> <ul> <li><a href="#description">Description</a></li> <li><a href="#preparation">Preparation</a></li> <li><a href="#process">Process</a></li> <li><a href="#notice">Notice</a></li> </ul></li> <li><a href="#consequences-41">Consequences</a></li> </ul></li> <li><a href="#43-%E6%94%AF%E6%8C%81%E8%BF%87%E6%BB%A4%E7%9A%84%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97">43. 支持过滤的消息队列</a> <ul> <li><a href="#status-42">Status</a></li> <li><a href="#context-42">Context</a></li> <li><a href="#decision-42">Decision</a></li> <li><a href="#consequences-42">Consequences</a></li> </ul></li> <li><a href="#44-%E6%B3%9B%E5%9F%9F%E5%90%8D%E8%A7%A3%E6%9E%90">44. 泛域名解析</a> <ul> <li><a href="#status-43">Status</a></li> <li><a href="#context-43">Context</a></li> <li><a href="#decision-43">Decision</a></li> <li><a href="#consequences-43">Consequences</a></li> </ul></li> </ul> </div> <div class="main typo"> <h1 id=1-record-architecture-decisions>1. Record architecture decisions</h1> <p>Date: 30/03/2017</p> <h2 id=status-0>Status</h2> <p>Accepted</p> <h2 id=context-0>Context</h2> <p>We need to record the architectural decisions made on this project.</p> <h2 id=decision-0>Decision</h2> <p>We will use Architecture Decision Records, as described by <NAME> in this article: <a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions</a></p> <p>Architecture Decisions, what are they ?: <a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html</a></p> <p>Architecture Decisions: Demystifying Architecture: <a href="https://www.utdallas.edu/~chung/SA/zz-Impreso-architecture_decisions-tyree-05.pdf">https://www.utdallas.edu/~chung/SA/zz-Impreso-architecture_decisions-tyree-05.pdf</a></p> <p>We will use adr-tools, as this file generated by <a href="https://github.com/npryce/adr-tools">https://github.com/npryce/adr-tools</a></p> <h2 id=consequences-0>Consequences</h2> <p>See <NAME>'s article, linked above.</p> <h1 id=2-团队中的密码管理>2. 团队中的密码管理</h1> <p>Date: 30/03/2017</p> <h2 id=status-1>Status</h2> <p>Accepted</p> <h2 id=context-1>Context</h2> <p><img src="files/password-manage.png" alt=""></p> <p>视频链接:<a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">http://v.youku.com/v_show/id_XMjk5ODQ3NzA3Mg==.html</a></p> <p>我们工作中使用的密码有 100 + 左右,其中包括 服务器,数据库,测试账号,第三方服务(阿里云,Dnspod,邮箱,等)</p> <p>我们所有的密码都是分散的管理着,每个人都自行对这 20 到 100 个密码进行管理,并且方式各种各样。</p> <p>当前存在以下问题:</p> <ol> <li>使用容易记但很不安全的密码,例如,<code>123456</code>;</li> <li>在每一个服务上使用相同的非安全密码;</li> <li>当团队成员有变动时,密码没有改变;</li> <li>无加密的将密码存在本地文件或是云笔记中;</li> <li>通过邮箱或是微信进行密码分享。</li> </ol> <p>我们需要一个工具管理我们的密码,包括如下功能:</p> <ol> <li>生成复杂密码;</li> <li>密码被加密后保存;</li> <li>分发方式安全;</li> <li>使用起来简单方便;</li> <li>支持团队分组管理。</li> </ol> <p>Refs:</p> <p>How to Manage Passwords in a Team: <a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">https://medium.com/altcademy/how-to-manage-passwords-in-a-team-3ed010bc3ccf</a></p> <h2 id=decision-1>Decision</h2> <p>LastPass(功能繁杂,使用人数最多,费用 1450 USD / 50 users) PassPack(功能简单,小众,不支持附件,费用 144 USD / 80 users) 1Password(功能简单,使用方式友好,费用 7200 USD / 50 users)</p> <h2 id=consequences-1>Consequences</h2> <ol> <li>需要考虑兼容性,Win/Mac/Linux;</li> <li>费用需要考虑;</li> <li>需要可存储附件(比如,ssh 公私钥)。</li> </ol> <h1 id=3-使用-ssh-key-替换用户名密码方式登录>3. 使用 ssh key 替换用户名密码方式登录</h1> <p>Date: 30/03/2017</p> <h2 id=status-2>Status</h2> <p>Accepted</p> <h2 id=context-2>Context</h2> <p>当前我们使用的是用户名、密码方式进行服务器登录,存在以下问题</p> <ol> <li>安全性问题,密码面临被破解的风险;</li> <li>易用性问题,无法使用 config 记录密码,可以使用第三方软件解决,如,SecureCRT,ZOC7;</li> <li>无法充分使用 local terminal,如 iTerm2;</li> </ol> <h3 id=refs-2>Refs:</h3> <ul> <li>SSH: passwords or keys? <a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">https://lwn.net/Articles/369703/</a></li> <li>Why is SSH key authentication better than password authentication? <a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">https://superuser.com/questions/303358/why-is-ssh-key-authentication-better-than-password-authentication</a></li> <li>Why is using an SSH key more secure than using passwords? <a href="https://www.utdallas.edu/~chung/SA/zz-Impreso-architecture_decisions-tyree-05.pdf">https://security.stackexchange.com/questions/69407/why-is-using-an-ssh-key-more-secure-than-using-passwords</a></li> </ul> <h2 id=decision-2>Decision</h2> <p>禁用用户名、密码登录,使用 ssh key 进行登录</p> <p><img src="files/password-manage.png" alt=""></p> <h2 id=consequences-2>Consequences</h2> <ol> <li>团队成员使用新方式需要适应;</li> <li>key 的管理需要统一(需要引入堡垒机)。</li> </ol> <h1 id=4-ubuntu-vs-centos>4. Ubuntu vs CentOS</h1> <p>Date: 30/03/2017</p> <h2 id=status-3>Status</h2> <p>Accepted</p> <h2 id=context-3>Context</h2> <p>我们的服务器用的都是阿里云的 ECS,历史原因多数操作系统是 centos(6.5),内部得到的信息是稳定,当然目前阿里云已不提供此版本镜像。</p> <p>从个人使用经历看,自 10 年那会起,我所经历的公司选用的都是 ubuntu,当然我们应该知其所以然,而不是盲目的接受。</p> <ol> <li>centos 系统初始化,软件安装基本都走的是手动编译,效率低,但这点往往被大家作为稳定性的佐证;</li> <li>centos 系统之上的所有软件都过于老旧,想装第三方软件的最新稳定版,很困难(难道一定要手动编译才好);</li> <li>从开始使用 ubuntu,就看重他的简单易用,当然当时业界的看法是,不专业,不稳定;</li> <li>ubuntu 的社区比 centos 更活跃,网上的资料也比 centos 多;</li> <li>ubuntu 相关的问题很容易在网上找到解决方案,但 centos 不是。</li> </ol> <p>这些都是自己的使用体验</p> <p>从主机市场分析数据(<a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">https://www.digitalocean.com/community/questions/whats-is-better-and-why-linux-centos-or-ubuntu?answer=30514</a>)看,Simple Hosting, VPS, Dedicated &amp; Clouds 这三个领域,centos 占有率均低于 ubuntu。尤其在云市场,centos 只有 ubuntu 的 1/20(<a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">http://thecloudmarket.com/stats#/by_platform_definition</a>)。</p> <p><img src="files/password-manage.png" alt=""></p> <p>更多的对比信息请查看:</p> <ul> <li>CentOS vs Ubuntu: Which one is better for a server <a href="https://www.utdallas.edu/~chung/SA/zz-Impreso-architecture_decisions-tyree-05.pdf">https://thishosting.rocks/centos-vs-ubuntu-server/</a></li> <li>What Linux server should I go for: Ubuntu or CentOS? <a href="https://github.com/npryce/adr-tools">https://www.quora.com/What-Linux-server-should-I-go-for-Ubuntu-or-CentOS</a></li> </ul> <h2 id=decision-3>Decision</h2> <p>逐步将系统从 centos 切换至 ubuntu,保证系统的一致,为后期的运维自动化做准备。</p> <h2 id=consequences-3>Consequences</h2> <ul> <li>手动的编译软件改为 apt-get 安装;</li> <li>如果没有对旧系统,旧软件的某些特性有依赖,最好升级为各个软件的最新稳定版,这对性能和安全都大有好处。</li> </ul> <h1 id=5-使用-slack-替代微信邮件和短信>5. 使用 Slack 替代微信、邮件和短信</h1> <p>Date: 31/03/2017</p> <h2 id=status-4>Status</h2> <p>Accepted</p> <h2 id=context-4>Context</h2> <ol> <li>当前使用微信、邮件作为工作中的沟通工具,工作与生活混合;</li> <li>各种告警信息需分别查看邮件、短信或是监控平台;</li> <li>随着任务管理平台、Bug 管理平台、wiki、文档分享网站、聊天工具的流行,邮件的使用场景越来越小,并且邮件信息并不及时;</li> <li>通过微信进行沟通,新人无法了解历史信息,经常需要把发过的内容重复发送。</li> </ol> <h2 id=decision-4>Decision</h2> <h3 id=slack-支持的功能-4>Slack 支持的功能</h3> <ol> <li><strong>公开与私有的频道,频道可随时加入或退出</strong>; <ol> <li>按项目,project-crm, project-sms, 等;</li> <li>按技术话题,tech-restful-api, tech-queue 等;</li> <li>可以邀请相关人,任何人也可随意加入。</li> </ol></li> <li><strong>消息支持表情快速回复</strong>; <ol> <li>表情是附加在消息上的,上下文内聚很高。</li> </ol></li> <li>消息支持收藏; <ol> <li>一些不错的重要信息,可以收藏起来随时查看。</li> </ol></li> <li>支持各种文件的分享; <ol> <li>pdf 等文件均可预览。</li> </ol></li> <li><strong>分享的链接支持预览</strong>; <ol> <li>分享的链接,不用点开也知道大体内容。</li> </ol></li> <li>搜索功能强大,可通过快捷方式,搜索同事,消息记录,文件等;</li> <li>多种程序代码支持高亮; <ol> <li>代码高亮预览,自动折叠,不影响整体效果。</li> </ol></li> <li><strong>强大的第三方集成,将所有消息、通知汇聚在一处</strong>,例如,Trello,Github,NewRelic, Sentry,Jenkins 等;</li> <li><strong>新加入者可查看群组历史信息</strong>。 <ol> <li>信息再也不用重复发了。</li> </ol></li> <li>开放性非常好 <ol> <li>任何人都可以方便申请开发者 KEY,建立自己的机器人。</li> </ol></li> </ol> <h3 id=研发部频道设计-4>研发部频道设计</h3> <ol> <li>CI/CD - 用于接收测试、部署结果,测试覆盖率,PR 等信息,也用于发起测试、部署等;</li> <li>NewRelic - 用于接收应用性能报警等信息;</li> <li>Sentry - 线上实时错误信息,可根据项目单独拆出来;</li> <li>Team-X - 用于组内沟通,一个 Scrum 组,包括研发,产品及测试;</li> <li>Knowledge - 用于所有研发人员进行沟通与分享;</li> <li>Product - 用于跨 Team 的产品进行沟通与分享;</li> <li>Backend - 用于所有后端人员进行问题咨询及分享;</li> <li>Leads(私密) - 用于所有 leader 进行沟通、安排周会等;</li> <li>Frontend, UI, Mobile, Devops, QA etc</li> </ol> <h3 id=我们用了如下第三方软件-4>我们用了如下第三方软件</h3> <ul> <li>Sentry</li> <li>NewRelic</li> <li>RedMine</li> <li>Teambition</li> <li>Confluence</li> <li>Github</li> <li>Bugly</li> <li>FIR.im</li> <li>Jenkins</li> <li>etc</li> </ul> <h3 id=slack-vs-bearychat-4>Slack vs BearyChat</h3> <ul> <li>Slack 优缺点: <ul> <li>鼻祖</li> <li>几乎所有常用软件(国外)都有集成</li> <li>功能完善健壮,公司可信</li> <li>网络不稳定</li> <li>国内应用集成很少</li> </ul></li> <li>BearChat 优缺点: <ul> <li>基本有 Slack 的核心功能</li> <li>数据的隐私无法保证</li> <li>服务的可用性无法保证</li> <li>第三方集成太少(must-read, Simple Poll, etc 都没有),倒是集成了国内的 Teambiton, 监控宝等</li> </ul></li> </ul> <p>最终,我们给国产软件(服务)一个机会。</p> <p>经过两周的 BearyChat 试用,目前已准备转用 Slack - 2017-08-03</p> <ol> <li>BearyChat 的 Teambition 集成失败,沟通后说是 TB 的接口调整;</li> <li>集成数的限制,都是 10 个,但同一个第三方多次集成,Slack 算一个,BearyChat 算多个,比如 Github, Sentry;</li> <li>经过对各个国内公司的了解,发现使用中 Slack 的国内稳定性还好。</li> </ol> <h2 id=consequences-4>Consequences</h2> <ul> <li>大家已习惯使用 Wechat,引入一个新的沟通平台有学习成本。</li> </ul> <h1 id=6-使用-git-替换-svn>6. 使用 Git 替换 SVN</h1> <p>Date: 06/04/2017</p> <h2 id=status-5>Status</h2> <p>Accepted</p> <h2 id=context-5>Context</h2> <p>当前我们用的是 SVN 做代码、产品文档、UI 设计图的管理 我们在此只说其中的代码管理</p> <ol> <li>代码仓库过大,新分支,新Tag 代码都是一份完整的拷贝;</li> <li>必须联网提交;</li> <li>SVN 代码合并方式低效,目前使用 Beyond Compare 做代码合并,分支使用方式落后;</li> <li>无法很好的做 code review(只能 patch 或第三方工具);</li> <li>面试者看到是这么落后,以此类别其他技术栈,综合理解就是,我能学到啥。</li> </ol> <h2 id=decision-5>Decision</h2> <p>使用全球最流行的分布式管理工具 Git 及平台 Github 分布式,目录结构简单,代码无冗余,可 review with PR。</p> <p>Refs:</p> <p>https://help.github.com/articles/what-are-the-differences-between-subversion-and-git/ http://stackoverflow.com/questions/871/why-is-git-better-than-subversion</p> <h2 id=consequences-5>Consequences</h2> <p>方式一:</p> <p>git svn clone <code>svn project url</code> -T trunk 将 SVN 项目的 trunk 转为 git 项目的 master,仅保留了 trunk 分支的提交记录,此方式适用于所有代码都规整到了一个分支,并且不需要其他分支的提交记录。</p> <p>方式二:</p> <p>使用命令 https://github.com/nirvdrum/svn2git ,它可以保留所有branch, tags,以及所有分支的提交历史。 svn2git http://svn.example.com/path/to/repo --trunk trunk --tags tag --branches branch git push --all origin git push --tags</p> <p>use <code>--revision number</code> to reduce the commit history.</p> <p>目前生产环境使用的 centos 版本过低,导致 git 也无法升级的处理方法: yum install http://opensource.wandisco.com/centos/6/git/x86_64/wandisco-git-release-6-1.noarch.rpm yum update git</p> <p>Refs: <a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">https://www.atlassian.com/git/tutorials/migrating-overview</a> <a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">https://www.atlassian.com/git/tutorials/svn-to-git-prepping-your-team-migration</a> <a href="https://www.utdallas.edu/~chung/SA/zz-Impreso-architecture_decisions-tyree-05.pdf">https://www.git-tower.com/learn/git/ebook/cn/command-line/appendix/from-subversion-to-git</a> <a href="https://github.com/npryce/adr-tools">https://tecadmin.net/how-to-upgrade-git-version-1-7-10-on-centos-6/</a></p> <h1 id=7-使用-passpack-进行密码管理>7. 使用 PassPack 进行密码管理</h1> <p>Date: 07/04/2017</p> <h2 id=status-6>Status</h2> <p>Accepted</p> <h2 id=context-6>Context</h2> <p>step zero: 管理员以 company-name 注册付费管理员账号</p> <p>step one: 公司成员在 https://www.passpack.com/ 使用公司邮箱注册免费账号,用户名统一:company-name-username</p> <p>step two: 点击 <code>People</code> tab 激活自己的账号,使用相同的用户名</p> <p>step three: 邀请管理员账号</p> <p>step four: 创建或导入自己管理的所有用户名密码,批量 transfer 给 company-name(个人密码也可以用它管理,就无需 transfer 给管理员了)</p> <p>PassPack 使用介绍:https://www.passpack.com/getting-started/PasspackGettingStarted_Admin_EN.pdf</p> <h2 id=decision-6>Decision</h2> <p>鉴于管理员一人处理非常琐碎,下放权限至 group owner 可编辑相应密码</p> <p>用户名命名规范:公司名简称-姓名 Name 命名规范:简单描述所用的服务,用于搜索,层级间使用冒号<code>:</code>隔开,例如,<code>aliyun:oss:contract-doc:ak</code></p> <h2 id=consequences-6>Consequences</h2> <ol> <li>推动各个 team leader 使用并管理;</li> <li>向 team member 分发密码走这个渠道;</li> <li>列入新人入职注册项。</li> </ol> <h1 id=8-使用堡垒机加强服务器安全>8. 使用堡垒机加强服务器安全</h1> <p>Date: 08/04/2017</p> <h2 id=status-7>Status</h2> <p>Accepted</p> <h2 id=context-7>Context</h2> <ol> <li>旧文写了为了禁止外网暴力破解,我们将用户名、密码登录方式改为了 ssh key 登录;</li> <li>为了管理方便,当时只区分了生产 key 和测试 key,内部大家共用 key, 并且有 sudo 权限,导致存在内部风险,而针对每个人手动生成 ssh key 又会有管理上的问题;</li> <li>每个人需要对所有机器配置 ssh config,使用不方便;</li> <li>当前成员行为无法区分,有成员在系统上执行了 vim 大文件操作导致系统负载急剧升高,也有成员将系统配置改动导致其他项目运行出现问题,当然也存在数据安全上的问题。</li> </ol> <p>未使用堡垒机时:</p> <p><img src="files/password-manage.png" alt=""></p> <h2 id=decision-7>Decision</h2> <p>目标:简化并统一管理线上服务器的登录并审计操作日志</p> <p>结构图:</p> <p><img src="files/bastion.png" alt=""></p> <p>Refs:</p> <ul> <li><a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">https://skyportblog.com/2015/08/27/the-jump-boxjump-server-is-not-dead-it-is-more-necessary-than-ever/</a></li> <li><a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">https://www.quora.com/What-is-the-difference-between-a-bastion-host-and-a-VPN-host</a></li> </ul> <p>经过多个堡垒机项目的调研,我们最终选择了 <a href="https://www.utdallas.edu/~chung/SA/zz-Impreso-architecture_decisions-tyree-05.pdf">https://github.com/jumpserver/jumpserver</a>,源于使用人数多,并且项目活跃度高。</p> <p>Jumpserver v0.4.0 新版本预览 <a href="https://github.com/npryce/adr-tools">https://github.com/jumpserver/jumpserver/issues/350</a></p> <h2 id=consequences-7>Consequences</h2> <ul> <li>0.3 版本的一些弊端导致我们激进的选择了 0.4 版本,此版本处于开发中,存在很多未知问题,并且我们已在之上做二次开发</li> <li>文件下载不方便</li> <li>内网之间文件同步不方便</li> </ul> <h1 id=9-结构化-django-项目>9. 结构化 Django 项目</h1> <p>Date: 10/04/2017</p> <h2 id=status-8>Status</h2> <p>Accepted</p> <h2 id=context-8>Context</h2> <p>We have 20+ projects which based on Django, but we don’t have the same structure which make our project hard to read.</p> <p>We need handle those things:</p> <ol> <li>store all apps in one place;</li> <li>support different environments;</li> <li>store project related configs.</li> </ol> <h2 id=decision-8>Decision</h2> <p>make a skeleton for django: <a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">https://github.com/huifenqi/django-project-skeleton</a></p> <h2 id=consequences-8>Consequences</h2> <ol> <li>make all new projects with this skeleton;</li> <li>apply this structure to the old projects when refactoring.</li> </ol> <h1 id=10-git-基础及风格指南>10. Git 基础及风格指南</h1> <p>Date: 11/04/2017</p> <h2 id=status-9>Status</h2> <p>Accepted</p> <h2 id=context-9>Context</h2> <p>We use git and GitHub in different ways, it’s emergency to teach team members with the git basics and style guide we will use.</p> <h2 id=decision-9>Decision</h2> <h3 id=git-basics-9>git basics</h3> <ol> <li>setup ssh keys (<a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">https://github.com/settings/keys</a>) or GUI;</li> <li>clone repo into local system: <code>git clone <EMAIL>:huifenqi/django-project-skeleton.git</code>;</li> <li>files store in three stages: <img src="files/password-manage.png" alt=""> <ol> <li><code>Working Directory</code>: holds the actual files;</li> <li><code>Index</code>: staging area which store your changed files;</li> <li><code>HEAD</code>: points to the last commit you've made.</li> </ol></li> <li><code>Working Directory</code> -&gt; <code>Index</code>: <code>git add &lt;filename&gt;</code> or <code>git add *</code>;</li> <li><code>Index</code> -&gt; <code>HEAD</code>: <code>git commit -m &quot;Commit message&quot;</code>;</li> <li>push updates to Github: <code>git push origin master</code>;</li> <li>create branch: <code>git checkout -b feature/x</code> <img src="files/branches.png" alt=""></li> <li>push branch to Github and others can see: <code>git push origin &lt;branch_name&gt;</code>;</li> <li>sync local with Github: <code>git pull</code>;</li> <li>make a new tag: <code>git tag &lt;tag_name&gt;</code>;</li> <li>show history: <code>git log</code>;</li> <li>show changes: <code>git diff &lt;previous_commit_hash&gt;</code>;</li> <li>others: <code>git status</code>, <code>git branch</code>, <code>git tag</code>, etc.</li> </ol> <h3 id=git-style-guide-9>git style guide</h3> <h4 id=branches-9>Branches</h4> <ul> <li>Choose short and descriptive names: <a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">https://github.com/agis-/git-style-guide#branches</a>;</li> <li>Use dashes to separate words.</li> </ul> <h4 id=commits-9>Commits</h4> <ul> <li>Each commit should be a single logical change. Don't make several logical changes in one commit;</li> </ul> <h4 id=messages-9>Messages</h4> <ul> <li>when writing a commit message, think about what you would need to know if you run across the commit in a year from now.</li> </ul> <h3 id=refs-9>Refs</h3> <ul> <li><a href="https://www.utdallas.edu/~chung/SA/zz-Impreso-architecture_decisions-tyree-05.pdf">http://rogerdudler.github.io/git-guide/index.html</a></li> <li><a href="https://github.com/npryce/adr-tools">https://confluence.atlassian.com/bitbucketserver/basic-git-commands-776639767.html</a></li> <li><a href="https://github.com/agis-/git-style-guide">https://github.com/agis-/git-style-guide</a></li> </ul> <h2 id=consequences-9>Consequences</h2> <p>Make sure everyone follow the guide, check the Github feeds often.</p> <h1 id=11-apply-github-workflow-to-our-team>11. Apply Github workflow to our team</h1> <p>Date: 11/04/2017</p> <h2 id=status-10>Status</h2> <p>Accepted</p> <h2 id=context-10>Context</h2> <p>Context here...</p> <h2 id=decision-10>Decision</h2> <h3 id=github-workflow-10>Github workflow</h3> <p>There are various workflows and each one has its strengths and weaknesses. Whether a workflow fits your case, depends on the team, the project and your development procedures.</p> <p>TBD</p> <h2 id=consequences-10>Consequences</h2> <p>TBD</p> <h1 id=12-think-about-micro-service>12. Think about micro service</h1> <p>Date: 13/04/2017</p> <h2 id=status-11>Status</h2> <p>Proposed</p> <h2 id=context-11>Context</h2> <ol> <li>已拆分为各种服务(1. 接口不统一、无监控、无统一日志管理);</li> <li>API 文档管理不够;</li> <li>服务的部署纯手动;</li> </ol> <h2 id=decision-11>Decision</h2> <p>Decision here...</p> <h2 id=consequences-11>Consequences</h2> <ol> <li>跨语言;</li> <li>提供 server 和 client 端;</li> <li>统一上线过程:独立部署、运行、升级;</li> <li>统一日志记录与审计:第三方日志服务;</li> <li>统一风格:REST API or RPC;</li> <li>统一认证和鉴权:权限管理、安全策略;</li> <li>统一服务测试:调度方式、访问入口;</li> <li>资源管理(虚拟机、物理机、网络);</li> <li>负载均衡:客户端 or 服务端;</li> <li>注册发现:中心话注册 or hardcode;</li> <li>监控告警;</li> </ol> <h2 id=refs-11>Refs</h2> <h3 id=why-11>Why</h3> <ul> <li>先把平台做扎实,再来微服务吧 <a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">http://www.infoq.com/cn/articles/how-to-understand-microservice-architecture</a></li> <li>Microservices – Please, don’t <a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">http://basho.com/posts/technical/microservices-please-dont/</a></li> <li>SOA和微服务架构的区别? <a href="https://www.utdallas.edu/~chung/SA/zz-Impreso-architecture_decisions-tyree-05.pdf">https://www.zhihu.com/question/37808426/answer/93335393</a></li> </ul> <h3 id=how-11>How</h3> <ul> <li>一个完整的微服务系统,应该包含哪些功能?<a href="https://github.com/npryce/adr-tools">http://www.infoq.com/cn/articles/what-complete-micro-service-system-should-include</a></li> <li>构建高性能微服务架构 <a href="https://github.com/agis-/git-style-guide">http://www.infoq.com/cn/articles/building-a-high-performance-micro-service-architecture</a></li> <li>服务化框架技术选型与京东JSF解密 <a href="http://zhuanlan.51cto.com/art/201612/525719.htm">http://zhuanlan.51cto.com/art/201612/525719.htm</a></li> <li>微服务实战:从架构到发布(一)<a href="https://segmentfault.com/a/1190000004634172">https://segmentfault.com/a/1190000004634172</a></li> <li>微服务架构的基础框架选择:Spring Cloud还是Dubbo? <a href="http://blog.didispace.com/microservice-framework/">http://blog.didispace.com/microservice-framework/</a></li> <li>分布式服务框架之服务化最佳实践 <a href="http://www.infoq.com/cn/articles/servitization-best-practice">http://www.infoq.com/cn/articles/servitization-best-practice</a></li> <li>You need to be this tall to use <a href="">micro</a> services: <a href="https://news.ycombinator.com/item?id=12508655">https://news.ycombinator.com/item?id=12508655</a></li> </ul> <h3 id=服务注册-11>服务注册</h3> <ul> <li>分布式服务治理的设计问题? <a href="https://www.zhihu.com/question/51436292/answer/126128311">https://www.zhihu.com/question/51436292/answer/126128311</a></li> </ul> <h3 id=rest-api-vs-rpc-11>REST API vs RPC</h3> <ul> <li>Do you really know why you prefer REST over RPC? <a href="https://apihandyman.io/do-you-really-know-why-you-prefer-rest-over-rpc/">https://apihandyman.io/do-you-really-know-why-you-prefer-rest-over-rpc/</a></li> <li>REST vs JSON-RPC? <a href="http://stackoverflow.com/questions/15056878/rest-vs-json-rpc">http://stackoverflow.com/questions/15056878/rest-vs-json-rpc</a></li> <li>What differentiates a REST web service from a RPC-like one? <a href="http://stackoverflow.com/questions/7410040/what-differentiates-a-rest-web-service-from-a-rpc-like-one">http://stackoverflow.com/questions/7410040/what-differentiates-a-rest-web-service-from-a-rpc-like-one</a></li> </ul> <h1 id=13-the-sense-of-done>13. The sense of Done</h1> <p>Date: 14/04/2017</p> <h2 id=status-12>Status</h2> <p>Proposed</p> <h2 id=context-12>Context</h2> <p>We face this situation very often?</p> <ol> <li>I’m already fixed this, it’s in testing;</li> <li>I’m already add this monitoring plugin in the repo, it’s deployed on staging, let’s watch for a few days, then deploy on production;</li> <li>I’m already move this service to new machine, I will clean the old machine later.</li> </ol> <p>Sounds familiar? Yes, very often.</p> <p>Is that all done? No, it doesn’t.</p> <h2 id=decision-12>Decision</h2> <ol> <li>talk this all the time, let team member have this sense;</li> <li>make specifications for each domain.</li> </ol> <h2 id=consequences-12>Consequences</h2> <p>Create specifications from our experience.</p> <p>An Done-Done example with <code>User Story</code>:</p> <ol> <li>stories and AC reviewed (DEV);</li> <li>All AC implemented (DEV);</li> <li>Code reviewed (Dev);</li> <li>Tests passed (Dev+QA+CI);</li> <li>No bugs left (QA);</li> <li>Deployed to production (Dev);</li> <li>Accepted (PM).</li> </ol> <p>Refs:</p> <ul> <li>What is Done Done? <a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">http://chrislema.com/what-is-done-done/</a></li> <li>Agile Principle 7: Done Means DONE! <a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">http://www.allaboutagile.com/agile-principle-7-done-means-done/</a></li> <li>The Definition of READY <a href="https://www.utdallas.edu/~chung/SA/zz-Impreso-architecture_decisions-tyree-05.pdf">http://blog.xebia.com/the-definition-of-ready/</a></li> <li>What is the Definition of Done (DoD) in Agile? <a href="https://github.com/npryce/adr-tools">http://www.solutionsiq.com/what-is-the-definition-of-done-dod-in-agile/</a></li> <li>Scrum Crash Course <a href="https://github.com/agis-/git-style-guide">https://www.slideshare.net/beITconference/infragistics-scrum-crashcoursebeit2014</a></li> </ul> <h1 id=14-how-to-restart-a-server>14. How to restart a server</h1> <p>Date: 19/04/2017</p> <h2 id=status-13>Status</h2> <p>Accepted</p> <h2 id=context-13>Context</h2> <p>Context here...</p> <h2 id=decision-13>Decision</h2> <p>Decision here...</p> <h2 id=consequences-13>Consequences</h2> <p>Consequences here...</p> <h1 id=15-case-how-to-find-the-root-reason-of-high-load>15. Case: How to find the root reason of high load</h1> <p>Date: 20/04/2017</p> <h2 id=status-14>Status</h2> <p>Accepted</p> <h2 id=context-14>Context</h2> <p>Context here...</p> <h2 id=decision-14>Decision</h2> <p>Decision here...</p> <h2 id=consequences-14>Consequences</h2> <p>Consequences here...</p> <h1 id=16-故障记录报告>16. 故障记录报告</h1> <p>Date: 20/04/2017</p> <h2 id=status-15>Status</h2> <p>Accepted</p> <h2 id=context-15>Context</h2> <p>事故频发,处理速度慢,流程不清晰,并且一直未做记录,导致同样的问题会再次复现。</p> <h2 id=decision-15>Decision</h2> <p>定义故障报告模板:</p> <ol> <li>对故障进行描述,以便查询并对我们的系统稳定性做评估;</li> <li>对故障做分析,便于未来可快速处理同样问题;</li> <li>加监控,以便问题出现前就做处理;</li> <li>解决并升级方案,完全避免此类问题。</li> </ol> <h2 id=consequences-15>Consequences</h2> <h3 id=故障报告模板-15>故障报告模板</h3> <h4 id=问题描述-15>问题描述</h4> <ul> <li>简单的故障描述(三句话即可)</li> <li>故障出现及恢复时间</li> <li>影响范围</li> <li>根本原因</li> </ul> <h4 id=时间线-15>时间线</h4> <ul> <li>故障通知时间</li> <li>各种为了恢复服务的操作时间(注意顺序)</li> </ul> <h4 id=原因分析-15>原因分析</h4> <ul> <li>详细的故障描述</li> <li>客观,不要添加粉饰性的内容</li> </ul> <h4 id=做错的事情-15>做错的事情</h4> <h4 id=做对的事情-15>做对的事情</h4> <h4 id=将来如何避免此类事情再次发生-15>将来如何避免此类事情再次发生</h4> <ul> <li>监控</li> <li>规范</li> <li>预估</li> </ul> <p>Refs: Outage Post-Mortem – June 14 <a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">https://www.pagerduty.com/blog/outage-post-mortem-june-14/</a> How to write an Incident Report / Postmortem <a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">https://sysadmincasts.com/episodes/20-how-to-write-an-incident-report-postmortem</a></p> <h1 id=17-incident-classify-and-recovery>17. Incident classify and recovery</h1> <p>Date: 20/04/2017</p> <h2 id=status-16>Status</h2> <p>Proposed</p> <h2 id=context-16>Context</h2> <p>对服务的可用等级不清晰,处理问题的优先级不足,临时分析现象及寻找解决方案,耗时过长</p> <h2 id=decision-16>Decision</h2> <p>划分服务等级,做好预案</p> <h2 id=consequences-16>Consequences</h2> <p>故障分类和预案</p> <h3 id=自然灾害-16>自然灾害</h3> <ol> <li>灾备,常见的有,两地三中心;</li> </ol> <h3 id=服务运营商-16>服务运营商</h3> <h4 id=dns-解析问题-16>DNS 解析问题</h4> <ol> <li>联系 DNS 提供商,确定故障恢复的时间;</li> <li>所需恢复时间大于 TTL,实施切换 DNS 运营商的预案(DnsPod to Aliyun etc)。</li> </ol> <h4 id=aliyun-内部问题-16>Aliyun 内部问题</h4> <h4 id=cdn-运营商-16>CDN 运营商</h4> <h3 id=外部人为-16>外部人为</h3> <h4 id=人为攻击-16>人为攻击</h4> <ul> <li>DDOS</li> <li>CC</li> <li>SQL 注入</li> <li>XSS</li> </ul> <h4 id=正常请求-16>正常请求</h4> <ul> <li>流量</li> </ul> <h3 id=架构内部-16>架构内部</h3> <h4 id=数据库级故障-16>数据库级故障</h4> <h4 id=内部网络级别-16>内部网络级别</h4> <ul> <li>Aliyun 内部</li> <li>网络、防火配置</li> </ul> <h4 id=系统级别故障-16>系统级别故障</h4> <ul> <li>单系统内部</li> <li>系统间通信</li> </ul> <h4 id=系统服务级别故障-16>系统服务级别故障</h4> <h4 id=应用服务级别故障-16>应用服务级别故障</h4> <h4 id=应用虚拟环境级别故障-16>应用虚拟环境级别故障</h4> <h4 id=应用代码级别故障-16>应用代码级别故障</h4> <h1 id=18-ios-持续发布>18. iOS 持续发布</h1> <p>Date: 20/04/2017</p> <h2 id=status-17>Status</h2> <p>Accepted</p> <h2 id=context-17>Context</h2> <p>目前使用测试同学的工作电脑做 iOS 的打包与分发,对测试同学有一定的影响。</p> <h2 id=decision-17>Decision</h2> <p><img src="files/password-manage.png" alt=""></p> <p>基本流程不变,将打包工作交由第三方服务 buddybuild 处理并分发。 buddybuild 本可以直接分发,但由于其分发网络在国内比较慢,所以继续使用 fir.im 进行分发</p> <h2 id=consequences-17>Consequences</h2> <p>免费版单次打包过程限制在 20 分钟内,无限次打包但会优先打包付费用的的应用,未来长期的高频次使用需要购买付费版。</p> <p>Refs:</p> <p>Custom Build Steps: <a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">http://docs.buddybuild.com/docs/custom-prebuild-and-postbuild-steps</a></p> <h1 id=19-服务器申请与升级---容量评估>19. 服务器申请与升级 - 容量评估</h1> <p>Date: 21/04/2017</p> <h2 id=status-18>Status</h2> <p>Accepted</p> <h2 id=context-18>Context</h2> <ol> <li>部分机器的 CPU,内存,硬盘,使用率均在 90% 左右,另一些机器各项指标使用率在 1% 左右;</li> <li>部分机器的 CPU,内存,硬盘搭配不合理,CPU 使用率 1%,但内存使用率在 90% 左右;</li> <li>一些对磁盘读写要求高的服务,使用的是普通云盘,比如,数据库,SVN等;</li> <li>申请机器时,无法提出配置要求,基本靠拍脑门决定;</li> <li>对服务的发展没有思考,配置要了 12 个月后才能使用到的配置。</li> </ol> <h2 id=decision-18>Decision</h2> <ol> <li>压力测试;</li> <li>分析业务各个指标的使用情况,CPU 密集型,内存密集型还是有其他的特点;</li> <li>鉴于 Aliyun ECS 随时可以扩展,可以先用低配机器,根据使用情况,进行单指标垂直升级;</li> <li>水平扩展,即提升了服务的处理能力又做了高可用;</li> <li>对于不合理的内存使用,要分析自己程序中是否有内存泄漏或大数据加载。</li> </ol> <h2 id=consequences-18>Consequences</h2> <p>Refs:</p> <ul> <li>互联网性能与容量评估的方法论和典型案例 <a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">http://www.jianshu.com/p/fbf56ccb4ebe</a></li> <li>携程网基于应用的自动化容量管理与评估 <a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">https://zhuanlan.zhihu.com/p/25341948</a></li> <li>大促活动前团购系统流量预算和容量评估 <a href="https://www.utdallas.edu/~chung/SA/zz-Impreso-architecture_decisions-tyree-05.pdf">http://tech.meituan.com/stress-test-before-promotion.html</a></li> <li>10个互联网团队应对高压的容量评估与高可用体系:私董会1期 <a href="https://github.com/npryce/adr-tools">http://weibo.com/ttarticle/p/show?id=2309403998916147312333</a></li> <li>mysql 性能容量评估 <a href="https://github.com/agis-/git-style-guide">http://www.cnblogs.com/Aiapple/p/5697912.html</a></li> </ul> <h1 id=20-日志管理>20. 日志管理</h1> <p>Date: 24/04/2017</p> <h2 id=status-19>Status</h2> <p>Accepted</p> <h2 id=context-19>Context</h2> <ol> <li>记录位置混乱,有系统默认路径,有自定义路径;</li> <li>日志未切割,日志一直记录在一个文件中,导致文件巨大;</li> <li>记录方式有问题,一个请求量不大的服务,每日存在 1G 的日志数据,发现存在将整个 html 写入日志的问题;</li> <li>日志记录格式不统一,涉及日志规范有 nginx, python 和 java;</li> <li>不容易访问,需要给开发者提供对应机器的登录与日志查看权限;</li> <li>使用 grep 等查询方式,上下文使用不方便,查询效率低;</li> <li>临时的统计需要写一次性的脚本;</li> <li>无法对异常日志做监控与报警;</li> <li>归档日志太多,需要定时清理。</li> </ol> <p>附加需求:</p> <ol> <li>日志根据项目区分查看权限;</li> <li>可报警;</li> <li>可产生图表。</li> </ol> <h2 id=decision-19>Decision</h2> <ol> <li>日志记录统一至 /data/logs 目录下,针对每个服务创建日志目录(包括系统服务),如 nginx;</li> <li>所有需要文件切割的地方,我们使用系统的 <code>/etc/logrotate.d</code>, copy <code>/etc/logrotate.d/nginx</code> 的设置进行改动即可。(系统的默认切割时间各个系统不一致,所以我们删除 <code>/etc/cron.daily/logrotate</code>,改为在 <code>/etc/crontab</code> 加入 <code>59 23 * * * root /usr/sbin/logrotate /etc/logrotate.conf</code>(使用日志服务后无需此步));</li> <li>针对大日志文件进行调研,查看日志内容的必要性;</li> <li>规范化日志记录格式及内容,格式可以参考 Aliyun 采集方式及常见配置示例 <a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">https://help.aliyun.com/document_detail/28981.html</a></li> <li>使用日志管理服务可用解决如上 5 - 9 的问题。</li> </ol> <p>可选的日志服务:</p> <ol> <li>Aliyun 日志服务 (功能强大(复杂),价格计算复杂,阿里云体系内速度应该快些,服务提供没多久,可用性待验证,展示效果很一般,价格适中);</li> <li>sumologic (查询功能强大,上下文展示方便,费用高);</li> <li>logentries (使用很方便,展示效果很棒,上下文展示一般,费用高);</li> </ol> <p>综合考虑后,选用 Aliyun 日志服务</p> <p>整体功能强大</p> <p><img src="files/password-manage.png" alt=""></p> <p>查询功能够用,虽然界面一般</p> <p><img src="files/branches.png" alt=""></p> <h2 id=consequences-19>Consequences</h2> <p>创建一个项目,然后创建各自服务的日志库,如下</p> <ul> <li>nginx: nginx-access, nginx-error</li> <li>service1: service1-access, service1-log</li> </ul> <p>未来需处理好 Aliyun 子账号与日志的权限关系</p> <p>Refs:</p> <ul> <li>How To Configure Logging and Log Rotation in Nginx on an Ubuntu VPS <a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">https://www.digitalocean.com/community/tutorials/how-to-configure-logging-and-log-rotation-in-nginx-on-an-ubuntu-vps</a></li> </ul> <h1 id=21-redis-使用按业务分离并上云>21. Redis 使用按业务分离并上云</h1> <p>Date: 26/04/2017</p> <h2 id=status-20>Status</h2> <p>Accepted</p> <h2 id=context-20>Context</h2> <ol> <li>redis server 部署在业务机上,业务与数据存储耦合;</li> <li>所有业务的数据存在一个 db 0 中,业务之间很容易产生 key 冲突,业务扩展时需顾虑其他业务数据;</li> <li>单点,业务中存有流程数据,风险比较大;</li> <li>如果切到独立的机器,资源利用率不高。</li> </ol> <h2 id=decision-20>Decision</h2> <ol> <li>将自建 redis server 迁移至 aliyun redis 中;</li> <li>理清业务对 redis 的使用情况,按业务划分指定 redis db index 或 独立 redis 实例;</li> <li>aliyun redis 做了高可用;</li> <li>aliyun 目前可选的范围很多,最小实例是 256M,价格也合理。</li> </ol> <p>使用 aliyun redis 后,额外得到一个数据管理与监控功能功能,如图</p> <p><img src="files/password-manage.png" alt=""></p> <h2 id=consequences-20>Consequences</h2> <ol> <li><p>针对缓存数据:</p> <p>我们无需做数据迁移,直接指定预分配的 aliyun redis db index 即可;</p></li> <li><p>对于存在需要迁移的数据:</p> <p>测试 -&gt; 更新连接配置 -&gt; 暂停业务服务 -&gt; 导入数据(AOF) -&gt; 启动业务服务</p> <p><code>redis-cli -h xxx.redis.rds.aliyuncs.com -p 6379 -a xx--pipe &lt; appendonly.aof</code></p> <ol> <li>确保 AOF 已打开(未打开的话,需更新配置及使用 bgrewriteaof 手动触发);</li> <li>当前使用的版本(3.0.4)不支持单 db 导入及 db swap,所以只能将整个 instance 数据导入(对于按 db index 区分的业务,需要注意数据不被搞乱)。</li> </ol></li> </ol> <p>Refs:</p> <ul> <li>持久化(persistence)<a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">http://redisdoc.com/topic/persistence.html</a></li> <li>How To Back Up and Restore Your Redis Data on Ubuntu 14.04 <a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">https://www.digitalocean.com/community/tutorials/how-to-back-up-and-restore-your-redis-data-on-ubuntu-14-04</a></li> <li>SWAPDB Redis command <a href="https://www.utdallas.edu/~chung/SA/zz-Impreso-architecture_decisions-tyree-05.pdf">https://news.ycombinator.com/item?id=12707973</a></li> <li>Storing Data with Redis <a href="https://github.com/npryce/adr-tools">http://www.mikeperham.com/2015/09/24/storing-data-with-redis/</a></li> </ul> <h1 id=22-防-ddos-攻击>22. 防 DDOS 攻击</h1> <p>Date: 28/04/2017</p> <h2 id=status-21>Status</h2> <p>Accepted</p> <h2 id=context-21>Context</h2> <ol> <li>DDOS 导致业务全线中断,购买高防 IP ,仍然需要重启机器进行 IP 更换(nginx 和业务系统在同一台机器上);</li> <li>入口过多,针对 DDOS,需要多线解决;</li> <li>机器出问题,业务中断,单点;</li> <li>新功能部署,业务中断,没有对多实例进行管理,每次都是杀掉所有,然后重新启动。</li> </ol> <h2 id=decision-21>Decision</h2> <ul> <li>入口收敛,保证对外只有一个域名;</li> <li>做业务服务的高可用;</li> <li>使用 slb + nginx 做高可用,并且在遭遇 DDOS 攻击时,可以通过切换 slb 低成本的解决 DDOS;</li> <li>使用 supervisor 进行任务管理,可逐步进行服务实例的重启。</li> </ul> <h2 id=consequences-21>Consequences</h2> <p>需要保证所有业务机器都是无状态的,即无数据库(mysql, redis, mongodb 等服务在此机器运行),没有用这台机器存储业务用的文件等。</p> <p>Refs:</p> <ul> <li>防 DDOS 攻击 <a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">http://baike.baidu.com/item/防DDOS攻击</a></li> <li>负载均衡(SLB)使用最佳实践 <a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">https://yq.aliyun.com/articles/80055</a></li> <li>Denial of Service Attack Mitigation on AWS <a href="https://www.utdallas.edu/~chung/SA/zz-Impreso-architecture_decisions-tyree-05.pdf">https://aws.amazon.com/cn/answers/networking/aws-ddos-attack-mitigation/</a></li> <li>How to Help Prepare for DDoS Attacks by Reducing Your Attack Surface <a href="https://github.com/npryce/adr-tools">https://aws.amazon.com/cn/blogs/security/how-to-help-prepare-for-ddos-attacks-by-reducing-your-attack-surface/</a></li> <li>Comparing Load Balancing Options: Nginx vs. HAProxy vs. AWS ELB <a href="https://github.com/agis-/git-style-guide">http://www.mervine.net/comparing-load-balancing</a></li> </ul> <h1 id=23-应用性能监控>23. 应用性能监控</h1> <p>Date: 28/04/2017</p> <h2 id=status-22>Status</h2> <p>Accepted</p> <h2 id=context-22>Context</h2> <ol> <li>服务 A,用户访问搜索页面时,请求了 10 分钟,还没返回内容;</li> <li>服务 B,这个页面请求怎么有 1000 次数据库查询;</li> <li>服务 C,这条数据库查询怎么耗时 5 分钟。</li> <li>我们的这个项目做了半年,使用效果如何呀,哦,页面平均响应时间是 5 秒,啊!;</li> <li>用户反馈平均需要需要 1 天以上的时间;</li> <li>测试很难将所有边界场景测试到。</li> </ol> <h2 id=decision-22>Decision</h2> <p>使用 Newrelic 对我们线上主要业务做性能监控,包括响应时长、吞吐量、错误率,慢查询,查询分析等,他可以做到实时定位和通知,并指出具体的代码行及 SQL 语句。</p> <h2 id=consequences-22>Consequences</h2> <p>Refs:</p> <ul> <li>New Relic <a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">https://newrelic.com/application-monitoring/features</a></li> <li>应用性能监控方法一览 <a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">http://www.infoq.com/cn/news/2015/08/monitoring-applications-category</a></li> </ul> <h1 id=24-实时错误跟踪>24. 实时错误跟踪</h1> <p>Date: 28/04/2017</p> <h2 id=status-23>Status</h2> <p>Accepted</p> <h2 id=context-23>Context</h2> <ol> <li>用户 A 使用功能 B,咦,出错了,怎么办呢,再试,还是不行,算了,不用了;又或者我报告一下吧,写邮件?;</li> <li>项目 A 昨晚上线后出现了很多问题,怎么办呢,回滚还是赶快去解决呢?</li> <li>用户发邮件说使用我们应用时出现错误了,错误描述不清晰,我们和用户沟通下吧,1小时过去了,还是重现不了,那我们去看看日志吧,翻出很久之前的日志,使用二分法慢慢查询,3 个小时过去了,终于定位出错误行啦,但是没有上下文及当时的环境变量等信息;</li> <li>异常使用不规范。</li> </ol> <h2 id=decision-23>Decision</h2> <h3 id=使用-sentry-对我们线上主要业务做异常监控-23>使用 Sentry 对我们线上主要业务做异常监控。</h3> <p><img src="files/password-manage.png" alt=""></p> <ul> <li><p>实时通知(sms, email, chat),推荐使用 slack;</p></li> <li><p>可定位具体的代码,包括错误栈信息;</p></li> <li><p>包含异常的环境变量信息。</p></li> <li><p>可主动上报信息;</p></li> <li><p>异常信息会聚合,了解当前异常优先级,避免被异常信息淹没;</p></li> <li><p>支持所有主流语言及对应的框架;</p> <p><img src="files/branches.png" alt=""></p></li> <li><p>配置非常简单,如,<a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">Django 集成</a>;</p></li> <li><p>价格合理,并且有每月1万条的免费限额。</p></li> </ul> <h3 id=规范化异常-23>规范化异常</h3> <h4 id=使用异常的优势-23>使用异常的优势</h4> <ol> <li>隔离错误处理代码和常规代码;</li> <li>在调用栈中向上传播错误;</li> <li>归类和区分错误类型。</li> </ol> <h4 id=异常处理实践原则-23>异常处理实践原则</h4> <ol> <li>使用异常,而不使用返回码;</li> <li>利用运行时异常设定方法使用规则;</li> <li>消除运行时异常;</li> <li>正确处理检查异常;</li> <li>使主流程代码保持整洁;</li> <li>尽量处理最具体的异常,不能处理的异常请抛出来;</li> <li>无法处理的异常却不能抛出时,通过日志记录详细异常栈,并返回给调用方友好的错误信息。</li> </ol> <h2 id=consequences-23>Consequences</h2> <p>Refs:</p> <ul> <li><a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">使用异常的优势</a>;</li> <li><a href="https://www.utdallas.edu/~chung/SA/zz-Impreso-architecture_decisions-tyree-05.pdf">如何正确使用Java异常处理机制</a>;</li> <li><a href="https://github.com/npryce/adr-tools">Java编码中异常的使用建议</a>;</li> <li><a href="https://github.com/agis-/git-style-guide">Write Cleaner Python: Use Exceptions</a>;</li> <li><a href="http://zhuanlan.51cto.com/art/201612/525719.htm">The definitive guide to Python exceptions</a>;</li> </ul> <h1 id=25-按-restful-风格设计更新服务接口>25. 按 RESTful 风格设计更新服务接口</h1> <p>Date: 04/05/2017</p> <h2 id=status-24>Status</h2> <p>Accepted</p> <h2 id=context-24>Context</h2> <ol> <li>当前 URL 定义类似这样,<code>add_message</code>, <code>report_exception</code>, <code>check_pwd</code> 等,函数式定义,导致接口数量增长过快,管理麻烦;</li> <li>所有的请求都走 POST 方法;</li> <li>所有请求返回状态都是 200,使用晦涩难懂的自定义状态码;</li> <li>函数式编程,代码重用度不高;</li> <li>自定义接口文档,无法及时更新;</li> <li>返回结构差异化大,过滤,排序和分页各式各样,无统一的规范;</li> <li>无 API 控制台可供测试;</li> <li>更多。</li> </ol> <h2 id=decision-24>Decision</h2> <ol> <li>URL的设计应使用资源集合的概念; <ul> <li>每种资源有两类网址(接口): <ul> <li>资源集合(例如,/orders);</li> <li>集合中的单个资源(例如,/orders/{orderId})。</li> </ul></li> <li>使用复数形式 (使用 ‘orders’ 而不是 ‘order’);</li> <li>资源名称和 ID 组合可以作为一个网址的节点(例如,/orders/{orderId}/items/{itemId});</li> <li>尽可能的让网址越短越好,单个网址最好不超过三个节点。</li> </ul></li> <li>使用名词作为资源名称 (例如,不要在网址中使用动词);</li> <li>使用有意义的资源描述; <ul> <li>“禁止单纯的使用 ID!” 响应信息中不应该存在单纯的 ID,应使用链接或是引用的对象;</li> <li>设计资源的描述信息,而不是简简单单的做数据库表的映射;</li> <li>合并描述信息,不要通过两个 ID 直接表示两个表的关系;</li> </ul></li> <li>资源的集合应支持过滤,排序和分页;</li> <li>支持通过链接扩展关系,允许客户端通过添加链接扩展响应中的数据;</li> <li>支持资源的字段裁剪,运行客户端减少响应中返回的字段数量;</li> <li>使用 HTTP 方法名来表示对应的行为: <ul> <li>POST - 创建资源,非幂等性操作;</li> <li>PUT - 更新资源(替换);</li> <li>PATCH - 更新资源(部分更新);</li> <li>GET - 获取单个资源或资源集合;</li> <li>DELETE - 删除单个资源或资源集合;</li> </ul></li> <li>合理使用 HTTP 状态码; <ul> <li>200 - 成功;</li> <li>201 - 创建成功,成功创建一个新资源时返回。 返回信息中将包含一个 'Location' 报头,他通过一个链接指向新创建的资源地址;</li> <li>400 - 错误的请求,数据问题,如不正确的 JSON 等;</li> <li>404 - 未找到,通过 GET 请求未找到对应的资源;</li> <li>409 - 冲突,将出现重复的数据或是无效的数据状态。</li> </ul></li> <li>使用 ISO 8601 时间戳格式来表示日期;</li> <li>确保你的 GET,PUT,DELETE 请求是<a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">幂等的</a>,这些请求多次操作不应该有副作用。</li> <li>PUT、POST、PATCH 请求参数通过 <code>application/json</code> 传递;</li> <li>正确返回格式: <ul> <li>单个资源:{field1: value1, …}</li> <li>资源集合:[{field1: value1, …}]</li> <li>资源集合(带分页):</li> </ul></li> </ol> <pre><code class="language-json">{ &quot;count&quot;: 0, &quot;next&quot;: null, &quot;previous&quot;: null, &quot;results&quot;: [{&quot;field1&quot;: &quot;value1&quot;, …}] } </code></pre> <ol start="13"> <li>错误返回格式: <ul> <li>非特定字段错误</li> </ul></li> </ol> <pre><code class="language-json">{ &quot;non_field_errors&quot;: [ &quot;该手机号码未注册!&quot; ] } </code></pre> <ul> <li>特定字段错误</li> </ul> <pre><code class="language-json">{ &quot;phone_number&quot;: [ &quot;该字段不能为空。&quot; ], &quot;address&quot;: [ &quot;该字段不能为空。&quot; ] } </code></pre> <ol start="14"> <li>使用 swagger 做 API 展示 与调试。 <img src="files/password-manage.png" alt=""></li> </ol> <h2 id=consequences-24>Consequences</h2> <p>Refs:</p> <ul> <li>API 设计参考手册 <a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">https://github.com/iamsk/api-cheat-sheet/blob/master/README-zh-Hans.md</a></li> <li>Best Practices for Designing a Pragmatic RESTful API <a href="https://www.utdallas.edu/~chung/SA/zz-Impreso-architecture_decisions-tyree-05.pdf">http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api</a></li> <li>REST API Quick Tips <a href="https://github.com/npryce/adr-tools">http://www.restapitutorial.com/lessons/restquicktips.html</a></li> <li>Django REST framework <a href="https://github.com/agis-/git-style-guide">http://www.django-rest-framework.org/</a></li> </ul> <h1 id=26-文件服务与业务服务隔离>26. 文件服务与业务服务隔离</h1> <p>Date: 06/05/2017</p> <h2 id=status-25>Status</h2> <p>Accepted</p> <h2 id=context-25>Context</h2> <ol> <li>当前存储方案有 3 种(FastDFS, nginx static, OSS),各自分别维护,人力成本高,都是单点,资源有效性无法保障;</li> <li>文件存储和业务服务共享服务器资源(CPU, 内存,带宽,磁盘 IO),服务器资源使用不合理,文件服务会占用大量内存和磁盘 IO 及网络 IO,影响业务,并且业务服务无法做高可用,遇到 DDOS 只能傻眼;</li> <li>面向用户的资源无法做加速;</li> <li>所有文件都是公开可访问,存在严重的安全问题(用户身份证照片、合同及报表数据的泄露)。</li> <li>所有敏感信息可被任何人全网下载;</li> </ol> <h2 id=decision-25>Decision</h2> <ol> <li>将所有文件存储和业务机器分离,将 FastDFS 配置单独机器提供服务;</li> <li>所有静态文件集中上云,录音,电子合同等静态文件上云;</li> <li>文件分权限访问,分配临时 token 去获取文件;</li> <li>css/js/images 等上云并配置 CDN,加速用户端访问。</li> </ol> <h2 id=consequences-25>Consequences</h2> <p>综合考虑了 Aliyun OSS 及七牛云,最终选择 OSS 是因为我们的服务都是基于 Aliyun ECS 的,使用 OSS 内网数据同步速度会快很多,并且内网通讯不收费。</p> <ol> <li>本地文件迁移至 Aliyun OSS (使用 ossimport2)注意事项: <ul> <li>宿主机内存消耗量大,磁盘读 IO 很高;</li> <li>需要写脚本进行文件比对,确认所有文件都同步成功。</li> </ul></li> <li>FastDFS 迁移注意事项: <ul> <li>同过配置多节点来进行新机器得同步;</li> <li>新机器需要 IO 优化的磁盘,否则整个数据同步瓶颈将在写磁盘操作上。</li> </ul></li> </ol> <p>Refs:</p> <ul> <li>ossimport2 Linux平台使用说明 <a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">https://help.aliyun.com/document_detail/32201.html?spm=5176.doc44075.2.11.I53UPo</a></li> </ul> <h1 id=27-消息队列>27. 消息队列</h1> <p>Date: 10/05/2017</p> <h2 id=status-26>Status</h2> <p>Accepted</p> <h2 id=context-26>Context</h2> <ol> <li>我们的很多业务都有这个需要,当前的一些定时任务已导致机器的产生瓶颈,很多业务之间的耦合性也很高;</li> <li>当前只有少量的业务在使用消息队列服务(activeMQ);</li> <li>activeMQ 对非 java 语言的支持并不友好;</li> <li>自己需要维护队列服务,做监控,高可用等。</li> </ol> <h2 id=decision-26>Decision</h2> <p>我们急需一个多语言支持且可靠的服务可以解决如上问题,即</p> <ul> <li>异步解耦</li> <li>削峰填谷</li> </ul> <p>Aliyun 的 MNS 和 ONS 功能的重合导致选择起来很困难,最终选择 MNS 源于以下几点。</p> <ol> <li>支持消息优先级;</li> <li>可靠性更高;</li> <li>文档更完善;</li> <li>服务更成熟;</li> <li>使用起来简单方便,定时消息不支持这点比较遗憾;</li> <li>ONS 使用起来有些复杂,监控方面的功能确实强大许多,但多数在开发与公测中;</li> <li>不好的点是各自都加了一些私活,MNS 加了自家的短信服务,ONS 加入了 MQTT 物联网套件,让 Q 看起来不单纯。</li> </ol> <h2 id=consequences-26>Consequences</h2> <p>使用 MNS 时需要确认以下几点:</p> <ul> <li><p>确认队列模型(支持一对一发送和接收消息)还是主题模型(支持一对多发布和订阅消息,并且支持多种消息推送方式)</p> <p><img src="files/password-manage.png" alt=""></p> <p><img src="files/branches.png" alt=""></p></li> <li><p>队列模型,需关注</p> <ol> <li>消息接收长轮询等待时间(0-30s);</li> <li>消息最大长度(1K-64K);</li> <li>消息存活时间(1min-15day);</li> <li>消息延时(0-7day);</li> <li>取出消息隐藏时长(1s-12hour);</li> </ol></li> <li><p>主题模型,需关注</p> <ol> <li>消息最大长度(1K-64K);</li> <li>消息可以加过滤标签;</li> </ol></li> </ul> <p>Refs:</p> <ul> <li>MNS 产品概述 <a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">https://help.aliyun.com/document_detail/27414.html?spm=5176.doc51077.6.539.XIqAPd</a></li> <li>消息服务MNS和消息队列ONS产品对比 <a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">https://help.aliyun.com/document_detail/27437.html?spm=5176.doc27475.6.655.piX01s</a></li> <li>SDK 下载地址:<a href="https://www.utdallas.edu/~chung/SA/zz-Impreso-architecture_decisions-tyree-05.pdf">https://help.aliyun.com/document_detail/32305.html</a></li> <li>Python 队列使用手册 <a href="https://github.com/npryce/adr-tools">https://help.aliyun.com/document_detail/32295.html?spm=5176.doc32305.6.667.mnHdf4</a></li> <li>Java 队列使用手册 <a href="https://github.com/agis-/git-style-guide">https://help.aliyun.com/document_detail/32449.html?spm=5176.doc32295.6.659.vWCLgJ</a></li> </ul> <h1 id=28-what-should-we-do-when-we-setup-a-new-server>28. What should we do when we setup a new server</h1> <p>Date: 11/05/2017</p> <h2 id=status-27>Status</h2> <p>Accepted</p> <h2 id=context-27>Context</h2> <p>Context here...</p> <h2 id=decision-27>Decision</h2> <p>Decision here...</p> <h2 id=consequences-27>Consequences</h2> <p>Refs:</p> <ul> <li>云服务器 ECS Linux SWAP 配置概要说明 <a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">https://help.aliyun.com/knowledge_detail/42534.html</a></li> <li>How To Add Swap on Ubuntu 14.04 <a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">https://www.digitalocean.com/community/tutorials/how-to-add-swap-on-ubuntu-14-04</a></li> </ul> <h1 id=29-本地-hosts-管理>29. 本地 hosts 管理</h1> <p>Date: 18/05/2017</p> <h2 id=status-28>Status</h2> <p>Accepted</p> <h2 id=context-28>Context</h2> <ol> <li>我们有多个测试环境(开发、测试、预发布及线上);</li> <li>我们的客户端为了避免针对不同环境做多次打包,使用了和线上一致的域名,所以当我们的 QA 需要测试不同环境时,需要手动更新每个 QA 的本地 hosts 文件;</li> <li>由于服务器及对应服务的调整,无法实时做到 hosts 的及时更新,也没法保证每个测试人员都做了更新(当前无通知,出问题后主要依靠问其他 QA 成员或咨询 Dev);</li> <li>部分线上服务未配置外网域名,比如 Boss 系统、Wiki 等,需要包括运营人员在内的所有人各自去配置本地 hosts。</li> </ol> <h2 id=decision-28>Decision</h2> <ol> <li>方案一:使用 SwitchHosts(Chosen) <ul> <li>可快速切换 hosts;</li> <li>支持集中式的 hosts 管理(在线);</li> <li>支持多 hosts 合并;</li> <li>支持多客户端。</li> </ul></li> </ol> <p>主界面如下,默认会将旧的 hosts 文件保存为 backup</p> <p><img src="files/password-manage.png" alt=""></p> <p>可以新建 hosts,比如测试环境一</p> <p><img src="files/branches.png" alt=""></p> <p>可以使用远程集中式管理的 hosts</p> <p><img src="files/bastion.png" alt=""></p> <p>最重要的是这些 hosts 可以通过同时打开各自开关将其合并使用。</p> <ol start="2"> <li>方案二:使用路由器 <ul> <li>只需切换不同的路由器即可进行不同环境的测试;</li> <li>配置办公网络路由器,需要 IT 人员来维护(暂无);</li> <li>只能办公室内进行访问。</li> </ul></li> </ol> <h2 id=consequences-28>Consequences</h2> <p>软件基于 Electron 开发,跨平台,Windows/Mac/Linus 客户端下载地址: <a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">https://pan.baidu.com/share/link?shareid=150951&amp;uk=3607385901#list/path=%2Fshare%2FSwitchHosts!&amp;parentPath=%2Fshare</a></p> <p>Refs:</p> <p>SwitchHosts Github: <a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">https://github.com/oldj/SwitchHosts</a></p> <h1 id=30-容量评估---存储>30. 容量评估 - 存储</h1> <p>Date: 2017-05-25</p> <h2 id=status-29>Status</h2> <p>Accepted</p> <h2 id=context-29>Context</h2> <ol> <li>一些需要高 IOPS 的服务,磁盘使用的是普通云盘,如,数据库,备份服务,图片服务等。</li> </ol> <h2 id=decision-29>Decision</h2> <ol> <li>明确存储的使用场景;</li> <li>关注吞吐量,IOPS和数据首次获取时间。</li> </ol> <p>我们的存储都是基于 Aliyun 的,他有以下类别及特点:</p> <ul> <li>nas(文件存储) <ul> <li>使用场景 <ul> <li>负载均衡共享存储和高可用</li> <li>企业办公文件共享(<strong>不支持本地挂载</strong>)</li> <li>数据备份</li> <li>服务器日志共享</li> </ul></li> <li>价格及吞吐能力 <ul> <li>2/G/M SSD性能型 60M/s</li> <li><strong>0.65/G/M 容量型 30M/s</strong></li> </ul></li> </ul></li> <li>disk(块存储、云盘) <ul> <li>使用场景 <ul> <li>普通云盘 <ul> <li>不被经常访问或者低 I/O 负载的应用场景</li> </ul></li> <li>高效云盘 <ul> <li>中小型数据库</li> <li>大型开发测试</li> <li>Web 服务器日志</li> </ul></li> <li>SSD 云盘 <ul> <li>I/O 密集型应用</li> <li>中大型关系型数据库</li> <li>NoSQL 数据库</li> </ul></li> </ul></li> <li>价格 <ul> <li>普通云盘 0.3/G/M</li> <li>高效云盘 0.35/G/M</li> <li>SSD 云盘 1/G/M</li> </ul></li> <li>吞吐量 <ul> <li>普通云盘 30MBps</li> <li>高效云盘 <strong>80MBps</strong></li> <li>SSD 云盘 256MBps</li> </ul></li> <li>IOPS <ul> <li>普通云盘 数百</li> <li>高效云盘 3000</li> <li>SSD 云盘 20000</li> </ul></li> <li>访问延迟 <ul> <li>普通云盘 5 - 10 ms</li> <li>高效云盘 1 - 3 ms</li> <li>SSD 云盘 0.5 - 2 ms</li> </ul></li> </ul></li> <li>oss(对象存储) <ul> <li>使用场景 <ul> <li>图片和音视频等应用的海量存储</li> <li>网页或者移动应用的静态和动态资源分离</li> <li>云端数据处理</li> </ul></li> <li>价格及吞吐能力 <ul> <li><strong>0.148/G/M 标准型 吞吐量大,热点文件、需要频繁访问的业务场景</strong> 大概 50M/s,类似高效云盘</li> <li><strong>0.08/G/M 低频访问型 数据访问实时,读取频率较低的业务场景</strong> Object 存储最低 30 天</li> <li>0.06/G/M 归档型 数据恢复有等待时间,数据有存储时长要求 Object 存储最低 30 天</li> </ul></li> </ul></li> <li>oas(归档存储) <ul> <li>使用场景 <ul> <li>低成本备份</li> <li>数据归档</li> <li>取代磁带</li> </ul></li> <li>价格及吞吐能力 <ul> <li>0.07/G/M 用户提取数据时能够容忍0-4小时的时间延迟</li> </ul></li> </ul></li> </ul> <h2 id=consequences-29>Consequences</h2> <ol> <li>加粗的信息可以重点查看下,同类别里比较推荐;</li> <li>我们选择时还要考虑价格及存储时长要求。</li> </ol> <p>Refs:</p> <ul> <li><a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">Server request and upgrade: capacity evaluation</a></li> <li>云盘参数和性能测试方法:<a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">https://help.aliyun.com/document_detail/25382.html</a></li> </ul> <h1 id=31-容量评估---内存>31. 容量评估 - 内存</h1> <p>Date: 2017-05-25</p> <h2 id=status-30>Status</h2> <p>Accepted</p> <h2 id=context-30>Context</h2> <ol> <li>机器内存太小了,需要升级一下;</li> <li>我们之前公司服务需要用多少多少;</li> <li>Java 程序最大最小堆的指定无标准。</li> </ol> <h2 id=decision-30>Decision</h2> <ul> <li>分析业务场景,明确我们到底需要多少内存,合理的预留1-2倍内存都没有问题;</li> <li>我们的业务目前分别由两种语言实现 Python 及 Java,Java 程序对内存的使用量非常大且监控不直观,为了合理分配内存,我们采取了以下分析方法。 <ul> <li>分配的最大内存用完后,GC 频率高且特定时间内无法做到垃圾回收,将会导致 <code>java.lang.OutOfMemoryError</code>;</li> <li>OOF,GC 频率及 GC 时间是确定 heap 参数的一个指标;</li> <li>线上不可能等到 OOF 时,才做升级,这样直接影响了系统的可用性,所以针对 Java 程序,一定要做好压力测试或对 JVM 做好监控(通过 Java VisualVM or JConsole),鉴于我们已用 Newrelic 栈,将有其通知我们服务的状况,Memory Analyzer 可以做更详细的变量级别内存使用查看;</li> </ul></li> <li>内存的不合理使用有:将大文件完整加载至内存,将整个表的数据读取至内存;</li> <li>内存泄漏:微观的有对象的引用问题,宏观的有连接未释放等;</li> <li>Xmx 设置后,对系统来说是已使用的,所以我们需要同时关注系统级别和 JVM 级别的内存使用情况。</li> </ul> <p><img src="files/password-manage.png" alt=""></p> <h2 id=consequences-30>Consequences</h2> <p>这篇文章的缘起是因为我们的一个同事发现自己使用的测试环境内存不够用,导致其他服务无法启动,并要求升级机器配置。当时的测试环境配置是:2核4G。出现问题前的操作是将 Xmx 由 1G 调整为 2G,通过分析发现是程序中加载了一个 7万条数据的大表导致,调整批量加载数据将以原先一半的内存解决此问题。</p> <p>Refs:</p> <ul> <li><a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">Server request and upgrade: capacity evaluation</a></li> <li>Spring Boot Memory Performance: <a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">https://spring.io/blog/2015/12/10/spring-boot-memory-performance</a></li> <li>How to control Java heap size (memory) allocation (xmx, xms):<a href="https://www.utdallas.edu/~chung/SA/zz-Impreso-architecture_decisions-tyree-05.pdf">http://alvinalexander.com/blog/post/java/java-xmx-xms-memory-heap-size-control</a></li> <li>What are the Xms and Xmx parameters when starting JVMs?:<a href="https://github.com/npryce/adr-tools">https://stackoverflow.com/questions/14763079/what-are-the-xms-and-xmx-parameters-when-starting-jvms</a></li> <li>JVM Tuning: Heapsize, Stacksize and Garbage Collection Fundamental:<a href="https://github.com/agis-/git-style-guide">https://crunchify.com/jvm-tuning-heapsize-stacksize-garbage-collection-fundamental/</a></li> <li>云监控内存使用率与Linux系统内存占用差异的原因:<a href="http://zhuanlan.51cto.com/art/201612/525719.htm">https://help.aliyun.com/knowledge_detail/38849.html</a></li> </ul> <h1 id=32-tcp-长连接高可用>32. TCP 长连接高可用</h1> <p>Date: 2017-05-25</p> <h2 id=status-31>Status</h2> <p>Accepted</p> <h2 id=context-31>Context</h2> <ol> <li>我们的一些智能设备,通过 TCP 和后端进行通信,上报数据及接收指令;</li> <li>智能设备由第三方提供,我们实现后端服务,当前支持域名和 IP 请求;</li> <li>随着未来设备数量的增长,我们的单台服务预计将无法满足;</li> <li>原方案是针对不同批次的智能设备,我们绑定不同的域名,已做客户的负载;</li> <li>存在设备使用的不可控引起服务端的使用率会存在问题;</li> <li>服务器出问题后服务的恢复时间受限于 DNS 更新的时间(切换新机器)。</li> </ol> <h2 id=decision-31>Decision</h2> <p><img src="files/password-manage.png" alt=""></p> <h2 id=consequences-31>Consequences</h2> <p>Refs:</p> <ul> <li>Aliyun 负载均衡 产品概述:<a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">https://help.aliyun.com/document_detail/27539.html</a></li> <li>Aliyun 负载均衡 基础架构:<a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">https://help.aliyun.com/document_detail/27544.html</a></li> <li>Aliyun 负载均衡 技术原理浅析:<a href="https://www.utdallas.edu/~chung/SA/zz-Impreso-architecture_decisions-tyree-05.pdf">https://help.aliyun.com/knowledge_detail/39444.html</a></li> <li>负载均衡服务TCP端口健康检查成功后返回RST包导致出现大量业务错误日志:<a href="https://github.com/npryce/adr-tools">https://help.aliyun.com/knowledge_detail/39464.html</a></li> <li>为什么不均衡:<a href="https://github.com/agis-/git-style-guide">https://help.aliyun.com/document_detail/27656.html</a></li> <li><a href="http://zhuanlan.51cto.com/art/201612/525719.htm">TCP接入层的负载均衡、高可用、扩展性架构</a></li> </ul> <h1 id=33-容量评估---mysql>33. 容量评估 - MySQL</h1> <p>Date: 2017-05-25</p> <h2 id=status-32>Status</h2> <p>Accepted</p> <h2 id=context-32>Context</h2> <p>QPS: 每秒钟查询量。如果每秒钟能处理 100 条查询 SQL 语句,那么 QPS 就约等于 100 TPS: 每秒钟事务处理的数量</p> <h2 id=decision-32>Decision</h2> <h3 id=和-mysql-性能相关的几个指标-32>和 MySQL 性能相关的几个指标</h3> <ul> <li>CPU <ul> <li>对于 CPU 密集型的应用,我们需要加快 SQL 语句的处理速度。由于MySQL 的 SQL 语句处理是单线程的,因此我们需要更好的 CPU,而不是更多的cpu</li> <li>一个 CPU 同时只能处理一条 SQL 语句。所以高并发量的情况下,就需要更多的 CPU 而不是更快的 CPU。</li> </ul></li> <li>内存 <ul> <li>把数据缓存到内存中读取,可以大大提高性能。常用的 MySQL 引擎中,MyISAM 把索引缓存到内存,数据不缓存。而InnoDB 同时缓存数据和索引</li> </ul></li> <li>磁盘 <ul> <li>MySQL 对磁盘 IO 的要求比较高,推荐高性能磁盘设备,比如,Aliyun 就推荐使用其 SSD,而不是普通云盘和高效云盘,当然 SSD 这个介质的可靠性,我们也需要考虑</li> <li>MySQL 实例应该独享,尤其不能和其他磁盘 IO 密集型任务放在一起</li> </ul></li> <li>网络 <ul> <li>一般数据库服务都部署在内网,带宽影响不大,避免使用外网连接数据库</li> <li>外网查询,尤其避免使用 <code>select *</code> 进行查询</li> <li>从库如果跨地域,走外网,则尽量减少从库数量。</li> </ul></li> </ul> <h3 id=影响数据库性能的因素及应对方式-32>影响数据库性能的因素及应对方式</h3> <ul> <li>高并发 <ul> <li>数据库连接数被占满</li> <li>对于数据库而言,所能建立的连接数是有限的,MySQL 中<code>max_connections</code> 参数默认值是 100</li> </ul></li> <li>大表 <ul> <li>记录行数巨大,单表超过千万行</li> <li>表数据文件巨大,表数据文件超过10G</li> <li>影响 <ul> <li>慢查询:很难在一定的时间内过滤出所需要的数据</li> <li>DDL 操作、建立索引需要很长的时间:MySQL 版本 &lt;5.5 建立索引会锁表,&gt;=5.5 虽然不会锁表但会引起主从延迟</li> <li>修改表结构需要很长时间锁表:会造成长时间的主从延迟;影响正常的数据操作</li> </ul></li> <li>处理 <ul> <li>分库分表</li> <li>历史数据归档</li> </ul></li> </ul></li> <li>大事务 <ul> <li>运行时间比较长,操作数据比较多的事务</li> <li>影响 <ul> <li>锁定太多数据,造成大量的阻塞和锁超时</li> <li>回滚时需要的时间比较长</li> <li>执行时间长,容易造成主从延迟</li> </ul></li> <li>处理 <ul> <li>避免一次处理太多的数据</li> <li>移出不必要在事务中的select操作</li> </ul></li> </ul></li> </ul> <h2 id=consequences-32>Consequences</h2> <p>鉴于我们使用了 Aliyun MySQL,他有完善的监控项,CPU、内存、磁盘、连接数及网络流量,关注各个指标并针对其做好报警策略即可</p> <p>Refs:</p> <ul> <li>什么影响了MySQL性能 <a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">http://blog.csdn.net/u011118321/article/details/54694262</a></li> <li>哪些因素影响了数据库性能 <a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">http://blog.csdn.net/u011118321/article/details/54692454</a></li> <li>Aliyun RDS 产品概述 <a href="https://www.utdallas.edu/~chung/SA/zz-Impreso-architecture_decisions-tyree-05.pdf">https://help.aliyun.com/document_detail/26092.html</a></li> <li>使用RDS不得不知的注意事项 <a href="https://github.com/npryce/adr-tools">https://help.aliyun.com/knowledge_detail/41872.html</a></li> <li>阿里云RDS上的一些概念性记录 <a href="https://github.com/agis-/git-style-guide">http://www.cnblogs.com/olinux/p/5563584.html</a></li> </ul> <h1 id=34-dns-笔记>34. DNS 笔记</h1> <p>Date: 2017-06-03</p> <h2 id=status-33>Status</h2> <p>Accepted</p> <h2 id=context-33>Context</h2> <ol> <li>网站被 DDOS 需要考虑切换 DNS 解析;</li> <li>负载均衡服务切换服务器,需要更新 DNS 解析;</li> <li>新加子域名,需要配置 DNS 解析。</li> </ol> <h2 id=decision-33>Decision</h2> <p>DNS 解析的同步需要时间,涉及以下几点:</p> <ol> <li>DNSPod 生效时间,一般在 30s 以内;</li> <li>各个 ISP DNS 服务器刷新时间;</li> <li>域名 TTL (用户本地缓存时间)。</li> </ol> <p>针对全球性业务,保险起见,我们等待一天以上。DNSPod 给出的说法是,域名解析通常需 24 小时至 72 小时才能全球完全同步。大多数业务正常情况以 TTL 为依据即可。</p> <h2 id=consequences-33>Consequences</h2> <p>一种域名解析更新策略是,现将旧的域名解析 TTL 设为最小值,等待一天,确保解析都已完全同步,这个完全不影响现有业务。将 DNS 解析更新到新的记录,这个时候 DNS 服务器将以最快的速度进行同步更新;确认都更新完毕后,我们将 TTL 设为较长时间,确保 DNS 解析的稳定性。</p> <p>Refs:</p> <ul> <li>有关DNSPod常见问题汇总: <a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">https://www.douban.com/group/topic/26842738/</a></li> <li>DNS解析过程及DNS TTL值: <a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">http://www.xiaoxiaozi.com/2013/04/23/2409/</a></li> </ul> <h1 id=35-关于灾难恢复>35. 关于灾难恢复</h1> <p>Date: 2017-06-05</p> <h2 id=status-34>Status</h2> <p>Proposed</p> <h2 id=context-34>Context</h2> <p>当前我们使用的是华北2可用区A机房(即北京昌平区的一个机房)部署了所有服务,存在以下几个问题,出现概率逐级减少:</p> <ol> <li>服务本身部署在单台机器,单机的故障会导致服务的不可用,这个我们的业务服务频频出现;</li> <li>所有服务部署于一个机房,机房电力,网络出现故障,将导致服务完全不可用,这个 2016 年中旬我们使用的 Aliyun 机房网络设备出现过一次问题,导致服务停服 1 小时左右(官方),实际对我们的影响在 12 个小时左右;</li> <li>北京发生各种灾害,殃及所有机房,导致服务不可用。</li> </ol> <h3 id=基础概念-34>基础概念</h3> <p>灾难恢复(Disaster recovery,也称灾备),指自然或人为灾害后,重新启用信息系统的数据、硬件及软体设备,恢复正常商业运作的过程。灾难恢复规划是涵盖面更广的业务连续规划的一部分,其核心即对企业或机构的灾难性风险做出评估、防范,特别是对关键性业务数据、流程予以及时记录、备份、保护。</p> <p>地域,即城市,不同的地域可以做到自然灾害级别的灾备,之间延迟较高</p> <p>可用区,即机房,不同的可用区可以做到电力和网络设备互相独立,之间有少量延迟</p> <p>两地三中心,业界目前最可靠的解决方案,即在两个城市共三个机房中部署服务</p> <h3 id=灾备的两项指标-34>灾备的两项指标</h3> <p>RTO - Recovery Time Objective,它是指灾难发生后,从 IT 系统宕机导致业务停顿之时开始,到 IT 系统恢复至可以支持各部门运作、恢复运营之时,此两点之间的时间段称为 RTO</p> <p>RPO - Recovery Point Objective,是指从系统和应用数据而言,要实现能够恢复至可以支持各部门业务运作,系统及生产数据应恢复到怎样的更新程度,这种更新程度可以是上一周的备份数据,也可以是上一次交易的实时数据</p> <h3 id=两地三中心-34>两地三中心</h3> <p><img src="files/password-manage.png" alt=""></p> <ul> <li>主系统 <ul> <li>即当前对外提供服务的机房</li> <li>首先要做到自身的高可用,所有服务不因单机故障导致服务不可用</li> <li>无资源浪费,多一些部署和维护成本</li> </ul></li> <li>同城灾备 <ul> <li>单个城市多个机房,解决单机房电力或网络故障导致的服务不可用</li> <li>主备的方式会有一半的资源浪费,双活的方式对服务有一定的延迟</li> <li>有一定的部署和维护成本</li> </ul></li> <li>异地灾备 <ul> <li>即跨城市部署服务,解决自然灾害等引起的服务不可用</li> <li>由于延迟的原因,这部分资源属于备用服务,仅在发生灾害是激活</li> <li>平时资源都是浪费,并且有较高的部署和维护成本</li> </ul></li> </ul> <h2 id=decision-34>Decision</h2> <ol> <li>同机房的服务高可用(进行中),这个是目前最高优先级;</li> <li>同城双活(提议中),可以解决大部分我们遇到的机房问题;</li> <li>异地灾备(暂不考虑),针对支付业务,当涉及合规性时,我们得考虑下;</li> <li>明确我们各个服务的重要程度,分服务针对性的做高可用及灾备策略。</li> </ol> <h2 id=consequences-34>Consequences</h2> <p>Refs:</p> <ul> <li>灾难恢复 <a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">https://zh.wikipedia.org/wiki/%E7%81%BE%E9%9A%BE%E6%81%A2%E5%A4%8D</a></li> <li>Aliyun 地域和可用区 <a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">https://help.aliyun.com/knowledge_detail/40654.html</a></li> <li>阿里云华北2区网络故障导致业务中断1小时 <a href="https://www.utdallas.edu/~chung/SA/zz-Impreso-architecture_decisions-tyree-05.pdf">http://www.sohu.com/a/101817812_401503</a></li> <li>因电缆井被烧,京津宁骨干网中断 <a href="https://github.com/npryce/adr-tools">http://www.sohu.com/a/131579749_465914</a></li> <li>经历不可抗力是一种什么体验 <a href="https://github.com/agis-/git-style-guide">https://zhuanlan.zhihu.com/p/26855422</a></li> <li>金融云特性 <a href="http://zhuanlan.51cto.com/art/201612/525719.htm">https://help.aliyun.com/document_detail/29851.html</a></li> <li>云上场景:众安保险,两地三中心容灾部署实践 <a href="https://segmentfault.com/a/1190000004634172">https://yq.aliyun.com/articles/6633</a></li> </ul> <h1 id=36-关于-mysql-高可用>36. 关于 MySQL 高可用</h1> <p>Date: 2017-06-06</p> <h2 id=status-35>Status</h2> <p>Proposed</p> <h2 id=context-35>Context</h2> <ol> <li>数据库版本 5.1,太旧,性能,安全,主从复制都存在问题;</li> <li>数据库部署在 ECS 上,但磁盘使用的是普通云盘,IOPS 已到阈值(优先级最高);</li> <li>数据库一主两从,但无高可用;</li> <li>业务端使用 IP 连接主数据库。</li> </ol> <h2 id=decision-35>Decision</h2> <ol> <li>提交 Aliyun 工单,尝试是否能申请下 5.1 版本的 MySQL,迁移数据至 RDS,解决 2,3,4 问题(沟通后,5.1 版本已不再提供,PASS);</li> <li>将部分数据库迁移出,缓解当前 MySQL 服务器压力,维护多个数据库实例(并未解决实际问题,PASS,当前压力最终确认是慢查询原因);</li> <li>ECS 上自建 HA,并启用新的实例磁盘为 SSD,切换新实例为 Master,停掉旧实例(根本问题未解决,技术债一直存在,自行维护仍然存在风险点);</li> <li>调研 5.5 和 5.1 的差异,直接迁移自建数据库至 Aliyun RDS MySQL 5.5。</li> </ol> <p>鉴于查看文档后, 5.1 到 5.5 的差异性影响不大,Aliyun 官方也支持直接 5.1 到 5.5 的迁移,所以计划直接迁移至 RDS 的 5.5 版本。</p> <p>为了杜绝风险:</p> <ol> <li>按业务分数据库分别迁移;</li> <li>所有迁移先走测试数据库,由 QA 做完整的测试。</li> </ol> <p>ECS self built MySQL 5.1 to RDS 5.5 with DTS 迁移流程:</p> <ol> <li>在 RDS 中创建原 MySQL 数据库对应的账号(各个项目账号独立);</li> <li>更新白名单:添加项目所部署的服务器;</li> <li>明确数据规模,对同步时间做个预期;</li> <li>同步(全量 or 增量),明确无延迟状态;</li> <li>更新数据库连接配置文件;</li> <li>明确无延迟状态,停服;</li> <li>确定数据量一致(由预先写好的脚本判断)(1min);</li> <li>关闭迁移服务(10s);</li> <li>重启服务器(10s)。</li> </ol> <p>6 至 9 步决定我们的停服时间。</p> <p>鉴于我们使用从库作为迁移的数据源,需更新如下配置:</p> <ul> <li>log-slave-updates=1</li> <li>binlog-format=row</li> </ul> <h2 id=consequences-35>Consequences</h2> <p>同步过程中出现如下问题,请周知:</p> <ol> <li>判断脚本出问题,未准备好脚本命令;</li> <li>终端出问题,更改命令麻烦;</li> <li>配置信息直接在生产环境更改,应走 github 提交;</li> <li>停服那步影响其他业务;</li> <li>从库使用者是否受影响,如数据组。</li> </ol> <p>Refs:</p> <ul> <li>MySQL upgrade from MySQL 5.1 to MySQL 5.5 <a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">http://www.ineedwebhosting.co.uk/blog/mysql-upgrade-from-mysql-5-1-to-mysql-5-5/</a></li> <li>Mysql时间字段格式如何选择,TIMESTAMP,DATETIME,INT?<a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">https://segmentfault.com/q/1010000000121702</a></li> <li>Changes Affecting Upgrades to MySQL 5.5 <a href="https://www.utdallas.edu/~chung/SA/zz-Impreso-architecture_decisions-tyree-05.pdf">https://dev.mysql.com/doc/refman/5.5/en/upgrading-from-previous-series.html</a></li> <li>Aliyun RDS 访问控制 <a href="https://github.com/npryce/adr-tools">https://help.aliyun.com/document_detail/53617.html</a></li> <li>Mysql log_slave_updates 参数 <a href="https://github.com/agis-/git-style-guide">http://www.cnblogs.com/zejin2008/p/4656251.html</a></li> <li>Mysql数据库主从心得整理 <a href="http://zhuanlan.51cto.com/art/201612/525719.htm">http://blog.sae.sina.com.cn/archives/4666</a></li> <li>即使删了全库,保证半小时恢复: <a href="https://segmentfault.com/a/1190000004634172">http://mp.weixin.qq.com/s?__biz=MjM5ODYxMDA5OQ==&amp;mid=2651959694&amp;idx=1&amp;sn=4ac53b797fca64229901373e793f860a</a></li> </ul> <h1 id=37-通过代理解决白名单问题>37. 通过代理解决白名单问题</h1> <p>Date: 2017-06-07</p> <h2 id=status-36>Status</h2> <p>Accepted</p> <h2 id=context-36>Context</h2> <ol> <li>我们的支付及财务业务,需要向第三方金融机构发起请求,第三方机构出于安全性考虑,需要将我们的服务器 IP 地址进行报备;</li> <li>第三方机构较多,针对服务器扩容,更换,报备一次比较麻烦;</li> <li>第三方机构审核时间不定,1 天到多天不定,关键时刻影响业务。</li> </ol> <h2 id=decision-36>Decision</h2> <p>正向代理是一个位于客户端和目标服务器之间的代理服务器(中间服务器)。为了从原始服务器取得内容,客户端向代理服务器发送一个请求,并且指定目标服务器,之后代理向目标服务器转交并且将获得的内容返回给客户端。正向代理的情况下客户端必须要进行一些特别的设置才能使用。</p> <p>常见场景:</p> <p><img src="files/password-manage.png" alt=""></p> <p>反向代理正好相反。对于客户端来说,反向代理就好像目标服务器。并且客户端不需要进行任何设置。客户端向反向代理发送请求,接着反向代理判断请求走向何处,并将请求转交给客户端,使得这些内容就好似他自己一样,一次客户端并不会感知到反向代理后面的服务,也因此不需要客户端做任何设置,只需要把反向代理服务器当成真正的服务器就好了。</p> <p>常见场景:</p> <p><img src="files/branches.png" alt=""></p> <p>方案:</p> <ol> <li>使用正向代理; <ul> <li>这个场景最容易想到的方案,使用起来直观,易懂;</li> <li>需要每个客户端进行配置,或是在应用中对单个请求做代理配置;</li> <li>需要维护一个高可用的代理服务,并备案此代理服务器。</li> </ul></li> <li>使用反向代理。 <ul> <li>在我们的服务器上做对方服务的反向代理(听起来有点绕,不直观)</li> <li>维护简单,就像是我们用 nginx/slb 为对方做了个负载均衡,但配置稍有不同;</li> </ul></li> </ol> <pre><code class="language-json">server { server_name {{ proxy_info.server_name }}; listen {{ proxy_info.ssl_listen }}; location / { proxy_pass_header Server; proxy_pass {{ proxy_info.proxy_url }}; proxy_redirect off; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Scheme $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } </code></pre> <ul> <li>使用简单,使用方配置本机 hosts 即可,为对方域名和代理 IP 映射。</li> </ul> <ol start="3"> <li>iptables <ul> <li>类似局域网共享上网;</li> <li>对 iptables 配置有要求;</li> <li>目标域名对应的 ip 地址改变,需要更新配置。</li> </ul></li> </ol> <p>最终我们通过 aliyun slb 的4层负载接两台部署了 ss5 的机器提供高可用的代理服务</p> <ul> <li>4层(TCP协议)服务中,当前不支持添加进后端云服务器池的ECS既作为Real Server,又作为客户端向所在的负载均衡实例发送请求。</li> <li>ss5 启动于内网地址即可</li> <li>ss5 配置需关注 AUTHENTICATION 和 AUTHORIZATION</li> </ul> <h2 id=consequences-36>Consequences</h2> <p>Refs:</p> <ol> <li>云服务器 ECS Linux 系统通过 Squid 配置实现代理上网 <a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">https://help.aliyun.com/knowledge_detail/41342.html</a></li> <li>正向代理与反向代理的区别 <a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">http://www.jianshu.com/p/208c02c9dd1d</a></li> <li>设置 iptables 使用linux做代理服务器 <a href="https://www.utdallas.edu/~chung/SA/zz-Impreso-architecture_decisions-tyree-05.pdf">https://www.l68.net/493.html</a></li> <li>SS5 <a href="https://github.com/npryce/adr-tools">http://ss5.sourceforge.net/project.htm</a></li> </ol> <h1 id=38-数据脱敏>38. 数据脱敏</h1> <p>Date: 2017-06-13</p> <h2 id=status-37>Status</h2> <p>Accepted</p> <h2 id=context-37>Context</h2> <ol> <li>数据目前交由服务后台或前端进行敏感信息处理,原始数据存在多种风险(外部脱裤,内部人员非必要性的查看等);</li> <li>各个 Team 数据加密策略不一致(有 MD5, AES etc);</li> <li>数据掩码方式也不统一。</li> </ol> <h2 id=decision-37>Decision</h2> <p>使用四个策略的结合:</p> <ol> <li>掩码 - 业务系统需要查看部分内容,已核对信息,日志中为了便于定位;</li> <li>替换 - 字段实际不被使用,但保留字段,并将数据替换为空内容;</li> <li>可逆加密 - AES(ECB/PKCS5Padding - 128)</li> <li>不可逆加密 - SHA1</li> </ol> <p>策略的使用需考虑,使用场景(生产、测试等环境),成本(对人员、服务器的需求),是否易用(影响开发效率),维度(目前就分两种:机密和公开)</p> <p>掩码规则:</p> <ul> <li>姓名 - <code>*斌</code> - 保留最后一个字,其余部分统一为一个星号</li> <li>电话 - <code>131****0039</code> - 中间4~7位每个字符替换为一个星号</li> <li>身份证号 - <code>**************1234</code> - 保留后四位,其余部分每个字符替换为一个星号</li> <li>银行卡号 - <code>3111111******1234</code> - 保留前六、后四位,其余部分每个字符替换为一个星号</li> <li>地址 - ``</li> <li>邮箱 - ``</li> <li>密码 - ``</li> <li>交易金额 - ``</li> <li>充值码 - ``</li> </ul> <p>两个原则:</p> <ol> <li>remain meaningful for application logic(尽可能的为脱敏后的应用,保留脱敏前的有意义信息)</li> <li>sufficiently treated to avoid reverse engineer(最大程度上防止黑客进行破解)</li> </ol> <h2 id=consequences-37>Consequences</h2> <p>Refs:</p> <ul> <li><a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">动态数据脱敏最佳实践.pdf</a></li> <li>美团数据仓库-数据脱敏 <a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">http://tech.meituan.com/data-mask.html</a></li> <li>大数据与数据脱敏 <a href="https://www.utdallas.edu/~chung/SA/zz-Impreso-architecture_decisions-tyree-05.pdf">https://zhuanlan.zhihu.com/p/20824603</a></li> <li>加解密详解 <a href="https://github.com/npryce/adr-tools">http://www.jianshu.com/p/b3be35c1d424</a></li> <li>大数据隐私保护技术之脱敏技术探究 <a href="https://github.com/agis-/git-style-guide">http://www.freebuf.com/articles/database/120040.html</a></li> </ul> <h1 id=39-秘钥管理>39. 秘钥管理</h1> <p>Date: 2017-06-14</p> <h2 id=status-38>Status</h2> <p>Accepted</p> <h2 id=context-38>Context</h2> <ol> <li>目前有相当多的账户、密码等信息存储在项目配置文件中;</li> <li>部分项目将敏感信息和项目分离,但所部署的服务器还是能被所有人登录查看;</li> <li>将服务器登录权限限制在运维手中,需要运维人员维护所有敏感信息的存储与管理,数量线性增长,尤其是支付组涉及的敏感信息更多,每一个新项目都需要运维人员的参与和维护。</li> </ol> <h2 id=decision-38>Decision</h2> <ol> <li>将服务器登录权限限制在个别人的手中;</li> <li>使用密码管理服务,确保运维人员只需维护一个秘钥;</li> <li>使用 Aliyun KMS 而不是自己搭建,节约运维成本。</li> </ol> <p>直接使用KMS加密、解密</p> <p><img src="files/password-manage.png" alt=""></p> <p>结合我们的需求,我们选用这种方式,使用方式如下</p> <pre><code class="language-python">import json from aliyunsdkcore.client import AcsClient from aliyunsdkkms.request.v20160120 import EncryptRequest, DecryptRequest OLD = 'password' NEW = '<KEY> client = AcsClient('id', 'secret', 'cn-beijing') def en(): request = EncryptRequest.EncryptRequest() request.set_KeyId('<KEY>') request.set_Plaintext(OLD) response = client.do_action_with_exception(request) print json.loads(response)['CiphertextBlob'] def de(): request = DecryptRequest.DecryptRequest() request.set_CiphertextBlob(NEW) response = client.do_action_with_exception(request) print json.loads(response)['Plaintext'] == OLD if __name__ == '__main__': de() </code></pre> <p>使用信封加密在本地加密、解密</p> <p><img src="files/branches.png" alt=""></p> <p><img src="files/bastion.png" alt=""></p> <h2 id=consequences-38>Consequences</h2> <ol> <li>直接使用KMS加密、解密会影响启动速度;</li> <li>一个明文多次加密,产生的密文不同,但所有密文都可以解密为明文。</li> </ol> <p>Refs:</p> <ul> <li>使用场景 <a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">https://help.aliyun.com/document_detail/28937.html</a></li> <li>什么是信封加密?<a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">https://help.aliyun.com/knowledge_detail/42339.html</a></li> <li>Python SDK使用说明 <a href="https://www.utdallas.edu/~chung/SA/zz-Impreso-architecture_decisions-tyree-05.pdf">https://help.aliyun.com/document_detail/53090.html</a></li> <li>KMS SDK source: <a href="https://github.com/npryce/adr-tools">https://github.com/aliyun/aliyun-openapi-python-sdk/tree/master/aliyun-python-sdk-kms/aliyunsdkkms/request/v20160120</a></li> <li>结合KMS实现本地文件加解密 <a href="https://github.com/agis-/git-style-guide">https://help.aliyun.com/video_detail/54134.html</a></li> <li>JAVA SDK样例代码 <a href="http://zhuanlan.51cto.com/art/201612/525719.htm">https://help.aliyun.com/document_detail/43347.html</a></li> </ul> <h1 id=40-agile---daily-standup-meeting>40. Agile - Daily standup meeting</h1> <p>Date: 2017-06-16</p> <h2 id=status-39>Status</h2> <p>Accepted</p> <h2 id=context-39>Context</h2> <ol> <li>Team <code>devops</code> set up recently, we need some change to improve the performance;</li> <li>No communication in the team, always person to person;</li> <li>Tasks not organized well which spread among different projects;</li> <li>Some teams require daily reports for their management, but lose the communication between team members.</li> </ol> <h2 id=decision-39>Decision</h2> <p>We're going to have 10 minutes daily standup meetings with each team so that We're on the same page about what everyone in the team is working on and we can strategize on how to approach the work items on the board for the day to come.</p> <p>Effective standups are all about communication and commitment, not about status updates. So before every scrum take 5 minutes to actually think and note down what you were planning to accomplish yesterday, did you actually accomplish what you've committed to, if not why?</p> <p>Take some time to plan your day and decide what you're going to accomplish today, commit to it and state it to the team (not the management), so the team members will keep each other accountable for the commitments they make to make the whole team improve together and make sure to remove impediments that prevent team members to accomplish what they plan.</p> <p>Scrum master should pay more attention to the status of each card, encourage team members to deploy in time.</p> <p>We change scrum master every two week to make sure all team members understand the details as an owner.</p> <h3 id=keynotes-39>Keynotes</h3> <ul> <li>Safe time - make sure everyone free that time;</li> <li>Everyone should standup;</li> <li>Focus - Every should watching the board;</li> <li>Less than 10 minutes for the whole meeting;</li> <li>One minute per person, no more than two minutes;</li> <li>Remove impediments;</li> <li>What done yesterday;</li> <li>What will do today.</li> </ul> <h2 id=consequences-39>Consequences</h2> <p>Everyone in the team will know each other better.</p> <p>Refs:</p> <ul> <li>Episode 66 – Standups <a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">http://www.thisagilelife.com/66/</a></li> </ul> <h1 id=41-mysql-迁移-rds-总结>41. MySQL 迁移 RDS 总结</h1> <p>Date: 2017-07-17</p> <h2 id=status-40>Status</h2> <p>Accepted</p> <h2 id=context-40>Context</h2> <ol> <li>当前数据库为 Master, Slave 模式;</li> <li>Master 实例上创建了 16 个数据库,全部需要迁移;</li> <li>部分业务存在跨库查询;</li> <li>有一个数据库被近 10 个业务进行查询等数据库操作;</li> <li>当前数据库为 MySQL 5.1,存在主从同步性能问题;</li> <li>RDS 仅支持 MySQL 5.5, 5.6, 5.7 版本;</li> </ol> <h2 id=decision-40>Decision</h2> <ol> <li>调研 MySQL 5.1 与 5.5 之间的差异,并周知各个项目组成员;</li> <li>将数据库与业务之间的引用关系用二维表列举出来;</li> <li>选出被业务单独或少量引用的数据库,先通过将对应测试数据库进行迁移,并交由测试人员进行测试;</li> <li>测试完成后对正式环境直接进行迁移;</li> <li>针对被10多个业务引用的数据库迁移,我们不止要做测试环境的迁移,还要做线上环境的测试 <ol> <li>为了保证线上测试可回滚,我们需限定只有测试人员进行操作; <ol> <li>限制我们的服务器安全组,外网只能通过办公网络访问;</li> <li>限制我们的入口 slb,只能通过办公网络访问。</li> </ol></li> <li>我们的服务之间存在调用关系,部分业务走的外网域名; <ol> <li>准备我们所有外网业务的域名及其内网 ip 映射,通过 ansible 分发并追加其至所有的线上机器 hosts</li> </ol></li> <li>所有业务准备好分支 feature/db-config-update-to-rds,此分支与 master 分支差异只有数据库配置改动,冻结 master 新代码合入,如此确保随时可上线,随时可回滚;</li> <li>创建数据库迁移任务: 结构迁移+整体数据+增量数据迁移;</li> <li>停止并备份任务计划调度(/etc/crontab,cron.d,/var/spool/cron);</li> <li>停止所有业务服务;</li> <li>停止所有 nginx;</li> <li>脚本验证所有机器上的服务和任务计划,确保无运行中相关程序;</li> <li>验证无数据库连接;</li> <li>锁定原数据库写操作(验证确认确实不可写)</li> <li>网络隔离;</li> <li>检查源数据库与目的数据库 数据一致性;</li> <li>停止数据迁移任务;</li> <li>停止主db数据库服务;</li> <li>启动RDS到从库的数据同步任务;</li> <li>重启所有服务;</li> <li>重启 nginx;</li> <li>测试团队开始全面验证;</li> <li>网络隔离解除;</li> <li>恢复任务计划;</li> <li>重新执行停服期间计划任务。</li> </ol></li> </ol> <h2 id=consequences-40>Consequences</h2> <ol> <li>RDS 磁盘预留过低,导致同步中途停止,无法进行写操作;</li> <li>一些业务需要回调,测试不完整;</li> <li>如果有完整的预发布环境,可保证服务零停机时间;</li> </ol> <h1 id=42-agile---retrospective-meeting>42. Agile - Retrospective meeting</h1> <p>Date: 2017-07-31</p> <h2 id=status-41>Status</h2> <p>Accepted</p> <h2 id=context-41>Context</h2> <ol> <li>Team members know little about last iteration and don’t know which part is good, bad or need improve;</li> <li>New team members know nothing about the team’s history and don’t know the best practices for this team;</li> <li>We need learn from what we done.</li> </ol> <h2 id=decision-41>Decision</h2> <h3 id=description-41>Description</h3> <p>After each iteration we'll spend one hour discussing relevant topics we add during the iteration in our retrospective board.</p> <p>The idea is to spend quality time and get the most value out of this meeting, therefore each team member is encouraged to bring discussion topics as well as suggestion for improvement.</p> <h3 id=preparation-41>Preparation</h3> <ul> <li>The SM marks the current iteration as finished, moving all the unfinished tasks to the new iteration;</li> <li>Check the dashboard and analyze our metrics for the last finished iteration. Find out all problematic tasks with <code>low Flow Efficiency</code> or <code>low Quality Score</code>;</li> <li>Safety check;</li> <li>The SM remind team members in team channel at least 10 minutes before starting the meeting; <ul> <li>Everyone is available;</li> <li>Everyone is encouraged to prepared the <code>Good</code>,<code>Bad</code> and <code>Need improve</code> cards; <ul> <li>Something that went well or wrong;</li> <li>Any type of improvement suggestion you might think of. Regarding the process, the code base, the collaboration etc.</li> </ul></li> <li>Add description/comments to existing ones;</li> <li>Votes(optional);</li> </ul></li> </ul> <h3 id=process-41>Process</h3> <ul> <li>Discuss problematic tasks that have bad metrics, in order to understand how we can improve; <ul> <li>Identify the root cause of the problem;</li> <li>Come up with ideas about how we could have done it better, so that we can learn from our mistakes;</li> </ul></li> <li>The SM prioritizes the topics, based on team member's votes (optional);</li> <li>Follow up on the previous iteration's discussion (optional);</li> <li>Follow up on existing action items;</li> <li>During the meeting the SM records the outcomes and action items in our retrospective board;</li> <li>At the end of the meeting we should save 10 min for a brief overview of the past iteration(recently completed features, features in progress, planed features, velocity graphs and user story vs bugs graphs)</li> </ul> <h3 id=notice-41>Notice</h3> <ul> <li>Starts on time and all the team members must participate;</li> <li>Discuss the accumulated cards in our Backlog, 5 minutes/card;</li> <li>Each topic is time-boxed. However after the 5min timer expires, if everyone agrees we need further discussion, we restart the timer one more time.</li> <li>Anybody can stop the current discussion if it's clear we're going nowhere;</li> <li>We keep the retrospective meetings within 1 hour.</li> </ul> <h2 id=consequences-41>Consequences</h2> <p>Everyone will learn from history, and not make same error twice.</p> <h1 id=43-支持过滤的消息队列>43. 支持过滤的消息队列</h1> <p>Date: 2017-08-18</p> <h2 id=status-42>Status</h2> <p>Accepted</p> <h2 id=context-42>Context</h2> <p>最近需要优化这样的场景,我们的合同状态有多种(待完善,待审核,审核通过,审核不通过等),每种状态的改变来自多个地方(中介后台,运营后台,风控系统等),每种状态的处理也来自多个地方(SAAS系统,中介后台,运营系统等),且处理者需要处理的状态不相同;</p> <p>当前实现方案是:</p> <ol> <li>定时任务,各个系统定时处理状态为 X 的合同(处理不及时);</li> <li>使用回调,状态更新时回调至处理者处(扩展不方便);</li> </ol> <h2 id=decision-42>Decision</h2> <ol> <li><p>消息服务(MNS) 主题模型</p> <p><img src="files/password-manage.png" alt=""></p> <ul> <li>可订阅,并且可以通过 Tag 进行消息过滤;</li> <li>只支持推送模式,每个消费者需要创建回调接口;</li> <li>只支持外网地址推送,对内部服务来说,网络耗时太高。</li> </ul></li> <li><p>消息服务(MNS) 队列模型</p> <p><img src="files/branches.png" alt=""></p> <ul> <li>根据消费者创建队列,几个消费者就创建几个队列;</li> <li>生产者根据消费者所需向其队列发送消息,即生产者需要发送相同消息至多个队列;</li> <li>每增加一个消费者,都需更新所有对应生产者的代码,维护性太低。</li> </ul></li> <li><p>消息服务(MNS) 主题+队列模型</p> <p><img src="files/bastion.png" alt=""></p> <ul> <li>根据消费者创建队列,几个消费者就创建几个队列;</li> <li>生产着只需向主题队列发送消息,&lt;del&gt;消费者队列订阅所有主题队列的消息&lt;/del&gt;;</li> <li>&lt;del&gt;消费者需要接收所有消息,并在业务逻辑中过滤出自己需要处理的消息&lt;/del&gt;;</li> <li>消费者队列可以按 tag 进行过滤;</li> <li>消费者完整消费自己的队列即可。</li> </ul></li> <li><p>消息队列(ONS) MQ</p> <p><img src="files/message-filter.png" alt=""></p> <ul> <li>总共只需一个 topic 队列,各个消费者通过 Tag 进行过滤;</li> <li>完美支持我们的使用场景;</li> <li>不提供 Python SDK。</li> </ul></li> </ol> <h2 id=consequences-42>Consequences</h2> <ul> <li>方案 1,2 不用考虑;</li> <li>使用方案 3,所有消费者需要处理所有的消息;</li> <li>使用方案 4,需先实现其 SDK。</li> </ul> <p><img src="files/ons-mq-from-ali-workorder.png" alt=""></p> <p>官方不建议用方案 4,我们尝试调试也不顺畅,所以决定使用方案 3。</p> <p>Refs:</p> <ul> <li>消息服务 <a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">https://help.aliyun.com/document_detail/27414.html</a></li> <li>广播拉取消息模型 <a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">https://help.aliyun.com/document_detail/34483.html</a></li> </ul> <h1 id=44-泛域名解析>44. 泛域名解析</h1> <p>Date: 2017-08-25</p> <h2 id=status-43>Status</h2> <p>Accepted</p> <h2 id=context-43>Context</h2> <p>随着会找房平台第三方公寓的入驻,我们需要手动添加大量的公寓二级域名于 DNS 中,如,ayk.huizhaofang.com, jingyu.huizhaofang.com 等。</p> <ol> <li>整个流程依赖域名管理者;</li> <li>DNS 管理控制台维护这些记录很麻烦,并将原有专用域名淹没在大量记录中;</li> <li>网站做了前后端分离,起始页永远返回状态为 200 的页面。</li> </ol> <h2 id=decision-43>Decision</h2> <ol> <li>DNS 记录添加泛解析;</li> <li>Nginx server name 添加泛解析;</li> <li>不受约束的泛解析,会使所有子域名返回状态为 200 的页面,导致搜索引擎降权;</li> <li>使用 <code>include /path/to/server_names;</code> 可以通过独立的文件解决此问题,并可对新添加的子域名做 code review;</li> <li>上面的方案需要每次更改后做 nginx reload;有个想法是通过 lua 从 redis 中获取支持的子域名,进行判断并过滤;</li> </ol> <h2 id=consequences-43>Consequences</h2> <ol> <li><code>include</code> 方案:当前最简单,且有审核机制,但运维参与较重,需经常重启 nginx;</li> <li>lua + redis 方案: <ul> <li>每次请求需查询 redis;</li> <li>需做一个对应的管理系统进行子域名的管理。</li> </ul></li> </ol> <p>Refs:</p> <ul> <li>How can I set up a catch-all (wildcard) subdomain? <a href="http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions">https://www.namecheap.com/support/knowledgebase/article.aspx/597/2237/how-can-i-set-up-a-catchall-wildcard-subdomain</a></li> <li>Server names <a href="http://reasonofone.blogspot.hk/2014/08/architecture-decisions-what-are-they.html">http://nginx.org/en/docs/http/server_names.html</a></li> <li>谷歌重复内容处理 <a href="https://www.utdallas.edu/~chung/SA/zz-Impreso-architecture_decisions-tyree-05.pdf">https://support.google.com/webmasters/answer/66359</a></li> <li>百度网址降权 <a href="https://github.com/npryce/adr-tools">https://baike.baidu.com/item/网站降权</a></li> <li>nginx泛域名解析,实现多个二级域名 <a href="https://github.com/agis-/git-style-guide">https://yq.aliyun.com/articles/44682</a></li> <li>SEO Friendly Wildcard DNS Set Up for Apache, IIS, Nginx <a href="http://zhuanlan.51cto.com/art/201612/525719.htm">http://www.stepforth.com/resources/web-marketing-knowledgebase/set-seo-friendly-wildcard-dns/</a></li> <li>Nginx : thousands of server_name <a href="https://segmentfault.com/a/1190000004634172">https://serverfault.com/questions/405355/nginx-thousands-of-server-name</a></li> </ul> </div> </div> </body> </html> <|start_filename|>examples/export-3.html<|end_filename|> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>ADR Documents</title> <style type="text/css"> html { color: #333; background: #fff; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; text-rendering: optimizelegibility; } /* 如果你的项目仅支持 IE9+ | Chrome | Firefox 等,推荐在 <html> 中添加 .borderbox 这个 class */ html.borderbox *, html.borderbox *:before, html.borderbox *:after { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } /* 内外边距通常让各个浏览器样式的表现位置不同 */ body, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, code, form, fieldset, legend, input, textarea, p, blockquote, th, td, hr, button, article, aside, details, figcaption, figure, footer, header, menu, nav, section { margin: 0; padding: 0; } /* 重设 HTML5 标签, IE 需要在 js 中 createElement(TAG) */ article, aside, details, figcaption, figure, footer, header, menu, nav, section { display: block; } /* HTML5 媒体文件跟 img 保持一致 */ audio, canvas, video { display: inline-block; } /* 要注意表单元素并不继承父级 font 的问题 */ body, button, input, select, textarea { font: 300 1em/1.8 PingFang SC, Lantinghei SC, Microsoft Yahei, Hiragino Sans GB, Microsoft Sans Serif, WenQuanYi Micro Hei, sans-serif; } button::-moz-focus-inner, input::-moz-focus-inner { padding: 0; border: 0; } /* 去掉各Table cell 的边距并让其边重合 */ table { border-collapse: collapse; border-spacing: 0; } /* 去除默认边框 */ fieldset, img { border: 0; } /* 块/段落引用 */ blockquote { position: relative; color: #999; font-weight: 400; border-left: 1px solid #1abc9c; padding-left: 1em; margin: 1em 3em 1em 2em; } @media only screen and ( max-width: 640px ) { blockquote { margin: 1em 0; } } /* Firefox 以外,元素没有下划线,需添加 */ acronym, abbr { border-bottom: 1px dotted; font-variant: normal; } /* 添加鼠标问号,进一步确保应用的语义是正确的(要知道,交互他们也有洁癖,如果你不去掉,那得多花点口舌) */ abbr { cursor: help; } /* 一致的 del 样式 */ del { text-decoration: line-through; } address, caption, cite, code, dfn, em, th, var { font-style: normal; font-weight: 400; } /* 去掉列表前的标识, li 会继承,大部分网站通常用列表来很多内容,所以应该当去 */ ul, ol { list-style: none; } /* 对齐是排版最重要的因素, 别让什么都居中 */ caption, th { text-align: left; } q:before, q:after { content: ''; } /* 统一上标和下标 */ sub, sup { font-size: 75%; line-height: 0; position: relative; } :root sub, :root sup { vertical-align: baseline; /* for ie9 and other modern browsers */ } sup { top: -0.5em; } sub { bottom: -0.25em; } /* 让链接在 hover 状态下显示下划线 */ a { color: #1abc9c; } a:hover { text-decoration: underline; } .typo a { border-bottom: 1px solid #1abc9c; } .typo a:hover { border-bottom-color: #555; color: #555; text-decoration: none; } /* 默认不显示下划线,保持页面简洁 */ ins, a { text-decoration: none; } /* 专名号:虽然 u 已经重回 html5 Draft,但在所有浏览器中都是可以使用的, * 要做到更好,向后兼容的话,添加 class="typo-u" 来显示专名号 * 关于 <u> 标签:http://www.whatwg.org/specs/web-apps/current-work/multipage/text-level-semantics.html#the-u-element * 被放弃的是 4,之前一直搞错 http://www.w3.org/TR/html401/appendix/changes.html#idx-deprecated * 一篇关于 <u> 标签的很好文章:http://html5doctor.com/u-element/ */ u, .typo-u { text-decoration: underline; } /* 标记,类似于手写的荧光笔的作用 */ mark { background: #fffdd1; border-bottom: 1px solid #ffedce; padding: 2px; margin: 0 5px; } /* 代码片断 */ pre, code, pre tt { font-family: Courier, 'Courier New', monospace; } pre { background: #f8f8f8; border: 1px solid #ddd; padding: 1em 1.5em; display: block; -webkit-overflow-scrolling: touch; } /* 一致化 horizontal rule */ hr { border: none; border-bottom: 1px solid #cfcfcf; margin-bottom: 0.8em; height: 10px; } /* 底部印刷体、版本等标记 */ small, .typo-small, /* 图片说明 */ figcaption { font-size: 0.9em; color: #888; } strong, b { font-weight: bold; color: #000; } /* 可拖动文件添加拖动手势 */ [draggable] { cursor: move; } .clearfix:before, .clearfix:after { content: ""; display: table; } .clearfix:after { clear: both; } .clearfix { zoom: 1; } /* 强制文本换行 */ .textwrap, .textwrap td, .textwrap th { word-wrap: break-word; word-break: break-all; } .textwrap-table { table-layout: fixed; } /* 提供 serif 版本的字体设置: iOS 下中文自动 fallback 到 sans-serif */ .serif { font-family: Palatino, Optima, Georgia, serif; } /* 保证块/段落之间的空白隔行 */ .typo p, .typo pre, .typo ul, .typo ol, .typo dl, .typo form, .typo hr, .typo table, .typo-p, .typo-pre, .typo-ul, .typo-ol, .typo-dl, .typo-form, .typo-hr, .typo-table, blockquote { margin-bottom: 1.2em } h1, h2, h3, h4, h5, h6 { font-family: PingFang SC, Verdana, Helvetica Neue, Microsoft Yahei, Hiragino Sans GB, Microsoft Sans Serif, WenQuanYi Micro Hei, sans-serif; font-weight: 100; color: #000; line-height: 1.35; } /* 标题应该更贴紧内容,并与其他块区分,margin 值要相应做优化 */ .typo h1, .typo h2, .typo h3, .typo h4, .typo h5, .typo h6, .typo-h1, .typo-h2, .typo-h3, .typo-h4, .typo-h5, .typo-h6 { margin-top: 1.2em; margin-bottom: 0.6em; line-height: 1.35; } .typo h1, .typo-h1 { font-size: 2em; } .typo h2, .typo-h2 { font-size: 1.8em; } .typo h3, .typo-h3 { font-size: 1.6em; } .typo h4, .typo-h4 { font-size: 1.4em; } .typo h5, .typo h6, .typo-h5, .typo-h6 { font-size: 1.2em; } /* 在文章中,应该还原 ul 和 ol 的样式 */ .typo ul, .typo-ul { margin-left: 1.3em; list-style: disc; } .typo ol, .typo-ol { list-style: decimal; margin-left: 1.9em; } .typo li ul, .typo li ol, .typo-ul ul, .typo-ul ol, .typo-ol ul, .typo-ol ol { margin-bottom: 0.8em; margin-left: 2em; } .typo li ul, .typo-ul ul, .typo-ol ul { list-style: circle; } /* 同 ul/ol,在文章中应用 table 基本格式 */ .typo table th, .typo table td, .typo-table th, .typo-table td, .typo table caption { border: 1px solid #ddd; padding: 0.5em 1em; color: #666; } .typo table th, .typo-table th { background: #fbfbfb; } .typo table thead th, .typo-table thead th { background: #f1f1f1; } .typo table caption { border-bottom: none; } /* 去除 webkit 中 input 和 textarea 的默认样式 */ .typo-input, .typo-textarea { -webkit-appearance: none; border-radius: 0; } .typo-em, .typo em, legend, caption { color: #000; font-weight: inherit; } /* 着重号,只能在少量(少于100个字符)且全是全角字符的情况下使用 */ .typo-em { position: relative; } .typo-em:after { position: absolute; top: 0.65em; left: 0; width: 100%; overflow: hidden; white-space: nowrap; content: "・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・"; } /* Responsive images */ .typo img { max-width: 100%; } header { position: fixed; z-index: 2; z-index: 1024; top: 0; left: 0; width: 100%; height: 60px; background-color: #fff; box-shadow: 0 0 4px rgba(0,0,0,0.5); text-transform: uppercase; font-size: 20px } header .logo { display: inline-block; padding-left: 37px; float: left; text-decoration: none; color: #333; line-height: 60px; background-repeat: no-repeat; background-position: left center } header nav { text-align: right; font-size: 0 } header nav ul { display: inline-block; padding: 0; list-style: none } header nav li { display: inline } header nav a { display: inline-block; padding: 0 15px; color: #333; text-decoration: none; font-size: 20px; line-height: 60px; transition: opacity .2s } header nav a.current { color: #9600ff } header nav a:hover { opacity: .75 } .content { padding-top: 100px; } #toc { width: 30%; max-width: 420px; max-height: 85%; float: left; margin: 25px 0px 20px 0px; position: fixed !important; overflow: auto; -webkit-overflow-scrolling: touch; overflow-scrolling: touch; box-sizing: border-box; z-index: 1; left: 0; top: 40px; bottom: 0; padding: 20px; } #toc > ul { list-style: none; padding: 20px 40px 0 40px; margin: 0; border-bottom: 1px solid #eee } #toc > ul > li > ul { padding-left: 40px; } #toc a { display: block; padding: 10px 0; text-decoration: none; color: #333; border-bottom: 1px solid #eee; transition: opacity .2s } #toc a.current { color: #9600ff } #toc a:hover { opacity: .75 } .main { width: 70%; max-width: 980px; float: left; padding-left: 30%; top: 160px; position: relative; } </style> </head> <body> <header> <div class="container"> <a href="https://github.com/phodal/adr" class="logo">ADR</a> <nav> <ul> <li><a href="https://github.com/phodal/adr">GitHub</a></li> </ul> </nav> </div> </header> <div class="content"> <div id="toc" class="tocify"> <ul> <li><a href="#1-record-architecture-decisions">1. Record architecture decisions</a> <ul> <li><a href="#status">Status</a></li> <li><a href="#context">Context</a></li> <li><a href="#decision">Decision</a></li> <li><a href="#consequences">Consequences</a></li> </ul></li> <li><a href="#2-implement-as-shell-scripts">2. Implement as shell scripts</a> <ul> <li><a href="#status-1">Status</a></li> <li><a href="#context-1">Context</a></li> <li><a href="#decision-1">Decision</a></li> <li><a href="#consequences-1">Consequences</a></li> </ul></li> <li><a href="#3-single-command-with-subcommands">3. Single command with subcommands</a> <ul> <li><a href="#status-2">Status</a></li> <li><a href="#context-2">Context</a></li> <li><a href="#decision-2">Decision</a></li> <li><a href="#consequences-2">Consequences</a></li> </ul></li> <li><a href="#4-markdown-format">4. Markdown format</a> <ul> <li><a href="#status-3">Status</a></li> <li><a href="#context-3">Context</a></li> <li><a href="#decision-3">Decision</a></li> <li><a href="#consequences-3">Consequences</a></li> </ul></li> <li><a href="#5-help-comments">5. Help comments</a> <ul> <li><a href="#status-4">Status</a></li> <li><a href="#context-4">Context</a></li> <li><a href="#decision-4">Decision</a></li> <li><a href="#consequences-4">Consequences</a></li> </ul></li> <li><a href="#6-packaging-and-distribution-in-other-version-control-repositories">6. Packaging and distribution in other version control repositories</a> <ul> <li><a href="#status-5">Status</a></li> <li><a href="#context-5">Context</a></li> <li><a href="#decision-5">Decision</a></li> <li><a href="#consequences-5">Consequences</a></li> </ul></li> <li><a href="#7-invoke-adr-config-executable-to-get-configuration">7. Invoke adr-config executable to get configuration</a> <ul> <li><a href="#status-6">Status</a></li> <li><a href="#context-6">Context</a></li> <li><a href="#decision-6">Decision</a></li> <li><a href="#consequences-6">Consequences</a></li> </ul></li> <li><a href="#8-use-iso-8601-format-for-dates">8. Use ISO 8601 Format for Dates</a> <ul> <li><a href="#status-7">Status</a></li> <li><a href="#context-7">Context</a></li> <li><a href="#decision-7">Decision</a></li> <li><a href="#consequences-7">Consequences</a></li> </ul></li> </ul> </div> <div class="main typo"> <h1 id=1-record-architecture-decisions>1. Record architecture decisions</h1> <p>Date: 12/02/2016</p> <h2 id=status-0>Status</h2> <p>Accepted</p> <h2 id=context-0>Context</h2> <p>We need to record the architectural decisions made on this project.</p> <h2 id=decision-0>Decision</h2> <p>We will use Architecture Decision Records, as described by <NAME> in this article: http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions</p> <h2 id=consequences-0>Consequences</h2> <p>See <NAME>'s article, linked above.</p> <h1 id=2-implement-as-shell-scripts>2. Implement as shell scripts</h1> <p>Date: 12/02/2016</p> <h2 id=status-1>Status</h2> <p>Accepted</p> <h2 id=context-1>Context</h2> <p>ADRs are plain text files stored in a subdirectory of the project.</p> <p>The tool needs to create new files and apply small edits to the Status section of existing files.</p> <h2 id=decision-1>Decision</h2> <p>The tool is implemented as shell scripts that use standard Unix tools -- grep, sed, awk, etc.</p> <h2 id=consequences-1>Consequences</h2> <p>The tool won't support Windows. Being plain text files, ADRs can be created by hand and edited in any text editor. This tool just makes the process more convenient.</p> <p>Development will have to cope with differences between Unix variants, particularly Linux and MacOS X.</p> <h1 id=3-single-command-with-subcommands>3. Single command with subcommands</h1> <p>Date: 12/02/2016</p> <h2 id=status-2>Status</h2> <p>Accepted</p> <h2 id=context-2>Context</h2> <p>The tool provides a number of related commands to create and manipulate architecture decision records.</p> <p>How can the user find out about the commands that are available?</p> <h2 id=decision-2>Decision</h2> <p>The tool defines a single command, called <code>adr</code>.</p> <p>The first argument to <code>adr</code> (the subcommand) specifies the action to perform. Further arguments are interpreted by the subcommand.</p> <p>Running <code>adr</code> without any arguments lists the available subcommands.</p> <p>Subcommands are implemented as scripts in the same directory as the <code>adr</code> script. E.g. the subcommand <code>new</code> is implemented as the script <code>adr-new</code>, the subcommand <code>help</code> as the script <code>adr-help</code> and so on.</p> <p>Helper scripts that are part of the implementation but not subcommands follow a different naming convention, so that subcommands can be listed by filtering and transforming script file names.</p> <h2 id=consequences-2>Consequences</h2> <p>Users can more easily explore the capabilities of the tool.</p> <p>Users are already used to this style of command-line tool. For example, Git works this way.</p> <p>Each subcommand can be implemented in the most appropriate language.</p> <h1 id=4-markdown-format>4. Markdown format</h1> <p>Date: 12/02/2016</p> <h2 id=status-3>Status</h2> <p>Accepted</p> <h2 id=context-3>Context</h2> <p>The decision records must be stored in a plain text format:</p> <ul> <li><p>This works well with version control systems.</p></li> <li><p>It allows the tool to modify the status of records and insert hyperlinks when one decision supercedes another.</p></li> <li><p>Decisions can be read in the terminal, IDE, version control browser, etc.</p></li> </ul> <p>People will want to use some formatting: lists, code examples, and so on.</p> <p>People will want to view the decision records in a more readable format than plain text, and maybe print them out.</p> <h2 id=decision-3>Decision</h2> <p>Record architecture decisions in <a href="https://daringfireball.net/projects/markdown/">Markdown format</a>.</p> <h2 id=consequences-3>Consequences</h2> <p>Decisions can be read in the terminal.</p> <p>Decisions will be formatted nicely and hyperlinked by the browsers of project hosting sites like GitHub and Bitbucket.</p> <p>Tools like <a href="http://pandoc.org/">Pandoc</a> can be used to convert the decision records into HTML or PDF.</p> <h1 id=5-help-comments>5. Help comments</h1> <p>Date: 13/02/2016</p> <h2 id=status-4>Status</h2> <p>Accepted</p> <h2 id=context-4>Context</h2> <p>The tool will have a <code>help</code> subcommand to provide documentation for users.</p> <p>It's nice to have usage documentation in the script files themselves, in comments. When reading the code, that's the first place to look for information about how to run a script.</p> <h2 id=decision-4>Decision</h2> <p>Write usage documentation in comments in the source file.</p> <p>Distinguish between documentation comments and normal comments. Documentation comments have two hash characters at the start of the line.</p> <p>The <code>adr help</code> command can parse comments out from the script using the standard Unix tools <code>grep</code> and <code>cut</code>.</p> <h2 id=consequences-4>Consequences</h2> <p>No need to maintain help text in a separate file.</p> <p>Help text can easily be kept up to date as the script is edited.</p> <p>There's no automated check that the help text is up to date. The tests do not work well as documentation for users, and the help text is not easily cross-checked against the code.</p> <p>This won't work if any subcommands are not implemented as scripts that use '#' as a comment character.</p> <h1 id=6-packaging-and-distribution-in-other-version-control-repositories>6. Packaging and distribution in other version control repositories</h1> <p>Date: 16/02/2016</p> <h2 id=status-5>Status</h2> <p>Accepted</p> <h2 id=context-5>Context</h2> <p>Users want to install adr-tools with their preferred package manager. For example, Ubuntu users use <code>apt</code>, RedHat users use <code>yum</code> and Mac OS X users use <a href="http://brew.sh">Homebrew</a>.</p> <p>The developers of <code>adr-tools</code> don't know how, nor have permissions, to use all these packaging and distribution systems. Therefore packaging and distribution must be done by &quot;downstream&quot; parties.</p> <p>The developers of the tool should not favour any one particular packaging and distribution solution.</p> <h2 id=decision-5>Decision</h2> <p>The <code>adr-tools</code> project will not contain any packaging or distribution scripts and config.</p> <p>Packaging and distribution will be managed by other projects in separate version control repositories.</p> <h2 id=consequences-5>Consequences</h2> <p>The git repo of this project will be simpler.</p> <p>Eventually, users will not have to use Git to get the software.</p> <p>We will have to tag releases in the <code>adr-tools</code> repository so that packaging projects know what can be published and how it should be identified.</p> <p>We will document how users can install the software in this project's README file.</p> <h1 id=7-invoke-adr-config-executable-to-get-configuration>7. Invoke adr-config executable to get configuration</h1> <p>Date: 17/12/2016</p> <h2 id=status-6>Status</h2> <p>Accepted</p> <h2 id=context-6>Context</h2> <p>Packagers (e.g. Homebrew developers) want to configure adr-tools to match the conventions of their installation.</p> <p>Currently, this is done by sourcing a file <code>config.sh</code>, which should sit beside the <code>adr</code> executable.</p> <p>This name is too common.</p> <p>The <code>config.sh</code> file is not executable, and so doesn't belong in a bin directory.</p> <h2 id=decision-6>Decision</h2> <p>Replace <code>config.sh</code> with an executable, named <code>adr-config</code> that outputs configuration.</p> <p>Each script in ADR Tools will eval the output of <code>adr-config</code> to configure itself.</p> <h2 id=consequences-6>Consequences</h2> <p>Configuration within ADR Tools is a little more complicated.</p> <p>Packagers can write their own implementation of <code>adr-config</code> that outputs configuration that matches the platform's installation conventions, and deploy it next to the <code>adr</code> script.</p> <p>To make development easier, the implementation of <code>adr-config</code> in the project's src/ directory will output configuration that lets the tool to run from the src/ directory without any installation step. (Packagers should not include this script in a deployable package.)</p> <h1 id=8-use-iso-8601-format-for-dates>8. Use ISO 8601 Format for Dates</h1> <p>Date: 21/02/2017</p> <h2 id=status-7>Status</h2> <p>Accepted</p> <h2 id=context-7>Context</h2> <p><code>adr-tools</code> seeks to communicate the history of architectural decisions of a project. An important component of the history is the time at which a decision was made.</p> <p>To communicate effectively, <code>adr-tools</code> should present information as unambiguously as possible. That means that culture-neutral data formats should be preferred over culture-specific formats.</p> <p>Existing <code>adr-tools</code> deployments format dates as <code>dd/mm/yyyy</code> by default. That formatting is common formatting in the United Kingdom (where the <code>adr-tools</code> project was originally written), but is easily confused with the <code>mm/dd/yyyy</code> format preferred in the United States.</p> <p>The default date format may be overridden by setting <code>ADR_DATE</code> in <code>config.sh</code>.</p> <h2 id=decision-7>Decision</h2> <p><code>adr-tools</code> will use the ISO 8601 format for dates: <code>yyyy-mm-dd</code></p> <h2 id=consequences-7>Consequences</h2> <p>Dates are displayed in a standard, culture-neutral format.</p> <p>The UK-style and ISO 8601 formats can be distinguished by their separator character. The UK-style dates used a slash (<code>/</code>), while the ISO dates use a hyphen (<code>-</code>).</p> <p>Prior to this decision, <code>adr-tools</code> was deployed using the UK format for dates. After adopting the ISO 8601 format, existing deployments of <code>adr-tools</code> must do one of the following:</p> <ul> <li>Accept mixed formatting of dates within their documentation library.</li> <li>Update existing documents to use ISO 8601 dates by running <code>adr upgrade-repository</code></li> </ul> </div> </div> </body> </html>
iT-Boyer/adr
<|start_filename|>src/com/wuyr/dmifier/utils/ReflectUtil.kt<|end_filename|> @file:Suppress("UNCHECKED_CAST", "KDocMissingDocumentation", "PublicApiImplicitType", "unused") package com.wuyr.dmifier.utils import com.jetbrains.rd.util.string.println import java.io.PrintWriter import java.io.StringWriter import java.lang.reflect.Field import java.lang.reflect.Method import java.lang.reflect.Modifier import kotlin.reflect.KClass /** * @author wuyr * @github https://github.com/wuyr/HookwormForAndroid * @since 2020-09-10 上午11:32 */ const val TAG = "ReflectUtil" /** * 发生异常是否抛出(默认不抛出,只打印堆栈信息) */ var throwReflectException: Boolean = true /** * 给对象成员变量设置新的值(可以修改final属性,静态的基本类型除外) * * @param target 目标对象 * @param fieldName 目标变量名 * @param value 新的值 * * @return true为成功 */ fun Class<*>.set(target: Any?, fieldName: String, value: Any?) = try { findField(fieldName).apply { isAccessible = true if (isLocked()) unlock() set(target, value) } true } catch (e: Exception) { if (throwReflectException) throw e else false } private fun Field.isLocked() = modifiers and Modifier.FINAL != 0 private fun Field.unlock() = let { target -> try { Field::class.java.getDeclaredField("modifiers") } catch (e: Exception) { Field::class.java.getDeclaredField("accessFlags") }.run { isAccessible = true setInt(target, target.modifiers and Modifier.FINAL.inv()) } } /** * 获取目标对象的变量值 * * @param target 目标对象 * @param fieldName 目标变量名 * * @return 目标变量值(获取失败则返回null) */ fun <T> Class<*>.get(target: Any?, fieldName: String) = try { findField(fieldName).run { isAccessible = true get(target) as? T? } } catch (e: Exception) { if (throwReflectException) throw e else e.stackTraceString.println() null } /** * 调用目标对象的方法 * * @param target 目标对象 * @param methodName 目标方法名 * @param paramsPairs 参数类型和参数值的键值对。示例: * <pre> * val view = LayoutInflater::class.invoke<View>(layoutInflater, "tryInflatePrecompiled", * Int::class to R.layout.view_test, * Resource::class to context.resource, * ViewGroup::class to rootView, * Boolean::class to false * ) * </pre> * * @return 方法返回值 */ fun <T> Class<*>.invoke(target: Any?, methodName: String, vararg paramsPairs: Pair<KClass<*>, Any?> = emptyArray()) = try { findMethod(methodName, *paramsPairs.map { it.first.java }.toTypedArray()).run { isAccessible = true invoke(target, *paramsPairs.map { it.second }.toTypedArray()) as? T? } } catch (e: Exception) { if (throwReflectException) throw e else e.stackTraceString.println() null } /** * 同上,此乃调用void方法,即无返回值 */ fun Class<*>.invokeVoid(target: Any?, methodName: String, vararg paramsPairs: Pair<KClass<*>, Any?> = emptyArray()) { try { findMethod(methodName, *paramsPairs.map { it.first.java }.toTypedArray()).run { isAccessible = true invoke(target, *paramsPairs.map { it.second }.toTypedArray()) } } catch (e: Exception) { if (throwReflectException) throw e else e.stackTraceString.println() } } /** * 创建目标类对象 * * @param paramsPairs 参数类型和参数值的键值对。示例: * <pre> * val context = ContextImpl::class.newInstance<Context>( * ActivityThread::class to ..., * LoadedApk::class to ..., * String::class to ..., * IBinder::class to ..., * ) * * @return 目标对象新实例 */ fun <T> Class<*>.newInstance(vararg paramsPairs: Pair<KClass<*>, Any?> = emptyArray()) = try { getDeclaredConstructor(*paramsPairs.map { it.first.java }.toTypedArray()).run { isAccessible = true newInstance(*paramsPairs.map { it.second }.toTypedArray()) as? T? } } catch (e: Exception) { if (throwReflectException) throw e else e.stackTraceString.println() null } fun Class<*>.findField(fieldName: String): Field { declaredFields.forEach { if (it.name == fieldName) { return it } } if (this == Any::class.java) { throw NoSuchFieldException(fieldName) } else { if (isInterface) { interfaces.forEach { runCatching { it.findField(fieldName) }.getOrNull()?.run { return this } } throw NoSuchFieldException(fieldName) } else return superclass.findField(fieldName) } } fun Class<*>.findMethod(methodName: String, parameterTypes: Array<Class<*>> = emptyArray()): Method { declaredMethods.forEach { if (it.name == methodName && parameterTypes.contentEquals(it.parameterTypes)) { return it } } if (this == Any::class.java) { throw NoSuchMethodException(parameterTypes.joinToString(prefix = "$methodName(", postfix = ")") { it.name }) } else { if (isInterface) { interfaces.forEach { runCatching { it.findMethod(methodName, parameterTypes) }.getOrNull()?.run { return this } } throw NoSuchMethodException(parameterTypes.joinToString(prefix = "$methodName(", postfix = ")") { it.name }) } else return superclass.findMethod(methodName, parameterTypes) } } fun <T> KClass<*>.invoke(target: Any?, methodName: String, vararg paramsPairs: Pair<KClass<*>, Any?> = emptyArray()) = try { java.run { findMethod(methodName, *paramsPairs.map { it.first.java }.toTypedArray()).run { isAccessible = true invoke(target, *paramsPairs.map { it.second }.toTypedArray()) as? T? } } } catch (e: Exception) { if (throwReflectException) throw e else e.println() null } fun KClass<*>.invokeVoid(target: Any?, methodName: String, vararg paramsPairs: Pair<KClass<*>, Any?> = emptyArray()) { try { java.run { findMethod(methodName, *paramsPairs.map { it.first.java }.toTypedArray()).run { isAccessible = true invoke(target, *paramsPairs.map { it.second }.toTypedArray()) } } } catch (e: Exception) { if (throwReflectException) throw e else e.stackTraceString.println() } } fun <T> KClass<*>.newInstance(vararg paramsPairs: Pair<KClass<*>, Any?> = emptyArray()) = try { java.run { getDeclaredConstructor(*paramsPairs.map { it.first.java }.toTypedArray()).run { isAccessible = true newInstance(*paramsPairs.map { it.second }.toTypedArray()) as? T? } } } catch (e: Exception) { if (throwReflectException) throw e else e.stackTraceString.println() null } fun String.set(target: Any?, fieldName: String, value: Any?) = Class.forName(this).set(target, fieldName, value) fun <T> String.get(target: Any?, fieldName: String) = Class.forName(this).get<T>(target, fieldName) fun <T> String.invoke(target: Any?, methodName: String, vararg paramsPairs: Pair<KClass<*>, Any?>) = Class.forName(this).invoke<T>(target, methodName, *paramsPairs) fun String.invokeVoid(target: Any?, methodName: String, vararg paramsPairs: Pair<KClass<*>, Any?>) = Class.forName(this).invokeVoid(target, methodName, *paramsPairs) fun <T> String.newInstance(vararg paramsPairs: Pair<KClass<*>, Any?>) = Class.forName(this).newInstance<T>(*paramsPairs) fun KClass<*>.set(target: Any?, fieldName: String, value: Any?) = java.set(target, fieldName, value) fun <T> KClass<*>.get(target: Any?, fieldName: String) = java.get<T>(target, fieldName) val Throwable.stackTraceString: String get() = StringWriter().use { sw -> PrintWriter(sw).use { pw -> printStackTrace(pw) pw.flush() } sw.flush() }.toString() fun Any?.println() = println(toString()) <|start_filename|>src/com/wuyr/dmifier/actions/ViewCodeAction.kt<|end_filename|> package com.wuyr.dmifier.actions import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.LangDataKeys import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.* import com.intellij.openapi.ui.Messages import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiManager import com.intellij.task.ProjectTaskManager import com.intellij.util.io.URLUtil import com.wuyr.dmifier.core.DMifier import com.wuyr.dmifier.utils.invoke import org.objectweb.asm.ClassReader import org.objectweb.asm.util.TraceClassVisitor import java.io.File import java.io.FileInputStream import java.io.PrintWriter import java.io.StringWriter import java.nio.file.Paths class ViewCodeAction : AnAction() { override fun update(e: AnActionEvent) { e.presentation.isEnabled = e.project?.let { project -> e.getData(PlatformDataKeys.VIRTUAL_FILE)?.let { file -> PsiManager.getInstance(project).findFile(file)?.fileType?.name == "JAVA" } } ?: false } override fun actionPerformed(e: AnActionEvent) { e.project?.compileAndShow(e.getData(LangDataKeys.PSI_FILE)?.virtualFile ?: return) } private fun Project.compileAndShow(target: VirtualFile) { ProjectTaskManager.getInstance(this).compile(target).onSuccess { result -> if (!result.hasErrors()) { val file = PsiManager.getInstance(this).findFile(target) ?: return@onSuccess val packageName = file::class.invoke<String>(file, "getPackageName")!! this.findClassFromOutputDirectories(target, packageName)?.let { outputFile -> Messages.showMessageDialog(outputFile.convertToDexMakerCode(), "DexMaker", null) } } } } private fun VirtualFile.convertToDexMakerCode() = StringWriter(2048).use { sw -> runCatching { ClassReader(FileInputStream(path)).accept(TraceClassVisitor(null, DMifier(), PrintWriter(sw)), 0) }.getOrElse { it.printStackTrace(PrintWriter(sw)) } sw.toString() } private fun Project.findClassFromOutputDirectories(target: VirtualFile, packageName: String): VirtualFile? { ProjectRootManager.getInstance(this).fileIndex.getModuleForFile(target)?.let { module -> module.getOutputDirectories(module.getModuleScope(false).contains(target)).forEach { outputDir -> outputDir?.let { dir -> VirtualFileManager.getInstance().getFileSystem(URLUtil.FILE_PROTOCOL).refreshAndFindFileByPath( Paths.get(dir, packageName, "${target.nameWithoutExtension}.class").toString() )?.also { outputFile -> outputFile.refresh(false, false) return outputFile } } } } return null } private fun Module.getOutputDirectories(isRelease: Boolean) = ArrayList<String?>().also { result -> CompilerModuleExtension.getInstance(this)?.let { moduleExtension -> CompilerProjectExtension.getInstance(project)?.let { projectExtension -> (if (isRelease) moduleExtension.compilerOutputPath else moduleExtension.compilerOutputPathForTests) ?.let { result.add(it.path) } ?: projectExtension.compilerOutput?.let { result.add(it.path) } OrderEnumerationHandler.EP_NAME.extensions.forEach { factory -> if (factory.isApplicable(this)) { ArrayList<String>().also { urls -> @Suppress("OverrideOnly") factory.createHandler(this).addCustomModuleRoots( OrderRootType.CLASSES, ModuleRootManager.getInstance(this), urls, isRelease, !isRelease ) }.forEach { url -> result.add(VirtualFileManager.extractPath(url).replace('/', File.separatorChar)) } } } } } } } <|start_filename|>src/com/wuyr/dmifier/core/DMifier.kt<|end_filename|> package com.wuyr.dmifier.core import org.objectweb.asm.* import org.objectweb.asm.util.Printer import java.lang.reflect.Modifier import java.util.* class DMifier : Printer(589824) { private fun StringBuilder.newLine() = append("\n") private var superTypeId = "" override fun visit( version: Int, access: Int, name: String?, signature: String?, superName: String, interfaces: Array<out String> ) { appendCodeBlockAndAdd { append("TypeId classId = ") append(name?.typeId) append(";") newLine() append("String fileName = \"") val simpleName = name?.run { val lastSlashIndex = lastIndexOf('/') if (lastSlashIndex == -1) name else substring(lastSlashIndex + 1).replace("[-()]".toRegex(), "_") } ?: "DexMakerClass" append(simpleName) append(".generated\";") newLine() append("DexMaker dexMaker = new DexMaker();") newLine() append("TypeId[] interfacesTypes = new TypeId[") append(interfaces.size) append("];") newLine() interfaces.forEachIndexed { index, content -> append("interfacesTypes[") append(index) append("] = ") append(content.typeId) append(";") newLine() } append("dexMaker.declare(classId, fileName, ") append((access or ACCESS_CLASS).accessFlag) append(", ") superTypeId = superName.typeId append(superTypeId) append(", interfacesTypes);") newLine() } } override fun visit(name: String?, value: Any?) { appendCodeBlockAndAdd { append("TypeId classId = ") append(name?.typeId) append(";") newLine() append("String fileName = \"") val simpleName = name?.run { val lastSlashIndex = lastIndexOf('/') if (lastSlashIndex == -1) name else substring(lastSlashIndex + 1).replace("[-()]".toRegex(), "_") } ?: "DexMakerClass" append(simpleName) append(".generated\";") newLine() append("DexMaker dexMaker = new DexMaker();") newLine() append("dexMaker.declare(classId, fileName, ") append("Modifier.PUBLIC") append(");") newLine() } } private val Int.accessFlag: String get() = StringBuilder().also { sb -> if (this == 0) { sb.append("0") } else { if ((this and Modifier.PUBLIC) != 0) sb.append("Modifier.PUBLIC | ") if ((this and Modifier.PRIVATE) != 0) sb.append("Modifier.PRIVATE | ") if ((this and Modifier.PROTECTED) != 0) sb.append("Modifier.PROTECTED | ") if ((this and Modifier.STATIC) != 0) sb.append("Modifier.STATIC | ") if ((this and Modifier.FINAL) != 0) sb.append("Modifier.FINAL | ") if ((this and Modifier.SYNCHRONIZED) != 0 && this and ACCESS_CLASS == 0) sb.append("Modifier.SYNCHRONIZED | ") if ((this and Modifier.VOLATILE) != 0) sb.append("Modifier.VOLATILE | ") if ((this and Modifier.TRANSIENT) != 0 && this and ACCESS_FIELD != 0) sb.append("Modifier.TRANSIENT | ") if ((this and Modifier.NATIVE) != 0 && this and (ACCESS_CLASS or ACCESS_FIELD) == 0) sb.append("Modifier.NATIVE | ") if ((this and Modifier.INTERFACE) != 0) sb.append("Modifier.INTERFACE | ") if ((this and Modifier.ABSTRACT) != 0) sb.append("Modifier.ABSTRACT | ") if ((this and Modifier.STRICT) != 0) sb.append("Modifier.STRICT | ") if (sb.isEmpty()) { sb.append("0") } else { sb.deleteCharAt(sb.lastIndex) sb.deleteCharAt(sb.lastIndex) sb.deleteCharAt(sb.lastIndex) } } }.toString() override fun visitSource(source: String?, debug: String?) { } override fun visitOuterClass(owner: String?, name: String?, descriptor: String?) { } override fun visitClassAnnotation(descriptor: String?, visible: Boolean): Printer { return this } override fun visitClassAttribute(attribute: Attribute?) { } override fun visitInnerClass(name: String?, outerName: String?, innerName: String?, access: Int) { } override fun visitField(access: Int, name: String, descriptor: String, signature: String?, value: Any?): Printer { appendCodeBlockAndAdd { append("dexMaker.declare(classId.getField(") append(descriptor.typeId) append(", \"") append(name) append("\"), ") append((access or ACCESS_FIELD).accessFlag) append(", ") append(value) append(");") } return this } private var currentMethodParameters = emptyList<String>() private var currentMethodReturnType = "" private var isStaticMethod = false override fun visitMethod( access: Int, name: String, descriptor: String, signature: String?, exceptions: Array<out String>? ): Printer { appendCodeBlockAndAdd { newLine() append("{") newLine() val parameters = descriptor.getParameterTypes() isStaticMethod = (access and Modifier.STATIC) != 0 currentMethodParameters = parameters currentMethodReturnType = descriptor.getReturnType().typeId localCount = currentMethodParameters.size + if (isStaticMethod) 0 else 1 append("MethodId methodId = classId.") when (name) { "<init>" -> { append("getConstructor(") if (parameters.isNotEmpty()) { parameters.forEach { append(it.typeId) append(", ") } deleteCharAt(lastIndex) deleteCharAt(lastIndex) } append(");") } "<clinit>" -> { append("getStaticInitializer();") } else -> { append("getMethod(") append(currentMethodReturnType) append(", \"") append(name) if (parameters.isEmpty()) { append("\"") } else { append("\", ") parameters.forEach { append(it.typeId) append(", ") } deleteCharAt(lastIndex) deleteCharAt(lastIndex) } append(");") } } newLine() append("Code methodCodeBlock = dexMaker.declare(methodId, ") append(access.accessFlag) append(");") newLine() } return this } private fun String.getReturnType() = substring(lastIndexOf(')') + 1) private fun String.getParameterTypes() = substring(1, lastIndexOf(')')).run { ArrayList<String>().apply { split(";").forEach { type -> if (type.isNotEmpty()) { if (type.contains('[') && type.indexOf('[') != type.lastIndexOf('[')) { type.split("[").forEach { if (it.isNotEmpty()) { addParameter("[$it") } } } else { addParameter(type) } } } removeIf { it.isEmpty() } } } private fun ArrayList<String>.addParameter(type: String) { if (type.startsWith('L') || type.startsWith("[L")) { add(type) } else { val index = type.indexOf(if (type.contains('[')) '[' else 'L') if (index == 0 && type.length >= 2) { add(type.substring(0, 2)) add(type.substring(2, type.length)) } else if (index > -1) { type.substring(0, index).forEach { c -> add(c.toString()) } add(type.substring(index, type.length)) } else { type.forEach { c -> add(c.toString()) } } } } private val String.typeId: String get() = when (this) { "Z" -> "TypeId.BOOLEAN" "C" -> "TypeId.CHAR" "F" -> "TypeId.FLOAT" "D" -> "TypeId.DOUBLE" "B" -> "TypeId.BYTE" "S" -> "TypeId.SHORT" "I" -> "TypeId.INT" "J" -> "TypeId.LONG" "V" -> "TypeId.VOID" else -> StringBuilder().also { sb -> sb.append("TypeId.get(\"") if ((!startsWith('L')) && !startsWith('[')) sb.append('L') sb.append(this) if (!endsWith(';') && length != 2) sb.append(';') sb.append("\")") }.toString() } private fun String.getMethodId(name: String, returnType: String, parameterTypes: List<String>) = appendCodeBlock { append(typeId) append(".getMethod(") append(returnType.typeId) append(", \"") append(name) if (parameterTypes.isEmpty()) { append("\")") } else { append("\", ") append(parameterTypes.joinToString { it.typeId }) append(")") } } private fun String.getFieldId(type: String, name: String) = appendCodeBlock { append(typeId) append(".getField(") append(type.typeId) append(", \"") append(name) append("\")") } override fun visitClassEnd() { } override fun visitEnum(name: String?, descriptor: String?, value: String?) { } override fun visitAnnotation(name: String?, descriptor: String?): Printer { return this } override fun visitArray(name: String?): Printer { return this } override fun visitAnnotationEnd() { } override fun visitFieldAnnotation(descriptor: String?, visible: Boolean): Printer { return this } override fun visitFieldAttribute(attribute: Attribute?) { } override fun visitFieldEnd() { } override fun visitAnnotationDefault(): Printer { return this } override fun visitMethodAnnotation(descriptor: String?, visible: Boolean): Printer { return this } override fun visitParameterAnnotation(parameter: Int, descriptor: String?, visible: Boolean): Printer { return this } override fun visitMethodAttribute(attribute: Attribute?) { } override fun visitCode() { } override fun visitFrame(type: Int, numLocal: Int, local: Array<out Any>?, numStack: Int, stack: Array<out Any>?) { } private var operationStringBuilder = StringBuilder() private var declarationStringBuilder = StringBuilder() private fun appendDeclarationCodeBlock(block: StringBuilder.() -> Unit) { declarationStringBuilder.apply { block() newLine() } } private fun appendOperationCodeBlock(appendNewLine: Boolean = true, block: StringBuilder.() -> Unit) { operationStringBuilder.apply { block() if (appendNewLine) { newLine() } } } private fun flushTempCodeBlock() { declarationStringBuilder.newLine() text.add(declarationStringBuilder.toString()) text.add(operationStringBuilder.toString()) declarationStringBuilder.setLength(0) operationStringBuilder.setLength(0) } // localName : typeId private val stack = LinkedList<Pair<String, String>>() private var localCount = 0 private var tempLocalCount = 0 private val localNames = HashMap<String, Pair<String, String>>() private fun newLocalName(typeId: String, store: Boolean = false, conflictLocal: String? = null) = if (store && conflictLocal != null) { var currentConflictLocal = conflictLocal!! do { currentConflictLocal = "${currentConflictLocal}_append" } while (localNames.containsKey(currentConflictLocal)) localNames[currentConflictLocal] = currentConflictLocal to typeId currentConflictLocal } else (if (store) "local${localCount++}" else "tempLocal${tempLocalCount++}").also { name -> if (store) { if (typeId == "TypeId.LONG" || typeId == "TypeId.DOUBLE") { localCount++ } localNames[name] = name to typeId } } private fun getLocalName(index: Int): Pair<String, String>? { var localName = "local$index" while (localNames.containsKey("${localName}_append")) { localName = "${localName}_append" } return localNames[localName] } private fun cast(targetType: String) { val typeId = targetType.typeId val output = newLocalName(typeId) appendDeclarationCodeBlock { append("Local ") append(output) append(" = methodCodeBlock.newLocal(") append(typeId) append(");") } appendOperationCodeBlock { append("methodCodeBlock.cast(") append(output) append(", ") append(stack.pop().first) append(");") } stack.push(output to typeId) } private fun loadConstant(type: String, value: Any?) { val typeId = type.typeId val output = newLocalName(typeId) appendDeclarationCodeBlock { append("Local ") append(output) append(" = methodCodeBlock.newLocal(") append(typeId) append(");") } appendOperationCodeBlock { append("methodCodeBlock.loadConstant(") append(output) append(", ") append(value) append(");") } stack.push(output to typeId) } override fun visitInsn(opcode: Int) { when (opcode) { Opcodes.ACONST_NULL -> loadConstant("java/lang/Object", null) Opcodes.ICONST_M1 -> loadConstant("I", -1) Opcodes.ICONST_0 -> loadConstant("I", 0) Opcodes.ICONST_1 -> loadConstant("I", 1) Opcodes.ICONST_2 -> loadConstant("I", 2) Opcodes.ICONST_3 -> loadConstant("I", 3) Opcodes.ICONST_4 -> loadConstant("I", 4) Opcodes.ICONST_5 -> loadConstant("I", 5) Opcodes.LCONST_0 -> loadConstant("J", 0) Opcodes.LCONST_1 -> loadConstant("J", 1) Opcodes.FCONST_0 -> loadConstant("F", 0) Opcodes.FCONST_1 -> loadConstant("F", 1) Opcodes.FCONST_2 -> loadConstant("F", 2) Opcodes.DCONST_0 -> loadConstant("D", 0) Opcodes.DCONST_1 -> loadConstant("D", 1) Opcodes.IALOAD, Opcodes.LALOAD, Opcodes.FALOAD, Opcodes.DALOAD, Opcodes.AALOAD, Opcodes.BALOAD, Opcodes.CALOAD, Opcodes.SALOAD -> { val typeId = stack[1].second.replaceFirst("[", "") val output = newLocalName(typeId) appendDeclarationCodeBlock { append("Local ") append(output) append(" = methodCodeBlock.newLocal(") append(typeId) append(");") } appendOperationCodeBlock { append("methodCodeBlock.aget(") append(output) append(", ") append(stack[1].first) append(", ") append(stack[0].first) append(");") stack.pop() stack.pop() } stack.push(output to typeId) } Opcodes.IASTORE, Opcodes.LASTORE, Opcodes.FASTORE, Opcodes.DASTORE, Opcodes.AASTORE, Opcodes.BASTORE, Opcodes.CASTORE, Opcodes.SASTORE -> { appendOperationCodeBlock { append("methodCodeBlock.aput(") append(stack[2].first) append(", ") append(stack[1].first) append(", ") append(stack[0].first) append(");") stack.pop() stack.pop() stack.pop() } } Opcodes.ARRAYLENGTH -> { val typeId = "TypeId.INT" val output = newLocalName(typeId) appendDeclarationCodeBlock { append("Local ") append(output) append(" = methodCodeBlock.newLocal(") append(typeId) append(");") } appendOperationCodeBlock { append("methodCodeBlock.arrayLength(") append(output) append(", ") append(stack.pop().first) append(");") } stack.push(output to typeId) } Opcodes.L2I, Opcodes.F2I, Opcodes.D2I -> cast("I") Opcodes.I2L, Opcodes.F2L, Opcodes.D2L -> cast("J") Opcodes.I2F, Opcodes.L2F, Opcodes.D2F -> cast("F") Opcodes.I2D, Opcodes.L2D, Opcodes.F2D -> cast("D") Opcodes.I2B -> cast("B") Opcodes.I2C -> cast("C") Opcodes.I2S -> cast("S") Opcodes.IADD -> binaryOp("I", "BinaryOp.ADD") Opcodes.LADD -> binaryOp("J", "BinaryOp.ADD") Opcodes.FADD -> binaryOp("F", "BinaryOp.ADD") Opcodes.DADD -> binaryOp("D", "BinaryOp.ADD") Opcodes.ISUB -> binaryOp("I", "BinaryOp.SUBTRACT") Opcodes.LSUB -> binaryOp("J", "BinaryOp.SUBTRACT") Opcodes.FSUB -> binaryOp("F", "BinaryOp.SUBTRACT") Opcodes.DSUB -> binaryOp("D", "BinaryOp.SUBTRACT") Opcodes.IMUL -> binaryOp("I", "BinaryOp.MULTIPLY") Opcodes.LMUL -> binaryOp("J", "BinaryOp.MULTIPLY") Opcodes.FMUL -> binaryOp("F", "BinaryOp.MULTIPLY") Opcodes.DMUL -> binaryOp("D", "BinaryOp.MULTIPLY") Opcodes.IDIV -> binaryOp("I", "BinaryOp.DIVIDE") Opcodes.LDIV -> binaryOp("J", "BinaryOp.DIVIDE") Opcodes.FDIV -> binaryOp("F", "BinaryOp.DIVIDE") Opcodes.DDIV -> binaryOp("D", "BinaryOp.DIVIDE") Opcodes.IREM -> binaryOp("I", "BinaryOp.REMAINDER") Opcodes.LREM -> binaryOp("J", "BinaryOp.REMAINDER") Opcodes.FREM -> binaryOp("F", "BinaryOp.REMAINDER") Opcodes.DREM -> binaryOp("D", "BinaryOp.REMAINDER") Opcodes.INEG -> binaryOp("I", "BinaryOp.NEGATE") Opcodes.LNEG -> binaryOp("J", "BinaryOp.NEGATE") Opcodes.FNEG -> binaryOp("F", "BinaryOp.NEGATE") Opcodes.DNEG -> binaryOp("D", "BinaryOp.NEGATE") Opcodes.ISHL -> binaryOp("I", "BinaryOp.SHIFT_LEFT") Opcodes.LSHL -> binaryOp("J", "BinaryOp.SHIFT_LEFT") Opcodes.ISHR -> binaryOp("I", "BinaryOp.SHIFT_RIGHT") Opcodes.LSHR -> binaryOp("J", "BinaryOp.SHIFT_RIGHT") Opcodes.IUSHR -> binaryOp("I", "BinaryOp.UNSIGNED_SHIFT_RIGHT") Opcodes.LUSHR -> binaryOp("J", "BinaryOp.UNSIGNED_SHIFT_RIGHT") Opcodes.IAND -> binaryOp("I", "BinaryOp.AND") Opcodes.LAND -> binaryOp("J", "BinaryOp.AND") Opcodes.IOR -> binaryOp("I", "BinaryOp.OR") Opcodes.LOR -> binaryOp("J", "BinaryOp.OR") Opcodes.IXOR -> binaryOp("I", "BinaryOp.XOR") Opcodes.LXOR -> binaryOp("J", "BinaryOp.XOR") Opcodes.LCMP -> { val typeId = "TypeId.INT" val output = newLocalName(typeId) appendDeclarationCodeBlock { append("Local ") append(output) append(" = methodCodeBlock.newLocal(TypeId.INT);") } appendOperationCodeBlock { append("methodCodeBlock.compareLongs(") append(output) append(", ") append(stack[1].first) append(", ") append(stack[0].first) append(");") stack.pop() stack.pop() } stack.push(output to typeId) } Opcodes.FCMPL, Opcodes.FCMPG, Opcodes.DCMPL, Opcodes.DCMPG -> { val typeId = "TypeId.INT" val output = newLocalName(typeId) appendDeclarationCodeBlock { append("Local ") append(output) append(" = methodCodeBlock.newLocal(TypeId.INT);") } appendOperationCodeBlock { append("methodCodeBlock.compareFloatingPoint(") append(output) append(", ") append(stack[1].first) append(", ") append(stack[0].first) append(", ") append(if (opcode == Opcodes.FCMPG || opcode == Opcodes.DCMPG) 1 else -1) append(");") stack.pop() stack.pop() } stack.push(output to typeId) } Opcodes.IRETURN, Opcodes.LRETURN, Opcodes.FRETURN, Opcodes.DRETURN, Opcodes.ARETURN -> { appendOperationCodeBlock { if (stack.peek().second != currentMethodReturnType) { stack.push(store(currentMethodReturnType) to currentMethodReturnType) } append("methodCodeBlock.returnValue(") append(stack.pop().first) append(");") stack.clear() } } Opcodes.RETURN -> { appendOperationCodeBlock { append("methodCodeBlock.returnVoid();") stack.clear() } } Opcodes.POP -> { stack.pop() } Opcodes.DUP -> { if (!pendingNewInstance) { stack.push(stack.peek()) } } Opcodes.MONITORENTER -> { appendOperationCodeBlock { append("methodCodeBlock.monitorEnter(") append(stack.pop().first) append(");") } } Opcodes.MONITOREXIT -> { appendOperationCodeBlock { append("methodCodeBlock.monitorExit(") append(stack.pop().first) append(");") } } Opcodes.ATHROW -> { appendOperationCodeBlock { append("methodCodeBlock.throwValue(") append(stack.pop().first) append(");") } } } } private fun binaryOp(type: String, op: String) { val typeId = type.typeId val output = newLocalName(typeId) appendDeclarationCodeBlock { append("Local ") append(output) append(" = methodCodeBlock.newLocal(") append(typeId) append(");") } appendOperationCodeBlock { append("methodCodeBlock.op(") append(op) append(", ") append(output) append(", ") append(stack[1].first) append(", ") append(stack[0].first) append(");") stack.pop() stack.pop() } stack.push(output to typeId) } override fun visitIntInsn(opcode: Int, operand: Int) { when (opcode) { Opcodes.BIPUSH -> loadConstant("B", operand) Opcodes.SIPUSH -> loadConstant("S", operand) Opcodes.NEWARRAY -> visitTypeInsn( Opcodes.ANEWARRAY, when (operand) { 4 -> "Z" 5 -> "C" 6 -> "F" 7 -> "D" 8 -> "B" 9 -> "S" 10 -> "I" 11 -> "J" else -> return } ) } } override fun visitVarInsn(opcode: Int, index: Int) { when (opcode) { Opcodes.ILOAD, Opcodes.LLOAD, Opcodes.FLOAD, Opcodes.DLOAD, Opcodes.ALOAD -> { val originLocalCount = currentMethodParameters.size + if (isStaticMethod) 0 else 1 if (index < originLocalCount) { if (index == 0 && !isStaticMethod) { stack.push("methodCodeBlock.getThis(classId)" to "classId") } else { val realIndex = if (isStaticMethod) index else index - 1 val typeId = currentMethodParameters[realIndex].typeId stack.push("methodCodeBlock.getParameter($realIndex, $typeId)" to typeId) } } else { stack.push(getLocalName(index)) } } Opcodes.ISTORE, Opcodes.LSTORE, Opcodes.FSTORE, Opcodes.DSTORE, Opcodes.ASTORE -> { val currentTypeId = stack.peek().second getLocalName(index)?.let { (targetLocal, targetTypeId) -> if (currentTypeId == targetTypeId) { store(currentTypeId, targetLocal) } else { store(currentTypeId, newLocalName(currentTypeId, true, targetLocal).also { appendDeclarationCodeBlock { append("Local ") append(it) append(" = methodCodeBlock.newLocal(") append(currentTypeId) append(");") } }) } } ?: store(currentTypeId) } } } private fun store(typeId: String, target: String? = null): String { val output = target ?: run { newLocalName(typeId, true).also { appendDeclarationCodeBlock { append("Local ") append(it) append(" = methodCodeBlock.newLocal(") append(typeId) append(");") } } } appendOperationCodeBlock { append("methodCodeBlock.move(") append(output) append(", ") append(stack.pop().first) append(");") } return output } private var pendingNewInstance = false override fun visitTypeInsn(opcode: Int, type: String) { when (opcode) { Opcodes.NEW -> { pendingNewInstance = true } Opcodes.ANEWARRAY -> { val ownerTypeId = (if (type.length == 1) "[$type" else "[L$type").typeId val output = newLocalName(ownerTypeId) appendDeclarationCodeBlock { append("Local ") append(output) append(" = methodCodeBlock.newLocal(") append(ownerTypeId) append(");") } appendOperationCodeBlock { append("methodCodeBlock.newArray(") append(output) append(", ") append(stack.pop().first) append(");") } stack.push(output to ownerTypeId) } Opcodes.CHECKCAST -> { cast(type) } Opcodes.INSTANCEOF -> { val typeId = type.typeId val output = newLocalName(typeId) appendDeclarationCodeBlock { append("Local ") append(output) append(" = methodCodeBlock.newLocal(") append(typeId) append(");") } appendOperationCodeBlock { append("methodCodeBlock.instanceOfType(") append(output) append(", ") append(stack.pop().first) append(", ") append(typeId) append(");") } stack.push(output to typeId) } } } override fun visitFieldInsn(opcode: Int, owner: String, name: String, descriptor: String) { when (opcode) { Opcodes.GETSTATIC -> { val typeId = descriptor.typeId val output = newLocalName(typeId) appendDeclarationCodeBlock { append("Local ") append(output) append(" = methodCodeBlock.newLocal(") append(typeId) append(");") } appendOperationCodeBlock { append("methodCodeBlock.sget(") append(owner.getFieldId(descriptor, name)) append(", ") append(output) append(");") } stack.push(output to typeId) } Opcodes.PUTSTATIC -> { appendOperationCodeBlock { append("methodCodeBlock.sput(") append(owner.getFieldId(descriptor, name)) append(", ") append(stack.peek().first) append(");") if (popAfterPut) { popAfterPut = false stack.pop() } } } Opcodes.GETFIELD -> { val typeId = descriptor.typeId val output = newLocalName(typeId) appendDeclarationCodeBlock { append("Local ") append(output) append(" = methodCodeBlock.newLocal(") append(typeId) append(");") } appendOperationCodeBlock { append("methodCodeBlock.iget(") append(owner.getFieldId(descriptor, name)) append(", ") append(output) append(", ") append(stack.pop().first) append(");") } stack.push(output to typeId) } Opcodes.PUTFIELD -> { appendOperationCodeBlock { append("methodCodeBlock.iput(") append(owner.getFieldId(descriptor, name)) append(", ") append(stack[1].first) append(", ") append(stack[0].first) append(");") stack.pop() if (popAfterPut) { popAfterPut = false stack.pop() } } } } } override fun visitInvokeDynamicInsn( name: String?, descriptor: String?, bootstrapMethodHandle: Handle?, vararg bootstrapMethodArguments: Any? ) { //FIXME: 不支持INVOKE DYNAMIC } override fun visitJumpInsn(opcode: Int, label: Label) { when (opcode) { Opcodes.IFEQ, Opcodes.IFNE, Opcodes.IFLT, Opcodes.IFGE, Opcodes.IFGT, Opcodes.IFLE -> { appendOperationCodeBlock { append("methodCodeBlock.compareZ(") append( when (opcode) { Opcodes.IFEQ -> "Comparison.EQ" Opcodes.IFNE -> "Comparison.NE" Opcodes.IFLT -> "Comparison.LT" Opcodes.IFGE -> "Comparison.GE" Opcodes.IFGT -> "Comparison.GT" Opcodes.IFLE -> "Comparison.LE" else -> "" } ) append(", ") append(label) append(", ") append(stack.pop().first) append(");") } } Opcodes.IF_ICMPEQ, Opcodes.IF_ICMPNE, Opcodes.IF_ICMPLT, Opcodes.IF_ICMPGE, Opcodes.IF_ICMPGT, Opcodes.IF_ICMPLE, Opcodes.IF_ACMPEQ, Opcodes.IF_ACMPNE -> { appendOperationCodeBlock { append("methodCodeBlock.compare(") append( when (opcode) { Opcodes.IF_ICMPEQ, Opcodes.IF_ACMPEQ -> "Comparison.EQ" Opcodes.IF_ICMPNE, Opcodes.IF_ACMPNE -> "Comparison.NE" Opcodes.IF_ICMPLT -> "Comparison.LT" Opcodes.IF_ICMPGE -> "Comparison.GE" Opcodes.IF_ICMPGT -> "Comparison.GT" Opcodes.IF_ICMPLE -> "Comparison.LE" else -> "" } ) append(", ") append(label) append(", ") append(stack[1].first) append(", ") append(stack[0].first) append(");") stack.pop() stack.pop() } } Opcodes.IFNULL -> { visitInsn(Opcodes.ACONST_NULL) visitJumpInsn(Opcodes.IF_ACMPEQ, label) } Opcodes.IFNONNULL -> { visitInsn(Opcodes.ACONST_NULL) visitJumpInsn(Opcodes.IF_ACMPNE, label) } Opcodes.GOTO -> { appendOperationCodeBlock { append("methodCodeBlock.jump(") append(label) append(");") } } } } private val labelMapping = HashSet<Label>() override fun visitLabel(label: Label) { if (!labelMapping.contains(label)) { labelMapping.add(label) appendDeclarationCodeBlock { append("Label ") append(label) append(" = new Label();") } appendOperationCodeBlock { append("methodCodeBlock.mark(") append(label) append(");") } } } private var popAfterPut = false override fun visitLdcInsn(value: Any) { when (value) { is Float -> loadConstant("F", "${value}F") is Double -> loadConstant("D", "${value}D") is Int -> loadConstant("I", value) is Long -> loadConstant("J", "${value}L") is String -> loadConstant("java/lang/String", "\"$value\"") } popAfterPut = true } override fun visitIincInsn(value: Int, increment: Int) { val output = getLocalName(value)?.first ?: return loadConstant("I", increment) appendOperationCodeBlock { append("methodCodeBlock.op(") append("BinaryOp.ADD") append(", ") append(output) append(", ") append(output) append(", ") append(stack.pop().first) append(");") } } override fun visitTableSwitchInsn(min: Int, max: Int, dflt: Label?, vararg labels: Label?) { } override fun visitLookupSwitchInsn(dflt: Label?, keys: IntArray, labels: Array<out Label>) { val target = stack.peek() repeat(keys.size) { index -> loadConstant("I", keys[index]) visitJumpInsn(Opcodes.IF_ICMPEQ, labels[index]) stack.push(target) } stack.pop() } override fun visitMultiANewArrayInsn(descriptor: String, numDimensions: Int) { } override fun visitTryCatchBlock(start: Label, end: Label, handler: Label, type: String) { // appendOperationCodeBlock { // append("methodCodeBlock.addCatchClause(") // append(type.typeId) // append(", ") // append(handler) // append(");") // } } override fun visitLocalVariable( name: String?, descriptor: String?, signature: String?, start: Label?, end: Label?, index: Int ) { } override fun visitLineNumber(line: Int, start: Label?) { } override fun visitMaxs(maxStack: Int, maxLocals: Int) { } override fun visitMethodEnd() { flushTempCodeBlock() appendCodeBlockAndAdd { append("}") } labelMapping.clear() localCount = 0 tempLocalCount = 0 localNames.clear() } private fun appendCodeBlockAndAdd(block: StringBuilder.() -> Unit) { text.add(stringBuilder.apply { setLength(0) block() newLine() }.toString()) } private fun appendCodeBlock(block: StringBuilder.() -> Unit) = stringBuilder.apply { setLength(0) block() }.toString() override fun visitModule(name: String?, access: Int, version: String?): Printer { return this } override fun visitNestHost(nestHost: String?) { } override fun visitClassTypeAnnotation( typeRef: Int, typePath: TypePath?, descriptor: String?, visible: Boolean ): Printer { return this } override fun visitNestMember(nestMember: String?) { } override fun visitMainClass(mainClass: String?) { } override fun visitPackage(packaze: String?) { } override fun visitRequire(module: String?, access: Int, version: String?) { } override fun visitExport(packaze: String?, access: Int, vararg modules: String?) { } override fun visitOpen(packaze: String?, access: Int, vararg modules: String?) { } override fun visitUse(service: String?) { } override fun visitProvide(service: String?, vararg providers: String?) { } override fun visitModuleEnd() { } override fun visitFieldTypeAnnotation( typeRef: Int, typePath: TypePath?, descriptor: String?, visible: Boolean ): Printer { return this } override fun visitParameter(name: String?, access: Int) { } override fun visitMethodTypeAnnotation( typeRef: Int, typePath: TypePath?, descriptor: String?, visible: Boolean ): Printer { return this } override fun visitAnnotableParameterCount(parameterCount: Int, visible: Boolean): Printer { return this } override fun visitMethodInsn( opcode: Int, owner: String, name: String, descriptor: String, isInterface: Boolean ) { val returnType = descriptor.getReturnType() val returnTypeId = returnType.typeId val parameterTypes = descriptor.getParameterTypes() val isVoid = returnType == "V" val methodId = owner.getMethodId(name, returnType, parameterTypes) if (pendingNewInstance) { val ownerTypeId = owner.typeId val output = newLocalName(ownerTypeId) appendDeclarationCodeBlock { append("Local ") append(output) append(" = methodCodeBlock.newLocal(") append(ownerTypeId) append(");") } appendOperationCodeBlock { append("methodCodeBlock.newInstance(") append(output) append(", ") append(methodId) append(", ") val parameterCount = parameterTypes.size repeat(parameterCount) { index -> append(stack[parameterCount - index - 1].first) append(", ") } repeat(parameterCount) { stack.pop() } deleteCharAt(lastIndex) deleteCharAt(lastIndex) append(");") } stack.push(output to ownerTypeId) pendingNewInstance = false return } var output = "" if (!isVoid) { output = newLocalName(returnTypeId) appendDeclarationCodeBlock { append("Local ") append(output) append(" = methodCodeBlock.newLocal(") append(returnTypeId) append(");") } } appendOperationCodeBlock { append("methodCodeBlock.") when (opcode) { Opcodes.INVOKEVIRTUAL -> append("invokeVirtual(") Opcodes.INVOKESPECIAL -> append( if (methodId.startsWith(superTypeId) && !methodId.contains("<init>")) "invokeSuper(" else "invokeDirect(" ) Opcodes.INVOKESTATIC -> append("invokeStatic(") Opcodes.INVOKEINTERFACE -> append("invokeInterface(") } append(methodId) append(", ") append(if (isVoid) "null" else output) append(", ") val parameterCount = parameterTypes.size + (if (opcode == Opcodes.INVOKESTATIC) 0 else 1) repeat(parameterCount) { index -> append(stack[parameterCount - index - 1].first) append(", ") } repeat(parameterCount) { stack.pop() } deleteCharAt(lastIndex) deleteCharAt(lastIndex) append(");") } if (!isVoid) { stack.push(output to returnTypeId) } } override fun visitInsnAnnotation( typeRef: Int, typePath: TypePath?, descriptor: String?, visible: Boolean ): Printer { return this } override fun visitTryCatchAnnotation( typeRef: Int, typePath: TypePath?, descriptor: String?, visible: Boolean ): Printer { return this } override fun visitLocalVariableAnnotation( typeRef: Int, typePath: TypePath?, start: Array<out Label>?, end: Array<out Label>?, index: IntArray?, descriptor: String?, visible: Boolean ): Printer { return this } companion object { private const val ACCESS_CLASS = 0x40000 private const val ACCESS_FIELD = 0x80000 } }
wuyr/DMifier
<|start_filename|>gulpfile.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ var gulp = require('gulp'); var browserify = require('gulp-browserify'); var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var gzip = require('gulp-gzip'); var jshint = require('gulp-jshint'); var sass = require('gulp-sass'); var gulpif = require('gulp-if'); var es = require('event-stream'); var clean = require('gulp-clean'); gulp.task('check', function() { gulp.src(['lib/javascripts/**', '!lib/javascripts/graph_components/class.js']) .pipe(jshint()) .pipe(jshint.reporter('default')) }); gulp.task('dashboard', function() { var stream = gulp.src(['lib/javascripts/power_dashboard.js']) .pipe(browserify({ insertGlobals : true, debug : false })) .pipe(concat('dashboard.js')) .pipe(gulp.dest('./tmp')) return stream; }); gulp.task('sass', function () { var sassOpts = {includePaths: [require('node-bourbon').includePaths, './lib/stylesheets']}; if(gulp.env.production) sassOpts.outputStyle = 'compressed'; gulp.src(['./bower_components/normalize.css/normalize.css', './lib/stylesheets/application.scss']) .pipe(sass(sassOpts)) .pipe(concat(gulp.env.production ? 'dashboard.min.css' : 'dashboard.css')) .pipe(gulp.dest('./build')); }); gulp.task('images', function() { return gulp.src(['./lib/stylesheets/sprite.png']) .pipe(gulp.dest('./build')) }); gulp.task('scripts', ['dashboard'], function() { var stream = gulp.src([ 'bower_components/underscore/underscore.js', 'bower_components/backbone/backbone.js', 'bower_components/jquery-tiny-pubsub/dist/ba-tiny-pubsub.js', 'bower_components/json2/json2.js', 'bower_components/sylvester/sylvester.src.js', 'bower_components/d3/d3.js', 'bower_components/tweenjs/src/Tween.js', 'bower_components/moment/moment.js', 'bower_components/animation-frame/AnimationFrame.js', 'bower_components/modernizr/modernizr.js', 'lib/javascripts/graph_components/class.js', 'tmp/dashboard.js' ]) .pipe(concat(gulp.env.production ? 'dashboard.min.js' : 'dashboard.js')) .pipe(gulpif(gulp.env.production, uglify())) .pipe(gulp.dest('./build')); return stream; }); gulp.task('scripts-with-cleanup', ['scripts'], function() { gulp.src(['./tmp/*.js']) .pipe(clean({force: true})) }); gulp.task('default', function() { gulp.run('check'); gulp.run('sass'); gulp.run('images'); gulp.run('scripts-with-cleanup'); }); gulp.task('watch', function() { gulp.watch([ 'lib/javascripts/**/*.js', 'lib/stylesheets/**/*.scss', 'lib/stylesheets.sprite.png' ], function() { gulp.run('scripts-with-cleanup'); }); }); <|start_filename|>lib/javascripts/backbone_components/data_line_view.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ // var Backbone = require('../../bower_components/backbone/backbone'); var DataLineView = Backbone.View.extend({ initialize: function() { _.bindAll(this, 'setMetricValue'); this.radialLine = this.options.radialLine; this.listenTo(this.model, 'change:highlighted', this.toggleVisibility, this); this.listenTo(this.model, 'change:selected', this.setCurrent, this); $.subscribe(this.radialLine.channelId + '.dataPointFound', this.setMetricValue); }, toggleVisibility: function(e) { var selectedModels = this.model.collection.models.filter(function(v) { return v.get('highlighted') === true; }); var toggle = (selectedModels.length) ? this.model.get('highlighted') : true; this.radialLine.toggle(toggle); }, setMetricValue: function() { this.model.setValueAsAverage(this.radialLine.nearestNextPoint.dataValue.value, this.radialLine.nearestPrevPoint.dataValue.value); }, setCurrent: function() { this.radialLine.toggleCurrent(this.model.get('selected')); } }); module.exports = DataLineView; <|start_filename|>lib/javascripts/graph_components/wheel_graph_composite.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ var GraphData = require('./graph_data'); var Clock = require('./clock'); var GraphBase = require('./graph_base'); var RadialGuideline = require('./radial_guideline'); var WheelGraphMetric = require('./wheel_graph_metric'); var IntervalIcon = require('./interval_icon'); var EventCloak = require('./event_cloak'); var Donut = require('./donut'); var Util = require('./util'); // Backbone var MetricGroup = require('../backbone_components/metric_group'); var MetricDisplayGroup = require('../backbone_components/metric_display_group'); var ClockDisplay = require('../backbone_components/clock_display'); /** * A place to hold all the wheel graph information for the current setup */ var WheelGraphComposite = Class.extend({ defaults: { endpointAlias: null, metrics: null, apiConfig: null }, init: function(options) { var _this = this; this.config = _.extend({ }, this.defaults, options); this.metrics = this.config.metrics; this.wheelGraphMetrics = [ ]; _.bindAll(this, 'draw'); this.graphData = new GraphData({ endpointAlias: this.config.endpointAlias, onReset: this.draw, reverseOrder: true, isWheel: true, apiConfig: this.config.apiConfig, onError: function() { _this.intervalIcon.displayError(); } }); var timestamps = _.map(this.graphData.data, function(v) { return v.timestamp; }); this.clock = new Clock({ timestamps: timestamps, radial: true }); /** * Backbone attachments */ this.metricGroup = new MetricGroup(); this.metricDisplayGroup = new MetricDisplayGroup({ el: $('.metric-display-group'), collection: this.metricGroup }); /** * Reference the existing DOM container for the wheel graph */ this.$wheelGraph = $('.wheel-graph'); this.wheelGraphBase = new GraphBase({ width: this.$wheelGraph.width(), height: this.$wheelGraph.height(), $el: this.$wheelGraph }); this.donut = new Donut({ base: this.wheelGraphBase }); /** * Create the guideline, which follows the mouse */ this.guideline = new RadialGuideline({ base: this.wheelGraphBase, clock: this.clock, classes: { line: 'wheel-graph__guideline' } }); /** * A BackboneView for updating the time */ this.clockDisplay = new ClockDisplay({ el: $('.clock-display')[0], clock: this.clock }); // Capture the line trails globally so they can be referenced from RadialLine. window.lineTrails = [ ]; /** * Create WheelGraphMetrics for all metrics associated with the graph data */ _.each(this.metrics, function(metric) { // metric.points = _this.graphData.formatAsMetric(metric.alias); _this.wheelGraphMetrics.push(new WheelGraphMetric({ metric: metric, base: _this.wheelGraphBase, clock: _this.clock, collection: _this.metricGroup, displayGroup: _this.metricDisplayGroup, guideline: _this.guideline, graphData: _this.graphData, donut: _this.donut })); }); /** * Center handle */ (function attachCenterHandle() { var handle = _this.wheelGraphBase.svg.append('circle') .attr('class', 'wheel-graph__handle') .attr('r', 5); $.subscribe(_this.clock.channelId + '.timeChange', function() { var _angle = Util.normalizeAngle(_this.clock.currentAngle) - 90; var _radius = 69; var x = (_radius * Math.cos(Util.toRadians(_angle))) + _this.wheelGraphBase.config.cx; var y = (_radius * Math.sin(Util.toRadians(_angle))) + _this.wheelGraphBase.config.cy; handle .attr('cx', x) .attr('cy', y) .classed('center-handle', true); }); })(); // Draw the event cloak last (so it's on top of all the others) this.eventCloak = new EventCloak({ animate: false, clock: this.clock, $el: $('.wheel-graph-event-cloak'), // We don't inherit the width and height because // the event cloak doesn't have to be attached to a base element width: this.wheelGraphBase.config.width, height: this.wheelGraphBase.config.height, cx: this.wheelGraphBase.config.cx, cy: this.wheelGraphBase.config.cy, resetPoint: this.clock.config.startAngle }); // Interval icon (changes the radius of an arc) this.intervalIcon = new IntervalIcon({ $el: $('.interval-icon'), graphData: this.graphData }); // Cause the graph data to reset every 60 seconds, too. $.subscribe(this.intervalIcon.channelId + '.timerReset', function() { _this.graphData.reset(); }); this.$innerNote = $('<div />', { 'class': 'wheel-graph__note inner'}); this.$innerNote.appendTo(this.wheelGraphBase.$el); this.$outerNote = $('<div />', { 'class': 'wheel-graph__note outer'}); this.$outerNote.appendTo(this.wheelGraphBase.$el); this.$mouseNote = $('<div />', { 'class': 'wheel-graph__note mouse'}); this.$mouseNote.appendTo(this.wheelGraphBase.$el); this.$mouseNote.html(''); $.subscribe('current_radial_line', function(e, d) { if(d.radiusScale) { var fixedPoint = 2; var suffix = ''; if(d.metric.alias === 'temperature' || d.metric.alias === 'humidity') { fixedPoint = 0; } if(d.metric.alias === 'temperature') { suffix = '°'; } if(d.metric.alias === 'humidity') { suffix = '%'; } _this.$innerNote.html(d.radiusScale.domain()[0].toFixed(fixedPoint) + suffix); _this.$outerNote.html(d.radiusScale.domain()[1].toFixed(fixedPoint) + suffix); } }); }, /** * Should be called if the associated GraphData changes. */ draw: function() { var _this = this; // Update the last updated label // var $lastUpdatedLabel = $('.interval-icon-label'); // $lastUpdatedLabel.html(moment(this.graphData.data[0].timestamp).format('hh:mm a')); // Refresh the timer. this.intervalIcon.setTimer(); var _timestamps = _.map(this.graphData.data, function(v) { return v.timestamp; }); this.clock.refresh(_timestamps); _.each(this.wheelGraphMetrics, function(v) { v.draw(); }); _.each(this.wheelGraphMetrics, function(v) { v.handle.reattach(); }); this.clock.setCurrentTimeFromAngle(360); } }); module.exports = WheelGraphComposite; <|start_filename|>lib/javascripts/backbone_components/histogram_metric_display.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ // var Backbone = require('../../bower_components/backbone/backbone'); var HistogramMetricDisplay = Backbone.View.extend({ initialize: function() { _.bindAll(this, 'reposition', 'updateValue'); this.handle = this.options.handle; this.metric = this.options.metric; this.$valueContainer = this.$el.find('.value-container'); this.listenTo(this.model, 'change:value', this.updateValue); $.subscribe(this.handle.channelId + '.moved', this.reposition); this.$histogram = this.$el.closest('.histogram'); this.invertPoint = this.$histogram.width() / 2; }, updateValue: function(e) { var fixedPoint = 2; if(this.metric.alias === 'temperature' || this.metric.alias === 'humidity') { fixedPoint = 0; } this.$valueContainer.html(this.model.get('value').toFixed(fixedPoint)); }, reposition: function(e, data) { // Update the x/y to match the handle's latest co-ordinates var _left = data.x; var _top = data.y; if(_left > this.invertPoint) { this.$el.css('marginLeft', 0 - this.$el.width() - 10).addClass('inverted'); } else { this.$el.css('marginLeft', '').removeClass('inverted'); } this.$el.css({ left: data.x, top: data.y }); } }); module.exports = HistogramMetricDisplay; <|start_filename|>lib/javascripts/graph_components/data_line.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /** * Draw a radial graph based on time & arbitary data */ var Util = require('./util'); /** * Draw a radial graph based on time & arbitary data */ var Util = require('./util'); /** * Draw a radial graph based on time & arbitary data */ var DataLine = Class.extend({ defaults: { base: null, min: 0, max: 100, offset: 0, inner_radius: 0, lineDataKey: 0, autoAttach: true, clock: null, // Instance of 'Clock' object for handling the time scale classes: { line: 'wheel-graph__line', group: 'wheel-graph__line-group' } }, init: function(options) { this.config = _.extend({ }, this.defaults, options); _.bindAll(this, 'redraw', 'findClosestPoints'); this.channelId = _.uniqueId('channel_'); this.base = this.config.base; this.clock = this.config.clock; this.metric = this.config.metric; this.model = this.config.model; this.delaySegment = this.config.delaySegment; this.lineDataKey = this.config.lineDataKey || 0; this.rangeData = null; $.subscribe(this.clock.channelId + '.timeChange', this.findClosestPoints); // Check if points have been provided on instantiation, // and draw the line if so. if(typeof this.config.points !== 'undefined' && this.config.length) { this.setPoints(this.config.points); } }, drawPath: function(data) { var line = d3.svg.line() .x(function(d) { return d[0]; }) .y(function(d) { return d[1]; }); var pathData = line(data); return pathData; }, /** * Don't perform any conversion by default. * (Because we're now treating angles as a simple unit) */ parseAngle: function(angle) { return angle; }, /** * Create a 'path dictionary' to store all relevent path data together */ setPathDict: function() { var pathDict = [ ]; var _this = this; var _delaySwitch = false; _.each(this.pathPoints, function(v, k) { var angle = _this.parseAngle(_this.lineData[k][_this.lineDataKey]); // var _startDelay = (_this.points[k]) ? (_this.points[k].startDelay || false) : false; // var _endDelay = (_this.points[k]) ? (_this.points[k].endDelay || false) : false; if(_this.points[k].startDelay) { _delaySwitch = true; } else if(_this.points[k].endDelay) { _delaySwitch = false; } pathDict.push({ angle: angle, normalisedAngle: _this.__normalizeAngle(angle), x: v[0], y: v[1], dataValue: _this.points[k], // startDelay: _startDelay, // endDelay: _endDelay, delayed: _delaySwitch }); }); return pathDict; }, setPoints: function(points) { this.points = points; if(!this.svg && this.config.autoAttach) { this.attach(); } this.redraw(); }, /** * Radial lines are normalised differently when inherited */ __normalizeAngle: function(angle) { return angle; }, /** * Reset the scales and redraw the line */ redraw: function(removeFirst) { var _this = this; removeFirst = removeFirst || false; if(removeFirst && this.svg) { this.group.remove(); this.svg.remove(); this.group = null; this.svg = null; this.attach(); } this.radiusScale = this.__createRadiusScale(); this.lineData = this.setData(); var pathData = this.drawPath(this.lineData); if(this.svg) this.svg.attr('d', pathData); this.pathPoints = Util.pathToPoints(pathData); // Capture a path dictionary to contain all useful information at once. this.pathDict = this.setPathDict(); _.each(window.lineTrails, function(v) { if(v.dataLine === _this) { v.draw(); } }); }, /** * Attach the SVG elements */ attach: function() { this.group = this.group || this.base.svg.append("svg:g") .attr("transform", "translate(" + (this.base.config.cx + this.config.offset) + "," + (this.base.config.cy) + ")") .classed(this.config.classes.group, true); this.svg = this.svg || this.group.append('path') .attr("class", this.config.classes.line + ' ' + this.config.alias); /** Boundary 1 **/ this.nextPointSVG = this.nextPointSVG || this.group.append('circle') .attr('class', 'handle') .attr('r', 3) .attr('fill', 'green'); /** Boundary 2 **/ this.prevPointSVG = this.prevPointSVG || this.group.append('circle') .attr('class', 'handle') .attr('r', 3) .attr('fill', 'red'); }, calculateDomain: function() { var _domain = [ ]; // Check if range data needs to be taken into account. if(this.rangeData) { var minOfMin = d3.min(this.rangeData, function(d) { var arr = [d.value]; if(d.min !== false) arr.push(d.min); if(d.max !== false) arr.push(d.max); return d3.min(arr); }); var maxOfMax = d3.max(this.rangeData, function(d) { var arr = [d.value]; if(d.min !== false) arr.push(d.min); if(d.max !== false) arr.push(d.max); return d3.max(arr); }); _domain = [minOfMin, maxOfMax]; } else { _domain = d3.extent(this.points, function(d) { return d.value; }); } var _diff = Math.abs(_domain[0] - _domain[1]); if(typeof this.metric.minDomainDifference !== 'undefined' && _diff < this.metric.minDomainDifference) { var _midpoint = _domain[0] + (_diff / 2); _domain[0] = _midpoint - (this.metric.minDomainDifference / 2); _domain[1] = _midpoint + (this.metric.minDomainDifference / 2); } // Apply any specific minimum boundaries if provided. if(typeof this.metric.domain !== 'undefined') { _domain[0] = _.min([_domain[0], this.metric.domain.min]); _domain[1] = _.max([_domain[1], this.metric.domain.max]); } return _domain; }, /** * Create a value scale */ __createRadiusScale: function() { var scale = d3.scale.linear(); scale.domain(this.calculateDomain()); scale.range([this.config.min, this.config.max]); return scale; }, /** * Loop through data and provide a d3 * compatible array of radius/angle */ setData: function() { var _this = this; return _.map(this.points, function(v, k) { var x = _this.clock.getAngleFromTime(v.date); var y = _this.radiusScale(v.value); return [x, y]; }); }, /** * Toggle the visibility of the entire group * (showing/hiding the handle and line itself) */ toggle: function(show) { if(this.group) { this.group.classed('hidden', !show); } if(this.delaySegment) { this.delaySegment.group.classed('hidden', !show); } }, toggleCurrent: function(current) { this.current = current ? true : false; if(this.current) { $.publish('current_radial_line', [this]); } }, /** * Use the radial line to track the current data point too */ findClosestPoints: function() { var _this = this; var nearestNextPoint, nearestPrevPoint; var currentAngle = this.__normalizeAngle(this.clock.currentAngle); if(this.current) { $.publish('current_data_line', [this]); } if(this.pathDict) { var isRadial = this.clock.config.radial; var last = this.pathDict[this.pathDict.length - 1].normalisedAngle; if(last === this.clock.config.startAngle && isRadial) last = this.clock.config.endAngle; var nextToLast = this.pathDict[this.pathDict.length - 2].normalisedAngle; var isTop = currentAngle === this.clock.config.startAngle || currentAngle === this.clock.config.endAngle; var isFirst = currentAngle < this.pathDict[0].normalisedAngle && currentAngle >= this.pathDict[1].normalisedAngle; var isLast = currentAngle >= last && currentAngle < nextToLast; // See if the current angle has gone outside the bounds of the data points. if(isRadial && currentAngle < last) { return false; } if(isRadial && (isTop || isFirst)) { nearestNextPoint = this.pathDict[1]; nearestPrevPoint = this.pathDict[0]; } else if(isRadial && isLast) { nearestPrevPoint = this.pathDict[this.pathDict.length - 2]; nearestNextPoint = this.pathDict[this.pathDict.length - 1]; } else { var sortedAngles = _.sortBy(this.pathDict, function(v) { return Math.abs(v.normalisedAngle - currentAngle); }); nearestNextPoint = _.find(sortedAngles, function(v) { return v.normalisedAngle <= currentAngle; }); nearestPrevPoint = _.find(sortedAngles, function(v) { return v.normalisedAngle > currentAngle; }); } if(nearestNextPoint && nearestPrevPoint) { this.nextPointSVG.attr('cx', nearestNextPoint.x).attr('cy', nearestNextPoint.y); this.prevPointSVG.attr('cx', nearestPrevPoint.x).attr('cy', nearestPrevPoint.y); // Add the vectors this.v1 = $V([nearestNextPoint.x, nearestNextPoint.y, 0]); this.v2 = $V([nearestPrevPoint.x - nearestNextPoint.x, nearestPrevPoint.y - nearestNextPoint.y, 0]); // Publish new stuff to radial line this.nearestPrevPoint = nearestPrevPoint; this.nearestNextPoint = nearestNextPoint; $.publish(this.channelId + '.dataPointFound', [{ hide: this.nearestPrevPoint.delayed, model: this.model }]); } } } }); module.exports = DataLine; <|start_filename|>lib/javascripts/graph_components/graph_data.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ var GraphData = Class.extend({ defaults: { data: [ ], onReset: null, onError: function() { }, reverseOrder: false, apiHost: null, endpointAlias: null, apiConfig: null, isWheel: false, throttle: 0, minDifference: 1500 }, init: function(options) { // _.bindAll(this, '__setSteps'); this.config = _.extend({ }, this.defaults, options); this.data = this.config.data; this.steps = null; this.endpointAlias = this.config.endpointAlias; if(this.config.apiConfig && this.endpointAlias !== null) { this.reset(); } }, filterByRange: function(opts) { this.endpointAlias = opts.alias; this.steps = opts.steps; this.rangeUnit = opts.rangeUnit; this.rangeValue = opts.rangeValue; this.reset(); }, reset: function() { var _this = this; this.loading = true; var _url = ''; if(this.config.apiConfig.host) _url += this.config.apiConfig.host; if(this.config.apiConfig.uriPrefix) _url += '/' + this.config.apiConfig.uriPrefix; _url += '/' + this.endpointAlias + '.json'; $.ajax({ url: _url, dataType: 'json', cache: false, success: function(data, status, xhr) { _this.loading = false; var _data = [ ]; var i = 0; var _obj = { }; var momentA, momentB, diff; for(i in data) { i = parseInt(i, null); if(i && _this.config.isWheel) { momentA = moment(data[i].timestamp); momentB = moment(data[i - 1].timestamp); diff = momentA.diff(momentB, 'minutes'); while(diff > 5) { _obj = {}; for (var prop in data[i-1]) { _obj[prop] = null; } momentB = momentB.add('minutes', 5); diff = momentA.diff(momentB, 'minutes'); _obj.timestamp = momentB.valueOf(); _data.push(_obj); } } if(!_this.config.throttle || (i % _this.config.throttle === 0) || i === 0 || i === null || (i+1 === data.length)) { _data.push(data[i]); } } if(_data.length && !_.isEqual(_data, _this.data)) { if(_this.config.reverseOrder && _data[0].timestamp < _data[_data.length-1].timestamp) { _data.reverse(); } _this.data = _data; if(typeof _this.config.onReset === 'function') { _this.config.onReset.call(_this); } } else { if(typeof _this.config.onError === 'function') { _this.config.onError.call(_this); } } }, error: function() { if(typeof _this.config.onError === 'function') { _this.config.onError.call(_this); } } }); }, formatAsMetric: function(metricAlias, prefix) { var _this = this; var data = [ ]; prefix = prefix || ''; _.each(this.data, function(v, k) { var obj = { }; var _value = (typeof v[prefix + metricAlias] !== 'undefined') ? v[prefix + metricAlias] : false; obj = { value: _value, date: v.timestamp }; if(prefix) { obj.key = prefix; } data.push(obj); }); this._setDelayBoundariesForMetric(data, metricAlias); return data; }, _setDelayBoundariesForMetric: function(metricPoints, metricAlias) { var _this = this; var _delaySwitch = false, _timestampDifference, _previousMetric, _startValue, _startKey; _.each(metricPoints, function(v, k) { var _isDelayEnd = v.value !== null && _delaySwitch === true; var _isDelayStart = v.value === null && _delaySwitch === false; var _now = moment(); var _mininumDifference = _this.config.minDifference * 1000; // We'll shiv the previous value into the ones which don't have a value. (Pt. 1) if(_isDelayStart) { _startKey = k; if(metricPoints[k-1]) { _startValue = metricPoints[k-1].value; } else { _startValue = 0; } } // Get the previous metric if the delay has just ended. if(_isDelayEnd) { for(var i = (k-1); i >= _startKey; i--) { // We'll shiv the previous value into the ones which don't have a value. (Pt. 2) metricPoints[i].value = _startValue; if(metricPoints[i].startDelay) { _previousMetric = metricPoints[i]; _timestampDifference = Math.abs(v.date - _previousMetric.date); break; } } if(_timestampDifference < _mininumDifference) { // Reset the start delay if the delay isn't significant enough. _previousMetric.startDelay = false; _isDelayEnd = false; _delaySwitch = false; } } v.startDelay = _isDelayStart; v.endDelay = _isDelayEnd; if(_isDelayStart) { _delaySwitch = true; } else if(_isDelayEnd) { _delaySwitch = false; } }); } }); module.exports = GraphData; <|start_filename|>lib/javascripts/graph_components/wheel_graph_metric.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ var RadialLine = require('./radial_line'); var DelaySegment = require('./delay_segment'); var LineTrail = require('./line_trail'); var Handle = require('./handle'); // Backbone var GroupedMetric = require('../backbone_components/grouped_metric'); var DataLineView = require('../backbone_components/data_line_view'); var TemperatureMetricDisplay = require('../backbone_components/temperature_metric_display'); var PercentageMetricDisplay = require('../backbone_components/percentage_metric_display'); var MetricDisplay = require('../backbone_components/metric_display'); var WheelGraphMetric = Class.extend({ defaults: { metric: null, base: null, clock: null }, init: function(options) { this.config = _.extend({ }, this.defaults, options); this.metric = this.config.metric; this.base = this.config.base; this.clock = this.config.clock; this.collection = this.config.collection; this.displayGroup = this.config.displayGroup; this.guideline = this.config.guideline; this.donut = this.config.donut; this.graphData = this.config.graphData; this.metricPoints = this.graphData.formatAsMetric(this.metric.alias); this.model = new GroupedMetric({ metric: this.metric }); this.radialLine = new RadialLine({ base: this.base, min: this.base.config.inner_radius, max: this.base.config.outer_radius, points: this.metricPoints, alias: this.metric.alias, clock: this.clock, model: this.model, metric: this.metric, lineDataKey: 1 }); this.delaySegment = new DelaySegment({ base: this.base, clock: this.clock, donut: this.donut, radial: true, metric: this.metric, metricPoints: this.metricPoints }); this.radialLine.delaySegment = this.delaySegment; this.lineTrail = new LineTrail({ dataLine: this.radialLine, classes: { line: 'wheel-graph__line-trail' } }); window.lineTrails.push(this.lineTrail); this.collection.add(this.model); this.$metricDisplay = this.displayGroup.$el.find('.metric-display[data-metric="' + this.metric.alias + '"]'); this.radialLineView = new DataLineView({ radialLine: this.radialLine, model: this.model }); var viewProps = { el: this.$metricDisplay[0], group: this.displayGroup, model: this.model, dataLineView: this.radialLineView }; var viewMode = this.$metricDisplay.data('view-mode'); if(viewMode === 'temperature') { this.metricDisplayView = new TemperatureMetricDisplay(viewProps); } else if(viewMode === 'percentage') { this.metricDisplayView = new PercentageMetricDisplay(viewProps); } else { this.metricDisplayView = new MetricDisplay(viewProps); } this.handle = new Handle({ base: this.base, radialLine: this.radialLine, alias: this.metric.alias, guideline: this.guideline }); }, draw: function() { var _data = this.graphData.formatAsMetric(this.metric.alias); this.metricPoints = _data; this.delaySegment.metricPoints = this.metricPoints; this.radialLine.setPoints(_data); this.delaySegment.draw(); } }); module.exports = WheelGraphMetric; <|start_filename|>lib/javascripts/backbone_components/grouped_metric.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ // var Backbone = require('../../bower_components/backbone/backbone'); var GroupedMetric = Backbone.Model.extend({ defaults: { selected: null, highlighted: null, metric: null, value: null }, initialize: function() { }, setValueAsAverage: function(prev, next) { this.set('value', (prev + next) / 2); } }); module.exports = GroupedMetric; <|start_filename|>lib/javascripts/graph_components/graph_base.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ var GraphBase = Class.extend({ defaults: { inner_radius: 70, outer_radius: null }, init: function(options) { this.config = _.extend({ }, this.defaults, options); this.svg = null; // Expose some config vars as properties this.$el = this.config.$el; this.config.cx = this.config.width / 2; this.config.cy = this.config.height / 2; if(this.config.outer_radius === null) { this.config.outer_radius = this.config.cx; } this.draw(); }, draw: function() { this.svg = d3 .select(this.$el[0]) .append("svg:svg") .attr("width", this.config.width) .attr("height", this.config.height); } }); module.exports = GraphBase; <|start_filename|>lib/javascripts/graph_components/guideline.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ var GraphComponent = require('./graph_component'); /** * Draws a projected line from an origin * to a position that's based on a specified angle */ var Guideline = GraphComponent.extend({ defaults: { lineFn: null, dataFn: null, height: 100, offset: 0, minPos: -1, maxPos: null, autoAttach: true, position: -90, // Default position clock: null, // Clock instance cx: null, // X co-ordinate of the start point cy: null, // Y co-ordinate of the start point classes: { // A set of strings used for adding classes to DOM nodes line: 'guideline' } }, init: function(options) { var _this = this; this._super(options); _.bindAll(this, 'goToCurrentPosition'); this.clock = this.config.clock; // Set the default radii and origins this.__inheritFromBase(['cx', 'cy', 'inner_radius', 'outer_radius']); if(this.config.autoAttach) { this.attach(); } this.__setPathFromPosition(this.config.position); this.currentPosition = this.config.position; this.render(); // Make sure the guideline updates whenever the time is changed. $.subscribe(this.clock.channelId + '.timeChange', this.goToCurrentPosition); }, goToCurrentPosition: function(e) { this.goToPosition(this.clock.currentAngle); }, /** * Recalculate and render the guideline * based on a specified co-ordinate */ goToPosition: function(pos) { this.__setPathFromPosition(pos); this.currentPosition = pos; // Add the vectors this.v1 = $V([this.guidePoints[0][0], this.guidePoints[0][1], 0]); this.v2 = $V([this.guidePoints[1][0] - this.guidePoints[0][0], this.guidePoints[1][1] - this.guidePoints[0][1], 0]); this.render(); }, __setPathFromPosition: function(pos) { // Set the default path data var x = _.max([pos, this.config.minPos]); if(this.config.maxPos !== null) { x = _.min([x, this.config.maxPos]); } this.guidePoints = [ [x, 0], [x, this.config.height] ]; }, /** * Attach the new SVG nodes to the base element */ attach: function() { // Add a new <g> and move it to the specified origin this.svgGroup = this.base.svg.append("svg:g") .attr("transform", "translate(" + (this.config.cx + this.config.offset) + "," + this.config.cy + ")"); // Append the <path> inside of the new <g> this.svg = this.svgGroup.append('svg:line') .attr("class", this.config.classes.line); }, /** * Render the attributes for the guideline */ render: function() { if(this.svg) { this.svg.attr('x1', this.guidePoints[0][0]) .attr('y1', this.guidePoints[0][1]) .attr('x2', this.guidePoints[1][0]) .attr('y2', this.guidePoints[1][1]); } } }); module.exports = Guideline; <|start_filename|>lib/javascripts/graph_components/split_labels.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ var GraphComponent = require('./graph_component'); var SplitLabels = GraphComponent.extend({ defaults: { $el: null, steps: 7, width: null, suffix: ' days ago', classes: { label: 'histogram-split-labels__label' } }, init: function(options) { this.config = _.extend({ }, this.defaults, options); this.steps = this.config.steps; this.suffix = this.config.suffix; this.$el = this.config.$el; }, draw: function(opts) { this.$el.empty(); this.steps = typeof opts.steps !== 'undefined' ? opts.steps : this.config.steps; this.suffix = typeof opts.suffix !== 'undefined' ? opts.suffix : this.config.suffix; this.rangeValue = typeof opts.rangeValue !== 'undefined' ? opts.rangeValue : null; var i; var $el; var _oneStep = this.config.width / this.steps; var label; for(i = 0; i < this.steps; i++) { $el = $('<div />', { 'class': this.config.classes.label }); $el.css('left', _oneStep * i); if(this.rangeValue) { $el.html(this.rangeValue - (this.rangeValue / this.steps * i)); } this.$el.append($el); } } }); module.exports = SplitLabels; <|start_filename|>lib/javascripts/graph_components/date_label.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ var DateLabel = Class.extend({ defaults: { format: 'MMMM Do, YYYY', padding: 15, border: 2, minPos: 0, maxPos: null, classes: { inner: 'histogram-date-label__inner', value: 'value-container', inverted: 'inverted' } }, init: function(options) { var _this = this; this.config = _.extend({ }, this.defaults, options); this.clock = this.config.clock; this.$el = this.config.$el; this.$inner = this.$el.find('.' + this.config.classes.inner); this.$value = this.$el.find('.' + this.config.classes.value); this.width = null; $.subscribe(this.clock.channelId + '.timeChange', function(e) { var _angle = _this.clock.currentAngle; _this.invertPoint = _this.$el.width() / 2; var _width = _this.$inner.width(); if(_width !== _this.width || _this.width === null) { _this.width = _width; } if(_angle > _this.invertPoint) { _this.$inner.css('marginLeft', 0 - _width + _this.config.border - _this.config.padding).addClass(_this.config.classes.inverted); } else { _this.$inner.css('marginLeft', '').removeClass(_this.config.classes.inverted); } var _left = _.max([_angle + _this.config.border, _this.config.minPos]); if(_this.config.maxPos !== null) _left = _.min([_left, _this.config.maxPos]); _this.$inner.css('left', _left); _this.$value.html(_this.clock.currentTime.format(_this.config.format)); }); } }); module.exports = DateLabel; <|start_filename|>lib/javascripts/graph_components/histogram_metric.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ var Guideline = require('./guideline'); var DataLine = require('./data_line'); var BackgroundAxis = require('./background_axis'); var RangeLine = require('./range_line'); var DelaySegment = require('./delay_segment'); var Handle = require('./handle'); // Backbone var GroupedMetric = require('../backbone_components/grouped_metric'); var DataLineView = require('../backbone_components/data_line_view'); var HistogramMetricDisplay = require('../backbone_components/histogram_metric_display'); var HistogramMetric = Class.extend({ defaults: { }, init: function(options) { var _this = this; this.config = _.extend({ }, this.defaults, options); this.metric = this.config.metric; this.collection = this.config.collection; this.clock = this.config.clock; this.graphData = this.config.graphData; this.eventCloak = this.config.eventCloak; this.$el = $('.histogram__inner[data-metric="' + this.metric.alias + '"]'); this.$outer = this.$el.closest('.histogram'); this.data = [ ]; this.rangeData = [ ]; this.metricPoints = [ ]; /** * Create a 'fake base'... because we don't need any particular appearance for the histograms * ... but we do need to reference the canvas in the same way as WheelGraphBase */ this.svg = d3.select(this.$el[0]).append("svg:svg").attr("width", this.$el.width()).attr("height", this.$el.height()); // this.svg.attr('transform', 'translate(' + -18 + ',' + 0 + ')'); var _baseOffset = 16; this.base = { svg: this.svg.append('svg:g').attr('width', this.$el.width() - _baseOffset).attr('transform', 'translate(' + _baseOffset + ',' + 0 + ')'), config: { cx: 0, cy: 0} }; // Create the grouped metric for the histogram // this is used to store the values provided by the UI // (as opposed to the constant data provided by the feed) this.model = new GroupedMetric(); this.collection.add(this.model); /** * Create the histogram guideline (a straight line which follows the mouse) */ this.guideline = new Guideline({ base: this.base, height: this.$el.height(), clock: this.clock, maxPos: this.clock.config.startAngle - 2, autoAttach: false, classes: { line: 'histogram__guideline' } }); this.dataLine = new DataLine({ clock: this.clock, max: 0, min: this.$el.height(), base: this.base, alias: this.metric.alias, metric: this.metric, points: this.metricPoints, offset: 0, classes: { line: 'histogram__data-line', group: 'histogram__data-line-group' }, autoAttach: false // Lazy attachment so it can be over the range line }); // Create a background for the Y axis this.backgroundAxisY = new BackgroundAxis({ base: this.base, dataLine: this.dataLine, clock: this.clock, rangeLabels: true, max: this.clock.config.startAngle, $outer: this.$outer, offset: { x: 0, y: 0 } }); this.backgroundAxisX = new BackgroundAxis({ base: this.base, dataLine: this.dataLine, clock: this.clock, $outer: this.$outer, horizontal: true, steps: 3, max: this.$el.height() }); this.rangeLine = new RangeLine({ dataLine: this.dataLine, base: this.base, max: 0, min: this.$el.height(), alias: this.metric.alias, autoAttach: true, clock: this.clock, metric: this.metric }); this.dataLine.attach(); this.delaySegment = new DelaySegment({ base: this.base, clock: this.clock, metric: this.metric, metricPoints: this.metricPoints }); this.guideline.attach(); this.handle = new Handle({ base: this.base, radialLine: this.dataLine, alias: this.metric.alias, guideline: this.guideline }); this.lineView = new DataLineView({ radialLine: this.dataLine, model: this.model }); // Create a view for the histogram metric this.metricDisplay = new HistogramMetricDisplay({ el: this.$outer.find('.histogram__value-label')[0], handle: this.handle, model: this.model, metric: this.metric }); // Fade out the histogram title if the time is near it var $title = this.$outer.find('.histogram__title'); $.subscribe(this.clock.channelId + '.timeChange', function(e) { var _angle = _this.clock.currentAngle; var _left = _.max([_angle + 2, 0]); var nearTitle = (_this.clock.currentAngle / _this.clock.config.startAngle) < 0.35; $title.toggleClass('dim', nearTitle); }); /************************ ************************* /// COPIED FROM WHEEL_GRAPH_COMPOSITE.JS ************************/ /// Create a quick inverted scale based on the current data line var setScales = function() { if(!_this.dataLine.radiusScale) { return false; } var domain = _this.dataLine.radiusScale.range(); var range = _this.dataLine.radiusScale.domain(); var scale = d3.scale.linear(); scale.domain(domain).range(range); return scale; }; /************************************* *************************************/ this.mouseLabel = { }; this.mouseLabel.$cloak = $('.event-cloak__listing[data-metric="' + this.config.metric.alias + '"]'); this.mouseLabel.maxX = this.mouseLabel.$cloak.width(); this.mouseLabel.maxY = this.mouseLabel.$cloak.height() - 2; this.mouseLabel.minX = this.mouseLabel.$cloak.data('left'); this.mouseLabel.minY = this.mouseLabel.$cloak.data('top'); this.mouseLabel.$el = this.$outer.find('.histogram__mouse-label'); this.mouseLabel.$value = this.mouseLabel.$el.find('.value-container'); this.mouseLabel.$histogram = $('.histogram__inner[data-metric="' + this.config.metric.alias + '"]').closest('.histogram'); $.subscribe(this.eventCloak.channelId + '.movementTracked', function() { if(!_this.mouseLabel.scale) { _this.mouseLabel.scale = setScales(); } // If it's still not found, then return false. if(!_this.mouseLabel.scale) { return false; } if(typeof _this.mouseLabel.mouseY !== 'undefined') { _this.mouseLabel.$el.css({ 'top': _this.mouseLabel.mouseY || 0, 'left': _this.mouseLabel.mouseX || 0 }); var fixedPoint = 2; if(_this.metric.alias === 'temperature' || _this.metric.alias === 'humidity') { fixedPoint = 0; } _this.mouseLabel.$value.html(_this.mouseLabel.scale(_this.mouseLabel.mouseY).toFixed(fixedPoint)); } }); // Show the mouse labels this.eventCloak.$el.mousemove(function(ev) { var _mouseX = ev.pageX - $(this).offset().left; var _mouseY = ev.pageY - $(this).offset().top; if(_this.mouseLabel.$histogram.hasClass('hover')) { _this.mouseLabel.mouseX = _mouseX - _this.mouseLabel.minX; _this.mouseLabel.mouseY = _mouseY - _this.mouseLabel.minY; // Apply boundaries _this.mouseLabel.mouseX = _.max([0, _this.mouseLabel.mouseX]); _this.mouseLabel.mouseX = _.min([_this.mouseLabel.maxX, _this.mouseLabel.mouseX]); _this.mouseLabel.mouseY = _.max([0, _this.mouseLabel.mouseY]); _this.mouseLabel.mouseY = _.min([_this.mouseLabel.maxY, _this.mouseLabel.mouseY]); } }); $.subscribe(this.dataLine.channelId + '.dataPointFound', function(e, opts) { _this.mouseLabel.$el.toggleClass('hidden', opts.hide); $(_this.metricDisplay.el).toggleClass('hidden', opts.hide); }); }, refreshData: function() { this.data = this.graphData.formatAsMetric(this.metric.alias); var _minData = this.graphData.formatAsMetric(this.metric.alias, 'min_'); var _maxData = this.graphData.formatAsMetric(this.metric.alias, 'max_'); this.rangeData = _minData.concat(_maxData); // this.metric.data = this.data; this.metricPoints = this.data; this.delaySegment.metricPoints = this.metricPoints; this.dataLine.points = this.metricPoints; var _this = this; this.dataLine.rangeData = []; _.each(this.data, function(v,k) { _this.dataLine.rangeData.push({ min: _minData[k].value, max: _maxData[k].value, value: v.value }); }); }, draw: function() { this.refreshData(); this.dataLine.setPoints(this.data); this.rangeLine.setPoints(this.rangeData); // Must be fired after dataLine // this.dataLine.radiusScale.domain(this.dataLine.calculateDomain()); // this.rangeLine.radiusScale.domain(this.dataLine.calculateDomain()); // this.rangeLine.draw(true); // this.dataLine.redraw(true); this.backgroundAxisY.setLines({ scale: this.dataLine.radiusScale }); this.backgroundAxisX.setLines({ scale: this.clock.timeScale, steps: this.graphData.steps }); this.delaySegment.draw(); } }); module.exports = HistogramMetric; <|start_filename|>lib/javascripts/graph_components/interval_icon.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ var Util = require('./util'); var IntervalIcon = Class.extend({ defaults: { $el: null, width: 26, height: 26, inner_radius: 6, outer_radius: 13, graphData: null, cy: null, cx: null, intervalMs: 60000, timerMs: 1000, classes: { svg: 'interval-icon__svg', arc: 'interval-icon__arc' } }, init: function(options) { var _this = this; this.config = _.extend({ }, this.defaults, options); _.bindAll(this, 'updateArc'); if(this.config.cx === null) this.config.cx = this.config.width / 2; if(this.config.cy === null) this.config.cy = this.config.height / 2; this.$el = this.config.$el; this.currentTimer = 0; this.graphData = this.config.graphData; this.svg = d3.select(this.$el[0]).append("svg:svg"); this.svg.classed(this.config.classes.svg, true); this.svg.attr('width', this.config.width).attr('height', this.config.height); this.arc = d3.svg.arc() .innerRadius(this.config.inner_radius) .outerRadius(this.config.outer_radius) .startAngle(0) .endAngle(function(d, i) { return d.value; }); this.data = (function() { var _arr = [ ]; var _degrees; for(var i = 0; i < (_this.config.intervalMs / _this.config.timerMs); i++) { _degrees = ((_this.config.timerMs / _this.config.intervalMs) * 360) * i; _arr.push({ value: Util.toRadians(_degrees) }); } return _arr; })(); this.svg.append("path") .data(this.data) .attr("d", this.arc) .attr("transform", "translate(" + this.config.cx + "," + this.config.cy + ")") .classed(this.config.classes.arc, true); this.interval = null; this.$timer = $('#countdown-timer'); this.$standardMsg = $('#standard-msg'); this.$processingMsg = $('#processing-msg'); }, displayError: function() { var _this = this; this.$processingMsg.show(); this.$standardMsg.hide(); this.$timer.html((_this.config.intervalMs / 1000) + ' seconds'); this.updateArc(); setTimeout(function() { _this.$processingMsg.hide(); _this.$standardMsg.show(); _this.setTimer(); }, 3000); }, updateArc: function() { this.svg.selectAll('.' + this.config.classes.arc) // .transition().duration(this.config.timerMs) .attr('d', this.arc(this.data[this.currentTimer])); }, setTimer: function() { (function(_this) { if(_this.interval) window.clearInterval(_this.interval); _this.interval = setInterval(function() { _this.updateArc(); var ms = _this.config.intervalMs - (_this.currentTimer * _this.config.timerMs); _this.$timer.html((ms / 1000) + ' seconds'); if((_this.currentTimer + 1) === (_this.config.intervalMs / _this.config.timerMs)) { _this.currentTimer = 0; _this.$timer.html((ms / 1000) + ' seconds'); $.publish(_this.channelId + '.timerReset'); clearInterval(_this.interval); } else { _this.currentTimer ++; } }, _this.config.timerMs); })(this); } }); module.exports = IntervalIcon; <|start_filename|>lib/javascripts/graph_components/range_line.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ var GraphComponent = require('./graph_component'); var RangeLine = GraphComponent.extend({ defaults: { dataLine: null, clock: null, min: 0, max: 100, offset: 0, autoAttach: true, classes: { line: 'histogram__range-line', group: 'histogram__range-line-group' } }, init: function(options) { var _this = this; _.bindAll(this, 'draw'); this._super(options); this.dataLine = this.config.dataLine; this.clock = this.config.clock; this.metric = this.config.metric; this.nest = d3.nest() .key(function(d) { return d.key; }); this.stack = d3.layout.stack() .offset("zero") .values(function(d) { return d.values; }) .x(function(d) { return d.date; }) .y(function(d) { return d.value; }); this.area = d3.svg.area() .x(function(d) { return _this.clock.getAngleFromTime(d.date); }) .y0(function(d) { return _this.radiusScale(d.y0); }) .y1(function(d) { return _this.radiusScale(d.y); }); if(this.config.autoAttach) { this.attach(); } }, attach: function() { this.group = this.group || this.base.svg.append("svg:g") .attr("transform", "translate(" + (this.base.config.cx + this.config.offset) + "," + (this.base.config.cy) + ")") .classed(this.config.classes.group, true); }, draw: function() { var _this = this; if(!this.points) { return false; } this.radiusScale = this.__createRadiusScale(); this.group.selectAll("." + _this.config.classes.line).remove(); this.group.selectAll("." + _this.config.classes.line) .data(this.points) .enter().append("path") .attr("d", function(d) { return _this.area(d.values); }) .attr("class", this.config.classes.line + ' ' + this.config.alias); }, setPoints: function(range) { range = range || [ ]; if(range.length) { this.data = range; this.points = this.stack(this.nest.entries(this.data)); } this.attach(); this.draw(); }, /** * Create a value scale based on DataLine */ __createRadiusScale: function() { var scale = d3.scale.linear(); var _domain = this.dataLine.radiusScale.domain(); scale.domain(_domain); /***********************************************/ scale.range([this.config.min, this.config.max]); return scale; } }); module.exports = RangeLine; <|start_filename|>lib/javascripts/power_dashboard.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ var WheelGraphComposite = require('./graph_components/wheel_graph_composite'); var HistogramsComposite = require('./graph_components/histograms_composite'); AnimationFrame.shim(); var PowerDashboard = Class.extend({ defaults: { wheelGraphEndpointAlias: '24-hours', wheelGraph: true, histograms: true, apiConfig: null, metrics: null }, init: function(options) { var wheelGraph, histograms; this.config = _.extend({ }, this.defaults, options); if(!Modernizr.svg) { return false; } if(!this.config.apiConfig || !this.config.metrics || !this.config.metrics.length) { return false; } if(this.config.wheelGraph) { wheelGraph = new WheelGraphComposite({ endpointAlias: this.config.wheelGraphEndpointAlias, metrics: this.config.metrics, apiConfig: this.config.apiConfig }); window.wheelGraph = wheelGraph; } if(this.config.histograms) { histograms = new HistogramsComposite({ metrics: this.config.metrics, apiConfig: this.config.apiConfig }); window.histograms = histograms; } // Handle all graph animations (minimise animation requests) window.requestAnimationFrame(function doRedraw() { window.requestAnimationFrame(doRedraw); if(wheelGraph && wheelGraph.eventCloak.isMouseOver) wheelGraph.eventCloak.trackMovement.call(wheelGraph.eventCloak); if(histograms && histograms.eventCloak.isMouseOver) histograms.eventCloak.trackMovement.call(histograms.eventCloak); TWEEN.update(); }); } }); window.PowerDashboard = PowerDashboard; exports = PowerDashboard; <|start_filename|>lib/javascripts/graph_components/donut.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ var GraphComponent = require('./graph_component'); var Donut = GraphComponent.extend({ defaults: { base: null, width: null, height: null, cx: null, cy: null, classes: { donut: 'wheel-graph__donut', hour_strokes_set: 'wheel-graph__hour-stroke-set', hour_strokes: 'wheel-graph__hour-stroke' }, inner_radius: null, outer_radius: null, hours: 24 }, init: function(options) { this._super(options); this.base = this.config.base; this.__inheritFromBase(['width', 'height', 'cx', 'cy', 'inner_radius', 'outer_radius']); this.draw(); }, // Draw a donut shape using a full-degree SVG arc. draw: function(c) { var arc, donut; arc = d3.svg.arc() .innerRadius(this.config.inner_radius) .outerRadius(this.config.outer_radius) .startAngle(0) .endAngle(2 * Math.PI); donut = this.base.svg.append("svg:g") .attr("class", this.config.classes.donut); donut.append("path") .attr("d", arc) .attr("transform", "translate(" + this.config.cx + "," + this.config.cy + ")"); this.drawStrokes(); return donut; }, drawStrokes: function() { var max = (2 * Math.PI); var step = (( 2 * Math.PI) / this.config.hours); var group = this.base.svg.append('svg:g') .attr('class', this.config.classes.hour_strokes_set); // start at angle 0 radians, to a maximum of 2*pi radians, go up in 24 steps for (var a = 0; a < max; a += step) { group.append("svg:line") .attr("x1", this.config.cx + Math.sin(a)*this.config.inner_radius) .attr("y1", this.config.cy + Math.cos(a)*this.config.inner_radius) .attr("x2", this.config.cx + Math.sin(a)*(this.config.outer_radius)) .attr("y2", this.config.cy + Math.cos(a)*(this.config.outer_radius)) .attr('class', this.config.classes.hour_strokes); } } }); module.exports = Donut; <|start_filename|>lib/javascripts/graph_components/date_filter_nav.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ var DateFilterNav = Class.extend({ init: function(options) { var _this = this; this.config = _.extend({ }, this.defaults, options); this.$el = this.config.$el; this.graphData = this.config.graphData; this.splitLabels = this.config.splitLabels; this.$ancs = this.$el.find('a[data-range]'); this.$ancs.click(function(e) { var $a = $(this); e.preventDefault(); _this.$ancs.removeClass('current'); $a.addClass('current'); _this.graphData.filterByRange({ alias: $a.data('range'), steps: $a.data('steps'), rangeUnit: $a.data('unit'), rangeValue: $a.data('range-value') }); _this.splitLabels.draw({ steps: $a.data('steps'), suffix: $a.data('suffix'), rangeValue: $a.data('range-value') }); }); if(this.$ancs.filter('.current').length) { this.$ancs.filter('.current').click(); } } }); module.exports = DateFilterNav; <|start_filename|>lib/javascripts/backbone_components/metric_display_group.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ // var Backbone = require('../../bower_components/backbone/backbone'); var MetricDisplayGroup = Backbone.View.extend({ initialize: function() { this.listenTo(this.collection, 'change:selected', this.toggleFilterMode, this); }, toggleFilterMode: function(mode) { var selectedModels = this.collection.models.filter(function(v) { return v.get('selected') === true; }); var $heroFeature = this.$el.closest('.hero-feature'); $heroFeature.toggleClass('item-selected', !!selectedModels.length); } }); module.exports = MetricDisplayGroup; <|start_filename|>lib/javascripts/graph_components/delay_segment.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ var GraphComponent = require('./graph_component'); var Util = require('./util'); var DelaySegment = GraphComponent.extend({ defaults: { cy: null, cx: null, clock: null, base: null, metric: null, donut: null, radial: false, classes: { group: 'delay-segment', arc: 'delay-segment__arc' } }, init: function(options) { this._super(options); this.points = [ ]; // Instance refs this.metric = this.config.metric; this.metricPoints = this.config.metricPoints; this.clock = this.config.clock; this.donut = this.config.donut; this.base = this.config.base; this.__inheritFromBase(['cx', 'cy']); this.group = this.base.svg.append('svg:g') .attr('class', this.config.classes.group); }, buildPoints: function() { var _points = [ ]; var _this = this; var i = 0; if(this.metricPoints) { _.each(this.metricPoints, function(v, k) { if(v.startDelay === true) { _points[i] = {start: v.date}; } else if(v.endDelay === true) { _points[i].end = v.date; i++; // Move on to the next array element } }); this.points = _points; } }, draw: function() { var _this = this; var _shape; this.buildPoints(); if(this.config.radial) { _shape = d3.svg.arc() .innerRadius(this.donut.config.inner_radius) .outerRadius(this.donut.config.outer_radius) .startAngle(function(d) { return Util.toRadians(_this.clock.timeScale(d.start)); }) .endAngle(function(d) { return Util.toRadians(_this.clock.timeScale(d.end)); }); this.group.selectAll("." + this.config.classes.arc).remove(); this.group.selectAll("." + this.config.classes.arc) .data(this.points).enter() .append("path") .attr("d", _shape) .attr("transform", "translate(" + this.config.cx + "," + this.config.cy + ")") .classed(this.config.classes.arc, true); } else { this.group.selectAll("." + this.config.classes.arc).remove(); this.group.selectAll("." + this.config.classes.arc) .data(this.points).enter() .append("svg:rect") .attr('x', function(d) { return _this.clock.timeScale(d.end || _this.clock.timeScale.domain()[1]); }) .attr('y', 0) .attr('width', function(d) { return _this.clock.timeScale(d.start || _this.clock.timeScale.domain()[0]) - _this.clock.timeScale(d.end || _this.clock.timeScale.domain()[1]); }) .attr('height', 120) .attr("transform", "translate(" + this.config.cx + "," + this.config.cy + ")") .classed(this.config.classes.arc, true); } } }); module.exports = DelaySegment; <|start_filename|>lib/javascripts/graph_components/histograms_composite.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ var GraphData = require('./graph_data'); var Clock = require('./clock'); var SplitLabels = require('./split_labels'); var DateFilterNav = require('./date_filter_nav'); var DateLabel = require('./date_label'); var EventCloak = require('./event_cloak'); var HistogramMetric = require('./histogram_metric'); // Backbone var MetricGroup = require('../backbone_components/metric_group'); var HistogramsComposite = Class.extend({ defaults: { endpointAlias: null, metrics: null, apiConfig: null }, init: function(options) { var _this = this; this.config = _.extend({ }, this.defaults, options); this.metrics = this.config.metrics; _.bindAll(this, 'draw'); this.$el = $('.histogram-group'); this.graphData = new GraphData({ endpointAlias: this.config.endpointAlias, onReset: this.draw, reverseOrder: true, apiConfig: this.config.apiConfig }); this.histogramMetrics = [ ]; this.metricGroup = new MetricGroup(); /** * The histogram clock */ this.clock = new Clock({ endAngle: 0, startAngle: this.$el.width() }); // Split labels this.splitLabels = new SplitLabels({ $el: $('.histogram-split-labels'), width: this.clock.config.startAngle }); // Date filters var dateFilter = new DateFilterNav({ $el: $('[data-behavior="filter_data_range"]'), graphData: this.graphData, splitLabels: this.splitLabels }); // Date label this.$dateLabel = new DateLabel({ clock: this.clock, $el: $('.histogram-date-label'), maxPos: this.clock.config.startAngle }); var $eventCloak = $('<div class="histogram-group__event-cloak" />').prependTo(this.$el); $.each(this.metrics, function(k, v) { $eventCloak.append('<div class="event-cloak__listing" data-metric="' + v.alias + '"></div>'); }); this.eventCloak = new EventCloak({ animate: true, clock: this.clock, $el: $eventCloak, width: $eventCloak.width(), height: $eventCloak.height(), cx: 0, cy: 0, offset: 0, angular: false, resetPoint: this.clock.config.endAngle, cloakOffset: 18 }); // Event cloaking for mouse label handling var $eventCloakListings = $eventCloak.find('.event-cloak__listing'); // Cache the co-ordinates $eventCloakListings.each(function() { var $this = $(this); $this.data('top', $this.position().top); $this.data('left', $this.position().left); $this.data('right', $this.position().left + $this.outerWidth()); $this.data('bottom', $this.position().top + $this.outerHeight()); $this.data('histogram', $('.histogram[data-metric="' + $this.data('metric') + '"]')); }); // Prevent pointer events completely. // (IE bug, so have to hide instead of using CSS) $eventCloakListings.hide(); $eventCloak.mousemove(function(ev) { var _mouseX = ev.pageX - $eventCloak.offset().left; var _mouseY = ev.pageY - $eventCloak.offset().top; $eventCloakListings.each(function() { var $this = $(this); var isBoundX = _mouseX >= $this.data('left') && _mouseX <= $this.data('right'); var isBoundY = _mouseY >= $this.data('top') && _mouseY <= $this.data('bottom'); if(isBoundX && isBoundY) { $this.data('histogram').addClass('hover'); } else { $this.data('histogram').removeClass('hover'); } }); }); $eventCloak.mouseout(function() { $eventCloakListings.each(function() { $(this).data('histogram').removeClass('hover'); }); }); // Loop through all the available metrics in the graph data _.each(this.metrics, function(metric) { _this.histogramMetrics.push(new HistogramMetric({ collection: _this.metricGroup, clock: _this.clock, metric: metric, graphData: _this.graphData, eventCloak: _this.eventCloak })); }); }, draw: function() { var _timestamps = _.map(this.graphData.data, function(v) { return v.timestamp; }); this.clock.refresh(_timestamps, null, this.graphData.rangeValue, this.graphData.rangeUnit); _.each(this.histogramMetrics, function(v) { v.draw(); }); this.clock.setCurrentTimeFromAngle(0); } }); module.exports = HistogramsComposite; <|start_filename|>lib/javascripts/graph_components/handle.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ var GraphComponent = require('./graph_component'); var Handle = GraphComponent.extend({ defaults: { cx: null, cy: null }, init: function(options) { this._super(options); this.channelId = _.uniqueId('channel_'); this.radialLine = this.config.radialLine; this.guideline = this.config.guideline; this.alias = this.config.alias; this.model = this.config.model; this.__inheritFromBase(['cx', 'cy']); // Now supports lazy attachment, so it doesn't rely on points straight away. this.isAttached = false; this.attach(); _.bindAll(this, 'draw'); $.subscribe(this.radialLine.channelId + '.dataPointFound', this.draw); }, attach: function() { if(!this.radialLine.pathPoints) { return false; } this.svg = this.base.svg.append('circle') .attr('class', 'wheel-graph__handle') .attr('r', 5) .attr("transform", "translate(" + this.config.cx + "," + this.config.cy + ")") .classed(this.alias, true); var lastPoint = this.radialLine.pathPoints[1]; this.svg.attr('cx', lastPoint[0]) .attr('cy', lastPoint[1]); this.isAttached = true; }, draw: function(e, opts) { var _this = this; if(!this.isAttached) { this.attach(); } // Calculate the handle through an intersection var line1 = $L(this.radialLine.v1, this.radialLine.v2); var line2 = $L(this.guideline.v1, this.guideline.v2); var intersection = line1.intersectionWith(line2); this.svg.attr('cx', intersection.elements[0]).attr('cy', intersection.elements[1]); if(opts.model) { var selectedModels = opts.model.collection.models.filter(function(v) { return v.get('selected') === true; }); if(!opts.model.get('selected') && !!selectedModels.length) { opts.hide = true; } } this.svg.classed('hidden', opts.hide || false); $.publish(this.channelId + '.moved', [{x: intersection.elements[0], y: intersection.elements[1]}]); }, reattach: function() { if(this.isAttached) { this.isAttached = false; this.svg.remove(); this.attach(); } } }); module.exports = Handle; <|start_filename|>lib/javascripts/backbone_components/clock_display.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ // var Backbone = require('../../bower_components/backbone/backbone'); var ClockDisplay = Backbone.View.extend({ initialize: function(options) { _.bindAll(this, 'updateDisplay'); this.clock = this.options.clock; // Attach as an object (no model) this.$value = this.$el.find('.clock-display__value'); this.$context = this.$el.find('.clock-display__context'); this.$day = this.$el.find('.clock-display__day'); $.subscribe(this.clock.channelId + '.timeChange', this.updateDisplay); }, updateDisplay: function(e, timestamp) { var _this = this; var time = moment(timestamp); this.$value.html(time.format('hh:mm')); this.$context.html(time.format('a')); this.$day.html(''); var _cal = time.calendar(); var _whitelist = ['Yesterday', 'Today']; _.each(_whitelist, function(v) { if(_cal.substr(0, v.length) === v) { _this.$day.html(', ' + v); } }); } }); module.exports = ClockDisplay; <|start_filename|>lib/javascripts/graph_components/clock.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /* * Handle the logic and time scales for a wheel graph * based on an array of timestamps */ var Util = require('./util'); var Clock = Class.extend({ defaults: { timestamps: [ ], startAngle: 360, endAngle: 0, radial: false, range: { unit: 'hours', value: 24 } }, init: function(options) { this.config = _.extend({ }, this.defaults, options); this.disabled = false; this.startTime = null; // Moment object this.endTime = null; // Moment object this.currentTime = null; // Moment object this.currentAngle = null; // Cache the current angle whenever the current time is set. this.channelId = _.uniqueId('channel_'); // Create a unique reference to reduce pub/sub calls. if(this.config.timestamps.length) { this.refresh(this.config.timestamps); } }, refresh: function(timestamps, startTime, range, unit) { this.timestamps = timestamps; startTime = startTime || timestamps[0]; range = range || null; unit = unit || null; this.setTimeRange(startTime, range, unit); }, /** * Create a scale of time * from the start time to the end time */ setTimeScale: function() { if(!this.startTime || !this.endTime) { return false; } var scale = d3.time.scale(); scale.domain([this.startTime.valueOf(), this.endTime.valueOf()]); if(this.startTime.valueOf() === this.endTime.valueOf()) { this.disabled = true; return false; } else { this.disabled = false; } scale.range([this.config.startAngle, this.config.endAngle]); this.timeScale = scale; this.domain = scale.domain(); this.range = scale.range(); this.setReverseScale(); return this; }, /** * Create a reverse scale to convert angles to time */ setReverseScale: function() { var scale = d3.scale.linear(); scale.domain(this.range); scale.range(this.domain); this.reverseScale = scale; return this; }, /** * Calculate an angle based on a an arbitary timestamp * (via the timeScale) */ getAngleFromTime: function(timestamp, offset) { offset = offset || 0; var angle = this.timeScale(timestamp); return angle + offset; }, /** * Set active time range */ setTimeRange: function(startTime, range, unit) { range = range || this.config.range.value; unit = unit || this.config.range.unit; this.startTime = moment(startTime); this.endTime = this.startTime.clone().subtract(unit, range); this.setTimeScale(); return this; }, /** * Set current time */ setCurrentTime: function(timestamp) { this.currentTime = moment(timestamp); this.currentAngle = this.getAngleFromTime(timestamp); if(this.config.radial) { this.currentAngle = Util.normalizeAngle(this.currentAngle); } $.publish(this.channelId + '.timeChange', [timestamp]); return this; }, /** * Set current time from angle */ setCurrentTimeFromAngle: function(angle) { if(this.disabled) { return false; } if(this.reverseScale) { var timestamp = this.reverseScale(angle); this.setCurrentTime(parseInt(timestamp, null)); } return this; } }); module.exports = Clock; <|start_filename|>lib/javascripts/graph_components/background_axis.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ var GraphComponent = require('./graph_component'); var BackgroundAxis = GraphComponent.extend({ defaults: { steps: 10, horizontal: false, width: null, height: null, rangeLabels: false, $outer: null, scale: null, max: 100, offset: { x: 0, y: 0 }, classes: { group: 'background-axis-group', line: 'background-axis-line', rangeLabel: 'background-axis-range-label' } }, init: function(options) { this.config = _.extend({ }, this.defaults, options); this.dataLine = this.config.dataLine; this.clock = this.config.clock; this.scale = this.config.scale; this.base = this.config.base; this.steps = this.config.steps; this.$outer = this.config.$outer; this.$topRangeLabel = this.$outer.find('.' + this.config.classes.rangeLabel + '.top'); this.$bottomRangeLabel = this.$outer.find('.' + this.config.classes.rangeLabel + '.bottom'); this.axis = this.config.horizontal ? 'x' : 'y'; this.otherAxis = this.axis == 'x' ? 'y' : 'x'; this.group = this.base.svg.append('svg:g').classed(this.config.classes.group, true); this.group.attr('transform', 'translate(' + this.config.offset.x + ',' + this.config.offset.y + ')'); this.__inheritFromBase(['width', 'height']); }, setLines: function(opts) { var coords = [ ]; if(opts.scale) this.scale = opts.scale; if(opts.steps) this.steps = opts.steps; var _difference = Math.abs(this.scale.range()[0] - this.scale.range()[1]); var _oneStep = _difference / this.steps; var i = 1; this.linePoints = [ ]; for(i = 1; i < this.steps; i++) { this.linePoints.push(_.min([this.scale.range()[0], this.scale.range()[1]]) + (_oneStep * i)); } this.draw(); this.drawRangeLabels(); }, draw: function() { var _this = this; if(this.linePoints) { this.group.selectAll("." + this.config.classes.line).remove(); this.group.selectAll("." + this.config.classes.line) .data(this.linePoints) .enter().append("svg:line") .attr("class", this.config.classes.line) .attr((this.otherAxis + '1'), function(d, i) { return 0; }) .attr((this.axis + '1'), function(d, i) { return d; }) .attr((this.otherAxis + '2'), function(d, i) { return _this.config.max; }) .attr((this.axis + '2'), function(d, i) { return d; }); } }, drawRangeLabels: function() { var metric = this.dataLine.metric; if(this.linePoints && this.config.rangeLabels) { var _mainProp = this.axis == 'y' ? 'top' : 'left'; var fixedPoint = 2; if(metric.alias === 'temperature' || metric.alias === 'humidity') { fixedPoint = 0; } this.$topRangeLabel.css(_mainProp, this.scale.range()[1]).find('.value-container').html(this.scale.domain()[1].toFixed(fixedPoint)); this.$bottomRangeLabel.css(_mainProp, this.scale.range()[0]).find('.value-container').html(this.scale.domain()[0].toFixed(fixedPoint)); } } }); module.exports = BackgroundAxis; <|start_filename|>lib/stylesheets/application.css<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ .wheel-graph__note, .histogram__mouse-label, .background-axis-range-label { font-size: 9px; color: rgba(0, 0, 0, 0.7); position: absolute; text-shadow: 0 -1px 2px white; pointer-events: none; } .icon, .icon--plus, .icon--close, .icon--info, .icon--down-arrow, .icon--up-arrow { text-indent: -9999px; display: inline-block; vertical-align: middle; width: 10px; height: 10px; background: url('../images/sprite.png') no-repeat 0 0; } .icon--plus { background-position: 0 -25px; } .icon--close { background-position: 0 0; } .icon--info { background-position: 0 -50px; opacity: 0.2; width: 12px; height: 12px; } .icon--down-arrow { background-position: 0 -75px; width: 13px; height: 9px; opacity: 0.25; } .icon--up-arrow, .item-selected .metric-display-group .metric-display.current .metric-display__icon { background-position: 0 -100px; width: 13px; height: 9px; opacity: 0.5; } svg, svg * { shape-rendering: geometricPrecision; } * { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } h1, h2, h3, h4 { margin: 0; } body { color: black; font-family: 'lucida grande', tahoma, verdana, sans-serif; font-size: 13px; line-height: 1.5; } img { display: block; } h4 { font-size: 13px; font-weight: normal; } a { color: #3a5897; text-decoration: none; } a:hover { text-decoration: underline; } p, ul, ol { margin: 19.25px 0 0; } p:first-child, ul:first-child, ol:first-child { margin-top: 0; } p, article ul, article h5 { color: #7f7f7f; } article ul { padding-left: 1.2em; } article li { margin-top: 0.6em; } article li:first-child { margin-top: 0; } nav ul, nav ol { padding-left: 0; list-style: none; margin: 0; } .container { width: 807px; overflow: hidden; padding-top: 16px; margin: 0 auto; } .container__inner { margin: 0 auto; } .divided-area-container { padding-bottom: 30px; } .divided-area, .divided-area--faq, .divided-area--faq-footer { border-top: 1px solid #e5e5e5; margin-top: 30px; padding-top: 30px; } .divided-area:first-child:not(.override-first) { border-top: 0; margin-top: 0; } .row { margin-left: -18px; margin-right: -0; } .row:before, .row:after { content: " "; display: table; } .row:after { clear: both; } .col--aux { width: 147px; margin-left: 18px; float: left; } .col--main, .col--main--histograms { width: 642px; margin-left: 18px; float: left; } .col--full { width: 807px; margin-left: 18px; float: left; } .col--split { float: left; width: 50%; } .page-header__title, .page-header__label { display: inline-block; vertical-align: baseline; margin-right: -4px; } .item-label-note { color: rgba(0, 0, 0, 0.35); } .large-chars { font-size: 68px; letter-spacing: -2px; line-height: 1.2; font-family: sans-serif; font-weight: bold; color: rgba(0, 0, 0, 0.5); -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"; } .large-chars .percent { font-size: 29px; line-height: 1.5; vertical-align: top; margin-left: 3px; } .block-link { color: inherit; text-decoration: none; } .page-header { margin-left: -18px; margin-right: -0; margin-top: 3px; } .page-header:before, .page-header:after { content: " "; display: table; } .page-header:after { clear: both; } .page-header__title { font-weight: normal; font-size: 24px; line-height: 1.2; letter-spacing: -1px; width: 477px; margin-left: 18px; } .page-header__label { width: 312px; margin-left: 18px; text-align: right; } .hero-feature { border: 1px solid #e2e1d0; border-radius: 3px; padding: 15px 0; background: #eeeddb; margin-top: 20px; } .hero-feature:before, .hero-feature:after { content: " "; display: table; } .hero-feature:after { clear: both; } .hero-feature__row, .hero-feature__row--boxout { margin-left: -19px; margin-right: -1px; margin-top: 20px; margin-bottom: 20px; } .hero-feature__row:before, .hero-feature__row:after { content: " "; display: table; } .hero-feature__row:after { clear: both; } .hero-feature__main { width: 477px; margin-left: 18px; float: left; min-height: 1px; } html.no-svg .hero-feature__main { display: none; } .hero-feature__aux { width: 312px; margin-left: 18px; float: left; } html.no-svg .hero-feature__aux { width: 807px; margin-left: 18px; float: left; padding-left: 18px; } .wheel-graph-container { width: 445px; margin: auto; } .wheel-graph { height: 445px; position: relative; z-index: 1; pointer-events: none; } .wheel-graph-event-cloak { position: absolute; top: 0; left: 0; right: 0; bottom: 0; width: inherit; margin: auto; z-index: 2; } .wheel-graph__donut path { fill: white; stroke: #e2e1d0; } .wheel-graph__donut--event { pointer-events: visibleFill; fill: none; stroke: none; visibility: visible; } .wheel-graph__hour-stroke { stroke: #f6f6ed; stroke-width: 1px; stroke-linecap: round; } .wheel-graph__line-group { -webkit-transition: opacity 0.3s ease; -moz-transition: opacity 0.3s ease; transition: opacity 0.3s ease; } .wheel-graph__line-group.hidden { opacity: 0; } .wheel-graph__line { fill: none; stroke: black; stroke-width: 2px; display: none; } .wheel-graph__line.humidity { stroke: #627aad; } .wheel-graph__line.wue { stroke: #779f2a; } .wheel-graph__line.pue { stroke: #ef8e1c; } .wheel-graph__line.temperature { stroke: #af89d3; } .wheel-graph__line-trail { fill: none; stroke: black; stroke-linecap: round; stroke-linejoin: round; } .wheel-graph__line-trail.humidity { stroke: #627aad; } .wheel-graph__line-trail.wue { stroke: #779f2a; } .wheel-graph__line-trail.pue { stroke: #ef8e1c; } .wheel-graph__line-trail.temperature { stroke: #af89d3; } .wheel-graph__line-trail.hidden { opacity: 0; } .wheel-graph__guideline { fill: none; stroke: #d2d2d2; } .wheel-graph__handle { stroke-width: 5px; fill: white; opacity: 0; -webkit-transition: opacity 1s ease; -moz-transition: opacity 1s ease; transition: opacity 1s ease; } .wheel-graph-container:hover .wheel-graph__handle, .histogram-group__event-cloak:hover ~ .histogram .wheel-graph__handle { opacity: 1; } .wheel-graph__handle.humidity { stroke: #627aad; } .wheel-graph__handle.wue { stroke: #779f2a; } .wheel-graph__handle.pue { stroke: #ef8e1c; } .wheel-graph__handle.temperature { stroke: #af89d3; } .wheel-graph__handle.center-handle { fill: #7f7f7f; opacity: 1 !important; } .wheel-graph__handle.hidden { -webkit-transition: none; -moz-transition: none; transition: none; opacity: 0 !important; } .wheel-graph__note { text-align: right; width: 200px; left: 50%; margin-left: -200px; padding-right: 5px; display: none; } .wheel-graph__note.outer { top: 5px; } .wheel-graph__note.inner { top: 137px; } .hero-feature .wheel-graph__note { opacity: 0; display: block; -webkit-transition: opacity 0.5s ease; -moz-transition: opacity 0.5s ease; transition: opacity 0.5s ease; } .hero-feature.item-selected .wheel-graph__note, .hero-feature.item-highlighted .wheel-graph__note { opacity: 1; } .wheel-graph__note.mouse { width: auto; margin-left: 10px; margin-top: -10px; padding-right: 0; text-align: left; opacity: 0; -webkit-transition: opacity 1s ease; -moz-transition: opacity 1s ease; transition: opacity 1s ease; } .wheel-graph-event-cloak:hover ~ .wheel-graph .wheel-graph__note.mouse { opacity: 1; } .delay-segment.hidden { opacity: 0; } .delay-segment__arc { fill: #f7f7f7; } .clock-display { position: absolute; width: 139px; height: 139px; top: 0; right: 0; bottom: 0; left: 0; margin: auto; text-align: center; border: 3px solid #7f7f7f; border-radius: 999px; } .clock-display__mid { display: table; height: 100%; width: 100%; } .clock-display__inner { display: table-cell; vertical-align: middle; } .clock-display__value { font-size: 40px; font-family: sans-serif; font-weight: bold; letter-spacing: -2px; line-height: 1; color: rgba(0, 0, 0, 0.5); color: #77766d; margin-top: 8px; } .clock-display__aux { letter-spacing: -1px; color: #9b9a8f; } .clock-display__context { text-transform: uppercase; } .metric-display-group { margin-right: 16px; margin-top: -20px; } .metric-display-group .metric-display { margin-top: 20px; } html.no-svg .metric-display-group .metric-display { float: left; width: 50%; height: 224px; } .item-selected .metric-display-group .metric-display.current { height: 274px; background: white; } .item-selected .metric-display-group .metric-display.current .metric-display__text { opacity: 1; } .item-selected .metric-display-group .metric-display.current .metric-display__icon { opacity: 0.5; } .item-selected .metric-display-group .metric-display.current .metric-display__label .icon, .item-selected .metric-display-group .metric-display.current .metric-display__label .icon--plus, .item-selected .metric-display-group .metric-display.current .metric-display__label .icon--close, .item-selected .metric-display-group .metric-display.current .metric-display__label .icon--info, .item-selected .metric-display-group .metric-display.current .metric-display__label .icon--down-arrow, .item-selected .metric-display-group .metric-display.current .metric-display__label .icon--up-arrow { display: none; } .item-selected .metric-display-group .metric-display.current .metric-display__value { margin-bottom: 8px; } .item-selected .metric-display-group .metric-display.current .hide-on-select { display: none; } .item-selected .metric-display-group .metric-display:not(.current) { height: 42px; } .item-selected .metric-display-group .metric-display:not(.current) .metric-display__label { width: 100%; } .item-selected .metric-display-group .metric-display:not(.current) .metric-display__label h4, .item-selected .metric-display-group .metric-display:not(.current) .metric-display__label .item-label-note { display: inline; } .item-selected .metric-display-group .metric-display:not(.current) .metric-display__label .icon, .item-selected .metric-display-group .metric-display:not(.current) .metric-display__label .icon--plus, .item-selected .metric-display-group .metric-display:not(.current) .metric-display__label .icon--close, .item-selected .metric-display-group .metric-display:not(.current) .metric-display__label .icon--info, .item-selected .metric-display-group .metric-display:not(.current) .metric-display__label .icon--down-arrow, .item-selected .metric-display-group .metric-display:not(.current) .metric-display__label .icon--up-arrow { display: none; } .item-selected .metric-display-group .metric-display:not(.current) .metric-display__value { display: none; } .metric-display { border-left: 5px solid #8e8e8e; height: 100px; padding: 16px; position: relative; -webkit-transition: background-color 0.5s ease, height 0.3s ease; -moz-transition: background-color 0.5s ease, height 0.3s ease; transition: background-color 0.5s ease, height 0.3s ease; overflow: hidden; } .metric-display:hover { background: rgba(255, 255, 255, 0.5); cursor: pointer; } .metric-display:hover .metric-display__icon { opacity: 0.5; } .metric-display.pue { border-left-color: #ef8e1c; } .metric-display.wue { border-left-color: #779f2a; } .metric-display.humidity { border-left-color: #627aad; } .metric-display.temperature { border-left-color: #af89d3; } .metric-display__icon { pointer-events: none; margin-left: 5px; -webkit-transition: opacity 0.5s ease; -moz-transition: opacity 0.5s ease; transition: opacity 0.5s ease; } html.no-svg .metric-display__icon { display: none !important; } .metric-display__label { float: left; width: 90px; margin-top: -4px; } html.no-svg .metric-display__label { padding-bottom: 15px; } .metric-display__value { float: right; text-align: right; margin-top: -8px; } .metric-display__value .large-chars { line-height: 1; } .metric-display__value .item-label-note { position: absolute; opacity: 1; -webkit-transition: opacity 0.5s ease; -moz-transition: opacity 0.5s ease; transition: opacity 0.5s ease; bottom: 11px; right: 16px; } .metric-display__text { font-size: 11px; line-height: 18px; opacity: 0; overflow: auto; padding-right: 16px; clear: both; padding-top: 15px; border-top: 1px solid #e5e5e5; -webkit-transition: opacity 0.5s ease; -moz-transition: opacity 0.5s ease; transition: opacity 0.5s ease; } .metric-display__text p + p { margin-top: 8px; } html.no-svg .metric-display__text { opacity: 1; } .corner-label-holder { position: relative; } .corner-label, .corner-label--bottom { position: absolute; top: 0; left: 16px; color: rgba(0, 0, 0, 0.7); } .corner-label--bottom { top: auto; bottom: -5px; color: rgba(0, 0, 0, 0.35); } .hero-feature__row--boxout { margin-bottom: 0; } .boxout { border-top: 1px solid rgba(0, 0, 0, 0.1); border-radius: 3px; margin: 0 18px 0 34px; overflow: hidden; } .boxout__intro-col { width: 477px; margin-left: 18px; float: left; padding: 14px 14px 0 0; width: 481px; } .boxout__intro-col p { color: rgba(0, 0, 0, 0.35); } .boxout__intro-col p strong { font-weight: normal; color: rgba(0, 0, 0, 0.5); } .boxout__data-col { width: 147px; margin-left: 18px; float: left; width: 146px; margin-left: 0; border-left: 1px solid rgba(0, 0, 0, 0.1); padding: 14px 14px 0; margin-bottom: -100px; padding-bottom: 100px; } .boxout__data-col h4 { color: rgba(0, 0, 0, 0.35); } .boxout__data-col .large-chars { font-size: 38px; line-height: 1; } .date-range-nav li { border-bottom: 1px solid rgba(207, 207, 207, 0.5); position: relative; line-height: 45px; } .date-range-nav li:after { content: ''; position: absolute; right: 0; top: 0; bottom: 0; width: 5px; background: rgba(207, 207, 207, 0.5); } .date-range-nav a { display: block; } .date-range-nav a.current { background: #eeeddb; padding-left: 10px; border-right: 5px solid #c4c4b5; cursor: default; color: inherit; } .date-range-nav a.current:hover { text-decoration: none; } .col--main--histograms { width: 624px; } .histogram-group { position: relative; } .histogram-group .histogram + .histogram { margin-top: 20px; } .histogram-group__event-cloak { position: absolute; top: 0; right: -18px; bottom: 0; left: -18px; z-index: 1; background: rgba(0, 0, 0, 0); } .event-cloak__listing { position: absolute; left: 0; right: 0; top: 0; height: 122px; background: rgba(0, 0, 0, 0); } .event-cloak__listing + .event-cloak__listing { top: 142px; } .event-cloak__listing + .event-cloak__listing + .event-cloak__listing { top: 284px; } .event-cloak__listing + .event-cloak__listing + .event-cloak__listing + .event-cloak__listing { top: 426px; } .event-cloak__svg { position: absolute; top: 0; left: 0; } .histogram-group__footer { margin-top: 20px; position: relative; } .histogram-group__footer:before { content: ''; position: absolute; height: 5px; background: #e5e5e5; top: 0; right: 0; left: 0; } .handle { display: none; } .histogram { border-bottom: 2px solid #e5e5e5; border-left: 2px solid #e5e5e5; position: relative; pointer-events: none; } .histogram__title { pointer-events: none; line-height: 45px; position: absolute; top: 0; left: 0; text-shadow: 0 -1px 0 white; padding: 13px; line-height: 1; -webkit-transition: opacity 1s ease; -moz-transition: opacity 1s ease; transition: opacity 1s ease; } .histogram-group__event-cloak:hover ~ .histogram .histogram__title.dim { opacity: 0.1; } .histogram__inner { height: 120px; margin: 0 -18px; } .histogram__guideline { fill: none; stroke: #cccccc; stroke-width: 1px; shape-rendering: crispEdges !important; opacity: 0; -webkit-transition: opacity 1s ease; -moz-transition: opacity 1s ease; transition: opacity 1s ease; } .histogram-group__event-cloak:hover ~ .histogram .histogram__guideline { opacity: 1; } .histogram__value-label { text-shadow: 0 -1px 0 white; position: absolute; left: 0; top: 0; margin-left: 10px; margin-top: 10px; opacity: 0; -webkit-transition: opacity 1s ease; -moz-transition: opacity 1s ease; transition: opacity 1s ease; } .histogram-group__event-cloak:hover ~ .histogram .histogram__value-label { opacity: 1; } .histogram__value-label .small-unit { font-size: 8px; } .histogram__value-label.hidden { opacity: 0 !important; -webkit-transition: none; -moz-transition: none; transition: none; } .histogram__range-line { stroke: none; fill: black; opacity: 0.25; } .histogram__range-line:first-child { display: none; } .pue .histogram__range-line { fill: #ef8e1c; } .wue .histogram__range-line { fill: #779f2a; } .humidity .histogram__range-line { fill: #627aad; } .temperature .histogram__range-line { fill: #af89d3; } .histogram__data-line { fill: none; stroke: black; stroke-width: 1px; } .histogram__data-line.humidity { stroke: #627aad; } .histogram__data-line.wue { stroke: #779f2a; } .histogram__data-line.pue { stroke: #ef8e1c; } .histogram__data-line.temperature { stroke: #af89d3; } .histogram__mouse-label { opacity: 0; -webkit-transition: opacity 1s ease; -moz-transition: opacity 1s ease; transition: opacity 1s ease; } .histogram.hover .histogram__mouse-label { opacity: 1; } .histogram__mouse-label.hidden { opacity: 0 !important; -webkit-transition: none; -moz-transition: none; transition: none; } .footer-state { position: relative; height: 42px; line-height: 42px; } .histogram-date-label { display: none; color: #7f7f7f; } .histogram-group__event-cloak:hover ~ .histogram-group__footer .histogram-date-label { display: block; } .histogram-group__event-cloak:hover ~ .histogram-group__footer .histogram-date-label + .histogram-split-labels { display: none; } .histogram-date-label__inner { position: absolute; left: 0; top: 5px; padding-left: 15px; white-space: nowrap; } .histogram-date-label__inner.inverted { padding-left: 0; padding-right: 15px; } .histogram-date-label__inner.inverted .histogram-date-label__keyline { left: auto; right: 0; } .histogram-date-label__keyline { position: absolute; left: 0; width: 1px; top: 0; bottom: 0; background: #cccccc; } .histogram-split-labels__label { position: absolute; top: 0; border-left: 1px solid #dddddd; padding-left: 16px; color: #7f7f7f; font-size: 10px; } .background-axis-line { stroke: #f2f2f2; shape-rendering: crispEdges !important; } .background-axis-range-label { right: 0; } .background-axis-range-label.bottom { margin-top: -12px; } #processing-msg { display: none; } .interval-icon { margin-top: 10px; } .interval-icon__arc { fill: black; opacity: 0.1; } html.no-svg .svg-only { display: none; } .support-message { margin: 16px; margin-top: 0; border: 1px solid rgba(0, 0, 0, 0.1); padding: 10px; border-radius: 3px; background: rgba(255, 255, 255, 0.2); display: none; } html.no-svg .support-message { display: block; } .divided-area--faq { border: 1px solid #e2e1d0; border-radius: 3px; padding: 15px; background: #eeeddb; } .divided-area--faq:first-child { margin-top: 20px; } .divided-area--faq .col--aux { width: 177px; } .divided-area--faq .col--main, .divided-area--faq .col--main--histograms { background: white; padding: 15px; border: 1px solid #e4e3d3; width: 580px; } .divided-area--faq .metric-display { cursor: default; } .divided-area--faq .metric-display:hover { background: transparent; } .divided-area--faq-footer { text-align: center; padding-bottom: 16px; } <|start_filename|>lib/javascripts/graph_components/graph_component.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ var GraphComponent = Class.extend({ defaults: { base: null // An instance of a WheelGraphBase object }, init: function(options) { this.config = _.extend({ }, this.defaults, options); this.base = this.config.base; this.svgGroup = null; this.svg = null; }, /** * Use the value from the base object for the given properties, * if it hasn't yet been overriden */ __inheritFromBase: function(props) { var _this = this; // Handle single properties as single element array if(typeof props === 'string') { props = [props]; } _.each(props, function(prop) { _this.config[prop] = _this.config[prop] === null ? _this.base.config[prop] : _this.config[prop]; }); } }); module.exports = GraphComponent; <|start_filename|>lib/javascripts/graph_components/radial_line.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ var DataLine = require('./data_line'); var Util = require('./util'); var RadialLine = DataLine.extend({ init: function(options) { this._super(options); }, /** * Take the data and output the x/y co-ordinates from true angles. */ drawPath: function(radialData) { var radial = d3.svg.line.radial(); var pathData = radial(radialData); return pathData; }, /** * Provide radial-specific data */ setData: function() { var _this = this; return _.map(this.points, function(v, k) { var angle = _this.clock.getAngleFromTime(v.date, 0); var radius = _this.radiusScale(v.value); return [radius, Util.toRadians(angle)]; }); }, /** * Radial lines are normalised differently when inherited */ __normalizeAngle: function(angle) { return Util.normalizeAngle(angle); }, /** * Angles need to be parsed back as degrees * because the path sent radians */ parseAngle: function(angle) { return Util.toDegrees(angle); } }); module.exports = RadialLine; <|start_filename|>lib/javascripts/graph_components/event_cloak.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /** * Handle events from a central location * and provide a dedicated SVG element to attach to */ var Util = require('./util'); var EventCloak = Class.extend({ defaults: { animate: false, clock: null, width: null, height: null, cx: null, cy: null, angular: true, offset: 90, resetPoint: 0, cloakOffset: 0 }, init: function(options) { this.channelId = _.uniqueId('_channel'); this.config = _.extend({ }, this.defaults, options); this.$el = this.config.$el; this.clock = this.config.clock; this.tweenComplete = false; this.isMouseOver = false; this.mouseX = null; this.mouseY = null; this.attach(); }, attach: function() { var _this = this; _.bindAll(this, 'onMouseOver', 'onMouseOut', 'onMouseMove'); this.$el.on('mouseover', this.onMouseOver); this.$el.on('mouseout', this.onMouseOut); this.$el.on('mousemove', this.onMouseMove); }, onMouseOver: function(ev) { ev.stopPropagation(); var _this = this; this.isMouseOver = true; var _currentAngle = this.config.angular ? Util.normalizeAngle(this.clock.currentAngle) : this.clock.currentAngle; this.__createTween(this.config.resetPoint, _currentAngle); }, onMouseOut: function(ev) { var _this = this; ev.stopPropagation(); this.isMouseOver = false; var _currentAngle = this.config.angular ? Util.normalizeAngle(this.clock.currentAngle) : this.clock.currentAngle; this.__createTween(_currentAngle, this.config.resetPoint); }, onMouseMove: function(e) { e.stopPropagation(); if(e.originalEvent) { var hasOffset = e.originalEvent.hasOwnProperty('offsetX'); this.mouseX = hasOffset ? e.originalEvent.offsetX : e.originalEvent.layerX; this.mouseY = hasOffset ? e.originalEvent.offsetY : e.originalEvent.layerY; } }, /** * Track any movement on the donut, by converting the x/y co-ordinates to an angle. */ trackMovement: function(angle) { var mouseAngle; if(this.config.angular) { mouseAngle = Util.getAngleFromOrigin([this.mouseX, this.mouseY], [this.config.cx, this.config.cy]) + this.config.offset; mouseAngle = Util.normalizeAngle(mouseAngle); } else { mouseAngle = this.mouseX + this.config.offset; } if(this.config.cloakOffset) { mouseAngle -= this.config.cloakOffset; mouseAngle = _.max([mouseAngle, 0]); } var _this = this; angle = typeof angle !== 'undefined' ? angle : mouseAngle; this.clock.setCurrentTimeFromAngle(angle); if(this.tween && !this.tweenComplete) { var _currentAngle = this.config.angular ? Util.normalizeAngle(this.clock.currentAngle) : this.clock.currentAngle; this.tween.to({angle: _currentAngle}); } $.publish(this.channelId + '.movementTracked'); }, /** * Instantiate the tween (one is created for every mouse over/out) */ __createTween: function(fromAngle, toAngle, barrier) { var _this = this; if(this.tween) { tween.stop(); } TWEEN.removeAll(); this.tween = tween = new TWEEN.Tween({ angle: fromAngle }); this.tweenComplete = false; tween.to({ angle: toAngle }) .easing(TWEEN.Easing.Quartic.Out) .onUpdate(function() { _this.clock.setCurrentTimeFromAngle(this.angle); }).onComplete(function() { _this.tweenComplete = true; }).start(); } }); module.exports = EventCloak; <|start_filename|>lib/javascripts/backbone_components/metric_display.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ // var Backbone = require('../../bower_components/backbone/backbone'); var MetricDisplay = Backbone.View.extend({ events: { 'click': 'toggleSelection', 'mouseover': 'toggleHighlight', 'mouseout': 'toggleHighlight' }, initialize: function(options) { this.$valueContainer = this.$el.find('.value-container'); this.listenTo(this.model, 'change:selected', this.changeCurrent, this); this.listenTo(this.model, 'change:value', this.updateValue, this); this.dataLineView = options.dataLineView; this.group = this.options.group; this.$heroFeature = this.$el.closest('.hero-feature'); }, toggleHighlight: function(e) { var _noneSelected = this.group.collection.filter(function(v) { return v.get('selected'); }).length === 0; if(_noneSelected) { this.__toggle('highlighted'); } if(this.dataLineView.radialLine.radiusScale) { $.publish('current_radial_line', [this.dataLineView.radialLine]); } // See if anything is highlighted. var highlightedModels = this.model.collection.models.filter(function(v) { return v.get('highlighted') === true; }); this.$heroFeature.toggleClass('item-highlighted', !!highlightedModels.length); }, toggleSelection: function(e) { this.__toggle('selected'); if(this.model.get('selected')) { this.__toggle('highlighted', true); } }, __toggle: function(field, override) { var _this = this; var _switchTo; if(typeof override !== 'undefined') { _switchTo = override; } else { _switchTo = !this.model.get(field); } this.model.set(field, _switchTo); if(!this.model.get(field)) { this.group.collection.each(function(v) { v.set(field, null); }); } else { var otherModels = this.group.collection.each(function(v) { if(v !== _this.model) { v.set(field, false); } }); } }, changeCurrent: function() { this.$el.toggleClass('current', this.model.get('selected')); }, updateValue: function() { this.$valueContainer.html(this.model.get('value').toFixed(2)); } }); module.exports = MetricDisplay; <|start_filename|>demo/application.js<|end_filename|> $(function() { var dashboard = new PowerDashboard({ apiConfig: { host: 'http://localhost:8000', uriPrefix: 'demo/api' }, metrics: [ { alias: 'humidity', name: 'Humidity', minDomainDifference: 0.05 }, { alias: 'temperature', name: 'Temperature', minDomainDifference: 0.05 }, { alias: 'pue', name: 'PUE', domain: { min: 1.0, max: 1.2 } }, { alias: 'wue', name: 'WUE', domain: { min: 0, max: 1.5 } } ] }); }); <|start_filename|>lib/javascripts/graph_components/line_trail.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ var GraphComponent = require('./graph_component'); /** * Allows a variable stroke width, using the data that we already have available to us. */ var LineTrail = GraphComponent.extend({ defaults: { dataLine: null, maxStrokeWidth: 2, minStrokeWidth: 0.2, classes: { line: 'line-trail' } }, init: function(options) { _.bindAll(this, 'draw'); this._super(options); this.dataLine = this.config.dataLine; }, draw: function() { var _this = this; this.strokeScale = this.__createScale(); var pointsToLoop = _.clone(this.dataLine.pathDict); pointsToLoop.pop(); var hiddenSwitch = false; this.dataLine.group.selectAll("." + this.config.classes.line).remove(); this.dataLine.group.selectAll("." + this.config.classes.line) .data(pointsToLoop) .enter().append("svg:line") .attr("class", this.config.classes.line + ' ' + this.dataLine.config.alias) .attr("stroke-width", function(d) { return _this.strokeScale(d.dataValue.date); }) .attr('x1', function(d, i) { return d.x; }) .attr('y1', function(d, i) { return d.y; }) .attr('x2', function(d, i) { return _this.dataLine.pathDict[i+1] ? _this.dataLine.pathDict[i+1].x : 0; }) .attr('y2', function(d, i) { return _this.dataLine.pathDict[i+1] ? _this.dataLine.pathDict[i+1].y : 0; }) .classed('hidden', function(d, i) { // Set the visibility, based on if the data is delayed. if(_this.dataLine.pathDict[i].dataValue.startDelay) { hiddenSwitch = true; } else if(_this.dataLine.pathDict[i].dataValue.endDelay) { hiddenSwitch = false; } return hiddenSwitch; }); }, __createScale: function() { var scale = d3.scale.linear(); scale.domain(this.dataLine.clock.domain); scale.range([this.config.maxStrokeWidth, this.config.minStrokeWidth]); return scale; } }); module.exports = LineTrail; <|start_filename|>lib/javascripts/graph_components/util.js<|end_filename|> /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ var Util = { /* This function return an array of the different absolute paths received as a string, converted to absolute points. Inspiration of adaptation: http://webmaestro.fr/convert-svg-relative-path-data-to-absolute-polyline-points-with-javascript/ */ pathToPoints: function(path) { var paths = path.split( /z|Z/ ), points = [ ]; for ( var i = 0; i < paths.length; i++ ) { path = paths[i].split( /l|L/ ); path[0] = path[0].replace( /m|M/, '' ); for ( var j in path ) { path[j] = path[j].split( ',' ); for ( var k in path[j] ) { path[j][k] = parseFloat( path[j][k]); } } } return path; }, // Convert radians to degrees toDegrees: function(rad) { return rad * 180 / Math.PI; }, // Convert degrees to radians toRadians: function(deg) { return deg * Math.PI / 180; }, // Convert degrees farenheit to celsius toCelsius: function(f) { return (f-32) * 5 / 9; }, // Get the angle from a specified origin, using x/y co-ordinates // coords[0] = x, coords[1] = y getAngleFromOrigin: function(coords, origin) { var rads = Math.atan2(coords[1] - origin[1], coords[0] - origin[0]); return Util.toDegrees(rads); }, normalizeAngle: function(angle, normaliseTo) { normaliseTo = normaliseTo || 360; angle = angle % normaliseTo; if(angle <= 0) { angle += normaliseTo; } return angle; } }; module.exports = Util;
duongten95/puewue-frontend
<|start_filename|>lib/models/user_model.dart<|end_filename|> class UserModel { String uid; String? email; String? displayName; String? phoneNumber; String? photoUrl; UserModel( {required this.uid, this.email, this.displayName, this.phoneNumber, this.photoUrl}); } <|start_filename|>lib/models/todo_model.dart<|end_filename|> import 'package:meta/meta.dart'; class TodoModel { final String id; final String task; final String extraNote; final bool complete; TodoModel( {required this.id, required this.task, required this.extraNote, required this.complete}); factory TodoModel.fromMap(Map<String, dynamic> data, String documentId) { String task = data['task']; String extraNote = data['extraNote']; bool complete = data['complete']; return TodoModel( id: documentId, task: task, extraNote: extraNote, complete: complete); } Map<String, dynamic> toMap() { return { 'task': task, 'extraNote': extraNote, 'complete': complete, }; } } <|start_filename|>lib/ui/todo/empty_content.dart<|end_filename|> import 'package:flutter/material.dart'; class EmptyContentWidget extends StatelessWidget { final String title; final String message; EmptyContentWidget( {required Key key, required this.title, required this.message}) : super(key: key); @override Widget build(BuildContext context) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text(title), Text(message), ], ), ); } } <|start_filename|>lib/caches/sharedpref/shared_preference_helper.dart<|end_filename|> import 'package:shared_preferences/shared_preferences.dart'; class SharedPreferenceHelper { Future<SharedPreferences>? _sharedPreference; static const String is_dark_mode = "is_dark_mode"; static const String language_code = "language_code"; SharedPreferenceHelper() { _sharedPreference = SharedPreferences.getInstance(); } //Theme module Future<void> changeTheme(bool value) { return _sharedPreference!.then((prefs) { return prefs.setBool(is_dark_mode, value); }); } Future<bool> get isDarkMode { return _sharedPreference!.then((prefs) { return prefs.getBool(is_dark_mode) ?? false; }); } //Locale module Future<String>? get appLocale { return _sharedPreference?.then((prefs) { return prefs.getString(language_code) ?? 'en'; }); } Future<void> changeLanguage(String value) { return _sharedPreference!.then((prefs) { return prefs.setString(language_code, value); }); } }
bharathm03/create_flutter_provider_app
<|start_filename|>include/time_measure_util.h<|end_filename|> #pragma once #include <chrono> #include <ratio> #include <string> #include <iostream> #include <tuple> #include <utility> class MeasureExecutionTime { private: const std::chrono::steady_clock::time_point begin; const std::string caller; public: MeasureExecutionTime(const std::string& caller):caller(caller),begin(std::chrono::steady_clock::now()){} ~MeasureExecutionTime(){ const auto duration=std::chrono::steady_clock::now()-begin; std::cout << "execution time for " << caller << " is "<<std::chrono::duration_cast<std::chrono::milliseconds>(duration).count()<<" ms\n"; } }; #ifndef MEASURE_FUNCTION_EXECUTION_TIME #define MEASURE_FUNCTION_EXECUTION_TIME const MeasureExecutionTime measureExecutionTime(__FUNCTION__); #endif class time_elapse_aggregator { public: std::chrono::duration<size_t,std::ratio<1,1000000000>> duration; std::string function_name; time_elapse_aggregator(const std::string caller) : function_name(caller) {} ~time_elapse_aggregator() { std::cout << "cumulative execution time for "; std::cout << function_name; std::cout << " is "<< std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() << " ms\n"; } }; class measure_cumulative_execution_time { private: time_elapse_aggregator& time_elapsed; const std::chrono::steady_clock::time_point begin; public: measure_cumulative_execution_time(time_elapse_aggregator& _time_elapsed) : time_elapsed(_time_elapsed), begin(std::chrono::steady_clock::now()) {} ~measure_cumulative_execution_time() { const auto duration = std::chrono::steady_clock::now()-begin; time_elapsed.duration += duration; } }; #ifndef MEASURE_CUMULATIVE_FUNCTION_EXECUTION_TIME #define MEASURE_CUMULATIVE_FUNCTION_EXECUTION_TIME static time_elapse_aggregator time_elapse_aggregator_object(__func__); measure_cumulative_execution_time measure_cumulative_execution_time_object(time_elapse_aggregator_object); #endif #ifndef MEASURE_CUMULATIVE_FUNCTION_EXECUTION_TIME2 #define MEASURE_CUMULATIVE_FUNCTION_EXECUTION_TIME2(TIME_ELAPSED_IDENTIFIER) static time_elapse_aggregator time_elapse_aggregator_object(TIME_ELAPSED_IDENTIFIER); measure_cumulative_execution_time measure_cumulative_execution_time_object(time_elapse_aggregator_object); #endif
aabbas90/BDD
<|start_filename|>lnetlib/lnetlib/socket_non_ssl.h<|end_filename|> /* The MIT License (MIT) Copyright (c) 2015 <NAME> 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. */ #ifndef LNETLIB_SOCKET_NON_SSL_H #define LNETLIB_SOCKET_NON_SSL_H #include "config.h" #include "asio/ip/tcp.hpp" #include "socket.h" namespace lnetlib { class socket_non_ssl : public socket { public: using tcp = asio::ip::tcp; using socket_base = asio::socket_base; socket_non_ssl(std::shared_ptr<tcp::socket> socket); ~socket_non_ssl() override; bool is_open() const override; void close() override; void async_read(stream_buffer& buffer, completion_cond cond, async_read_handler handler) override; void async_write(const package_buffer& buffer, async_write_handler handler) override; private: std::shared_ptr<tcp::socket> _socket; }; } #endif // LNETLIB_SOCKET_NON_SSL_H <|start_filename|>lnetlib/lnetlib/istream.cpp<|end_filename|> /* The MIT License (MIT) Copyright (c) 2015 <NAME> 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. */ #include "istream.h" namespace lnetlib { istream::istream(std::shared_ptr<stream_buffer> buffer) : std::istream(buffer.get()), _buffer(buffer) { this->read(reinterpret_cast<char*>(&_uid), sizeof(uint64_t)); this->read(reinterpret_cast<char*>(&_command), sizeof(uint64_t)); } istream::~istream() { } uint64_t istream::uid() const { return _uid; } int8_t istream::read_int8() { return read_basic<int8_t>(); } uint8_t istream::read_uint8() { return read_basic<uint8_t>(); } int16_t istream::read_int16() { return read_basic<int16_t>(); } uint16_t istream::read_uint16() { return read_basic<uint16_t>(); } int32_t istream::read_int32() { return read_basic<int32_t>(); } uint32_t istream::read_uint32() { return read_basic<uint32_t>(); } int64_t istream::read_int64() { return read_basic<int64_t>(); } uint64_t istream::read_uint64() { return read_basic<uint64_t>(); } float istream::read_float32() { return read_basic<float>(); } double istream::read_float64() { return read_basic<double>(); } std::unique_ptr<ostream> istream::create_response() { std::unique_ptr<ostream> stream { new ostream(_command, _uid) }; stream->dispatch.connect([this](std::unique_ptr<stream_buffer> buffer) { response_dispatch(std::move(buffer)); }); return stream; } } <|start_filename|>example/client/main.cpp<|end_filename|> #include <lnetlib/client.h> #include <iostream> #include <fstream> enum class Command { Hello = 0, Goodbye, Quit, SendFile, Message }; int main(int argc, char *argv[]) { (void)argc; (void)argv; lnetlib::client client; client.refused.connect([]() { std::cout << "connection refused\n"; std::cout.flush(); }); client.connected.connect([]() { std::cout << "connected\n"; std::cout.flush(); }); client.disconnected.connect([]() { std::cout << "disconnected\n"; std::cout.flush(); }); client.error.connect([](int code, const std::string& message) { std::cout << "error (" << code << "): " << message << "\n"; std::cout.flush(); }); client.received.connect([](std::unique_ptr<lnetlib::istream> stream) { switch (stream->command<Command>()) { case Command::Hello: { std::string msg = stream->read_string(); std::cout << "server says: hello, " << msg << "\n"; std::cout.flush(); break; } case Command::Goodbye: { std::cout << "server says: goodbye!\n"; std::cout.flush(); break; } case Command::SendFile: { std::string filename = stream->read_string(); std::vector<char> bytes = stream->read_data_chunk(); std::ofstream fstream(filename, std::ios::binary | std::ios::out); fstream.write(bytes.data(), bytes.size()); std::cout << "received file \"" << filename << "\"\n"; std::cout.flush(); break; } default: break; } }); auto encryption = client.encryption_info(); encryption->init(lnetlib::encryption_method::tlsv11); encryption->set_verify_callback([](bool preverified, X509_STORE_CTX *context) -> bool { char subject_name[256]; X509* cert = X509_STORE_CTX_get_current_cert(context); X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256); std::cout << "peer certificate subject name: " << subject_name << "\n"; std::cout.flush(); return preverified; }); encryption->set_ca_filename("ca.crt"); encryption->set_cert_filename("client.crt"); encryption->set_private_key_filename("client.key"); encryption->set_verify_mode(lnetlib::ssl_verify_peer); encryption->set_enabled(true); client.connect("127.0.0.1", 7777); char cmd = 0; bool loop = true; while (loop) { std::cin >> cmd; switch (cmd) { case 'q': { auto stream = client.conn()->create_stream(Command::Quit); stream->send(); break; } case 'm': { auto callback = [](std::unique_ptr<lnetlib::istream> stream) { std::string msg = stream->read_string(); std::cout << "callback message: " << msg << "\n"; std::cout.flush(); }; auto stream = client.conn()->create_stream(Command::Message, callback); stream->send(); break; } default: break; } } return 0; } <|start_filename|>lnetlib/lnetlib/server.cpp<|end_filename|> /* The MIT License (MIT) Copyright (c) 2015 <NAME> 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. */ #include "server.h" namespace lnetlib { server::server() : _running(false), _thread_policy(server_thread_policy::one_per_connection), _thread_count(0), _encryption(new encryption()) { } server::~server() { } server_thread_policy server::thread_policy() const { return _thread_policy; } void server::set_thread_policy(server_thread_policy thread_policy, int32_t thread_count) { if (_running) { return; } _thread_policy = thread_policy; _thread_count = thread_count; } std::shared_ptr<encryption> server::encryption_info() const { return _encryption; } void server::start(const std::string& addr, int port) { if (_running) { return; } if (!_encryption->last_error().empty()) { error(nullptr, -1, _encryption->last_error()); return; } _endpoint = tcp::endpoint(address::from_string(addr), port); try { _acceptor = std::make_shared<tcp::acceptor>(_service, _endpoint); _running = true; wait_first_connection(); } catch (const asio::system_error& sys_err) { error(nullptr, sys_err.code().value(), sys_err.code().message()); } } void server::stop() { if (!_running) { return; } _service.stop(); _running = false; } std::list<std::shared_ptr<connection>> server::connections() { std::lock_guard<std::mutex> locker(_mutex); return _connections; } void server::wait_first_connection() { create_session(); switch (_thread_policy) { case server_thread_policy::fixed_count: init_service_threads(); break; case server_thread_policy::one_per_connection: create_service_thread(); break; default: break; } } void server::wait_next_connection() { create_session(); if (_thread_policy == server_thread_policy::one_per_connection) { create_service_thread(); } } void server::create_session() { server_session *session = nullptr; if (!_encryption->is_enabled()) { session = new server_session_non_ssl(_service, _acceptor); } else { session = new server_session_ssl(_service, _acceptor, _encryption); } auto handler = std::bind(&server::connected_handler, this, session, std::placeholders::_1, std::placeholders::_2); session->connected.connect(handler); session->start(); } void server::connected_handler(server_session *session, std::shared_ptr<connection> conn, const error_code& err) { if (err) { error(conn, err.value(), err.message()); } else { add_connection(conn, std::shared_ptr<server_session>(session)); wait_next_connection(); } } void server::add_connection(std::shared_ptr<connection> conn, std::shared_ptr<server_session> session) { auto closed_slot = [this](std::shared_ptr<connection> conn) { disconnected(conn); remove_connection(conn); }; auto error_slot = [this](std::shared_ptr<connection> conn, int code, const std::string& message) { error(conn, code, message); }; auto received_slot = [this](std::shared_ptr<connection> conn, std::unique_ptr<istream> stream) { received(conn, std::move(stream)); }; conn->closed.connect(closed_slot); conn->error.connect(error_slot); conn->received.connect(received_slot); std::lock_guard<std::mutex> locker(_mutex); _connections.push_back(conn); _sessions[conn] = session; connected(conn); } void server::remove_connection(std::shared_ptr<connection> conn) { std::lock_guard<std::mutex> locker(_mutex); auto connection_iter = std::find(_connections.begin(), _connections.end(), conn); if (connection_iter != _connections.end()) { _connections.erase(connection_iter); } auto session_iter = _sessions.find(conn); if (session_iter != _sessions.end()) { _sessions.erase(session_iter); } } void server::init_service_threads() { if (_thread_count == -1) { _thread_count = std::thread::hardware_concurrency(); if (_thread_count == -1) { _thread_count = 2; } } if (_thread_count > 0) { for (int i = 0; i < _thread_count; ++i) { create_service_thread(); } } else { _service.run(); } } void server::create_service_thread() { auto thread_func = [this]() { _service.run(); }; std::thread thread(thread_func); thread.detach(); } } <|start_filename|>example/server/main.cpp<|end_filename|> #include <lnetlib/server.h> #include <iostream> #include <fstream> enum class Command { Hello = 0, Goodbye, Quit, SendFile, Message }; int main(int argc, char *argv[]) { (void)argc; (void)argv; lnetlib::server server; server.connected.connect([](std::shared_ptr<lnetlib::connection> conn) { (void)conn; std::cout << "client connected\n"; std::cout.flush(); }); server.disconnected.connect([](std::shared_ptr<lnetlib::connection> conn) { (void)conn; std::cout << "client disconnected\n"; std::cout.flush(); }); server.error.connect([](std::shared_ptr<lnetlib::connection> conn, int code, const std::string& message) { (void)conn; std::cout << "error (" << code << "): " << message << "\n"; std::cout.flush(); }); server.received.connect([](std::shared_ptr<lnetlib::connection> conn, std::unique_ptr<lnetlib::istream> stream) { switch (stream->command<Command>()) { case Command::Message: { auto response = stream->create_response(); response->write_string("ready\nsteady\ngo!\n"); response->send(); break; } case Command::Quit: { auto stream = conn->create_stream(Command::Goodbye); stream->send(); conn->close(); break; } default: break; } }); auto encryption = server.encryption_info(); encryption->init(lnetlib::encryption_method::tlsv11); encryption->set_verify_callback([](bool preverified, X509_STORE_CTX *context) -> bool { char subject_name[256]; X509* cert = X509_STORE_CTX_get_current_cert(context); X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256); std::cout << "peer certificate subject name: " << subject_name << "\n"; std::cout.flush(); return preverified; }); encryption->set_ca_filename("ca.crt"); encryption->set_cert_filename("server.crt"); encryption->set_private_key_filename("server.key"); encryption->set_verify_mode(lnetlib::ssl_verify_peer | lnetlib::ssl_verify_fail_if_no_peer_cert); encryption->set_enabled(true); server.start("127.0.0.1", 7777); char cmd = 0; bool loop = true; while (loop) { std::cin >> cmd; switch (cmd) { case 'h': for (auto conn : server.connections()) { auto stream = conn->create_stream(Command::Hello); stream->write_string("I'm server!\n"); } break; case 'f': { std::cout << "input filename: "; std::cout.flush(); std::string filename; std::cin >> filename; std::ifstream fstream(filename, std::ios::binary | std::ios::ate); if (!fstream.is_open()) { std::cout << "file not found\n"; std::cout.flush(); break; } uint64_t size = fstream.tellg(); std::vector<char> bytes; bytes.resize(size); fstream.seekg(0); fstream.read(bytes.data(), size); for (auto conn : server.connections()) { auto stream = conn->create_stream(Command::SendFile); stream->write_string(filename); stream->write_data_chunk(bytes); std::cout << "file sended\n"; std::cout.flush(); } } break; case 'q': loop = false; break; default: break; } } return 0; } <|start_filename|>lnetlib/lnetlib/connection.cpp<|end_filename|> /* The MIT License (MIT) Copyright (c) 2015 <NAME> 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. */ #include "connection.h" namespace lnetlib { connection::connection(std::shared_ptr<socket> sckt) : _socket(sckt), _socket_locked(false), _uid_counter(0) { wait_package(); } connection::~connection() { } bool connection::is_open() const { return _socket->is_open(); } void connection::close() { _socket->close(); closed(shared_from_this()); } bool connection::check_error(const error_code& err) { if (!err) { return true; } switch (err.value()) { case asio::error::operation_aborted: break; case custom_error::no_such_file_or_directory: closed(shared_from_this()); break; case custom_error::ssl_short_read: closed(shared_from_this()); break; default: error(shared_from_this(), err.value(), err.message()); break; } return false; } void connection::wait_package() { std::lock_guard<std::mutex> locker(_mutex); std::shared_ptr<stream_buffer> buffer = std::make_shared<stream_buffer>(); auto handler = std::bind(&connection::read_package_size_handler, this, buffer, std::placeholders::_1, std::placeholders::_2); _socket->async_read(*buffer.get(), asio::transfer_exactly(sizeof(uint64_t)), handler); } void connection::wait_package_body(uint64_t size) { std::lock_guard<std::mutex> locker(_mutex); std::shared_ptr<stream_buffer> buffer = std::make_shared<stream_buffer>(); auto handler = std::bind(&connection::read_package_body_handler, this, buffer, std::placeholders::_1, std::placeholders::_2); _socket->async_read(*buffer.get(), asio::transfer_exactly(size), handler); } void connection::read_package_size_handler(std::shared_ptr<stream_buffer> buffer, const error_code& err, std::size_t bytes) { if (!check_error(err)) { return; } if (bytes == 0) { return; } uint64_t size = 0; std::istream stream(buffer.get()); stream.read(reinterpret_cast<char*>(&size), sizeof(uint64_t)); wait_package_body(size); } void connection::read_package_body_handler(std::shared_ptr<stream_buffer> buffer, const error_code& err, std::size_t bytes) { if (!check_error(err)) { return; } if (bytes == 0) { return; } std::unique_ptr<istream> stream { new istream(buffer) }; stream->response_dispatch.connect(create_dispatch_slot()); auto iter = _callbacks.find(stream->uid()); if (iter != _callbacks.end()) { callback cb = _callbacks[stream->uid()]; _callbacks.erase(iter); cb(std::move(stream)); } else { received(shared_from_this(), std::move(stream)); } wait_package(); } std::shared_ptr<connection::package> connection::create_package(std::unique_ptr<stream_buffer> buffer) const { std::unique_ptr<stream_buffer> size_buffer { new stream_buffer() }; std::ostream size_stream(size_buffer.get()); uint64_t size = asio::buffer_size(buffer->data()); size_stream.write(reinterpret_cast<char*>(&size), sizeof(uint64_t)); std::shared_ptr<package> pkg = std::make_shared<package>(); pkg->size_buffer = std::move(size_buffer); pkg->data_buffer = std::move(buffer); pkg->buffer = std::unique_ptr<package_buffer>(new package_buffer()); pkg->buffer->push_back(pkg->size_buffer->data()); pkg->buffer->push_back(pkg->data_buffer->data()); return pkg; } void connection::send_package(std::shared_ptr<package> pkg) { auto write_handler = [this](std::shared_ptr<package> pkg, const error_code& err, std::size_t bytes) { (void)pkg; (void)bytes; if (!check_error(err)) { return; } std::lock_guard<std::mutex> locker(_mutex); if (!_packages.empty()) { std::shared_ptr<package> pkg = _packages.front(); _packages.pop(); send_package(pkg); } else { _socket_locked = false; } }; auto handler = std::bind(write_handler, pkg, std::placeholders::_1, std::placeholders::_2); _socket_locked = true; _socket->async_write(*(pkg->buffer.get()), handler); } connection::dispatch_slot connection::create_dispatch_slot() { dispatch_slot slot = [this](std::unique_ptr<stream_buffer> buffer) { std::shared_ptr<package> pkg = create_package(std::move(buffer)); std::lock_guard<std::mutex> locker(_mutex); if (_socket_locked) { _packages.push(pkg); } else { send_package(pkg); } }; return slot; } } <|start_filename|>lnetlib/lnetlib/server_session_non_ssl.cpp<|end_filename|> /* The MIT License (MIT) Copyright (c) 2015 <NAME> 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. */ #include "server_session_non_ssl.h" namespace lnetlib { server_session_non_ssl::server_session_non_ssl(service& srv, std::shared_ptr<tcp::acceptor> acceptor) : _socket(new tcp::socket(srv)), _acceptor(acceptor) { } server_session_non_ssl::~server_session_non_ssl() { } void server_session_non_ssl::start() { auto handler = std::bind(&server_session_non_ssl::accept_handler, this, std::placeholders::_1); _acceptor->async_accept(*_socket.get(), handler); } void server_session_non_ssl::accept_handler(const error_code& err) { std::shared_ptr<connection> conn; if (!err) { std::shared_ptr<socket> sckt = std::make_shared<socket_non_ssl>(_socket); conn = std::make_shared<connection>(sckt); } connected(conn, err); } } <|start_filename|>lnetlib/lnetlib/connection.h<|end_filename|> /* The MIT License (MIT) Copyright (c) 2015 <NAME> 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. */ #ifndef LNETLIB_CONNECTION_H #define LNETLIB_CONNECTION_H #include "config.h" #include <mutex> #include <memory> #include <thread> #include <map> #include <queue> #include <functional> #include "asio/error.hpp" #include "asio/ip/tcp.hpp" #include "asio/buffer.hpp" #include "asio/read.hpp" #include "asio/write.hpp" #include "asio/streambuf.hpp" #include "lsignal/lsignal.h" #include "istream.h" #include "ostream.h" #include "socket.h" namespace lnetlib { class connection : public std::enable_shared_from_this<connection> { public: enum custom_error { no_such_file_or_directory = 2, // ENOENT ssl_short_read = 335544539 // SSL_R_SHORT_READ }; using error_code = asio::error_code; using tcp = asio::ip::tcp; using data_buffer = asio::const_buffers_1; using stream_buffer = asio::streambuf; using package_buffer = std::vector<stream_buffer::const_buffers_type>; using callback = std::function<void(std::unique_ptr<istream>)>; using dispatch_slot = std::function<void(std::unique_ptr<stream_buffer> buffer)>; lsignal::signal<void(std::shared_ptr<connection>)> closed; lsignal::signal<void(std::shared_ptr<connection>, int, const std::string&)> error; lsignal::signal<void(std::shared_ptr<connection>, std::unique_ptr<istream>)> received; connection(std::shared_ptr<socket> sckt); ~connection(); bool is_open() const; void close(); template<typename T> std::unique_ptr<ostream> create_stream(T command); template<typename T> std::unique_ptr<ostream> create_stream(T command, callback cb); private: struct package { std::unique_ptr<package_buffer> buffer; std::unique_ptr<stream_buffer> size_buffer; std::unique_ptr<stream_buffer> data_buffer; }; std::mutex _mutex; std::shared_ptr<socket> _socket; bool _socket_locked; std::queue<std::shared_ptr<package>> _packages; uint64_t _uid_counter; std::map<uint64_t, callback> _callbacks; bool check_error(const error_code& err); void wait_package(); void wait_package_body(uint64_t size); void read_package_size_handler(std::shared_ptr<stream_buffer> buffer, const error_code& err, std::size_t bytes); void read_package_body_handler(std::shared_ptr<stream_buffer> buffer, const error_code& err, std::size_t bytes); std::shared_ptr<package> create_package(std::unique_ptr<stream_buffer> buffer) const; void send_package(std::shared_ptr<package> pkg); dispatch_slot create_dispatch_slot(); }; template<typename T> std::unique_ptr<ostream> connection::create_stream(T command) { std::unique_ptr<ostream> stream { new ostream(command, _uid_counter++) }; stream->dispatch.connect(create_dispatch_slot()); return stream; } template<typename T> std::unique_ptr<ostream> connection::create_stream(T command, callback cb) { std::unique_ptr<ostream> stream = create_stream(command); _callbacks[stream->uid()] = cb; return stream; } } #endif // LNETLIB_CONNECTION_H <|start_filename|>lnetlib/lnetlib/server.h<|end_filename|> /* The MIT License (MIT) Copyright (c) 2015 <NAME> 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. */ #ifndef LNETLIB_SERVER_H #define LNETLIB_SERVER_H #include "config.h" #include <list> #include <memory> #include <mutex> #include <thread> #include "asio/error.hpp" #include "asio/io_service.hpp" #include "asio/ip/tcp.hpp" #include "lsignal/lsignal.h" #include "helper.h" #include "istream.h" #include "ostream.h" #include "encryption.h" #include "connection.h" #include "server_session.h" #include "server_session_ssl.h" #include "server_session_non_ssl.h" namespace lnetlib { enum class server_thread_policy { one_per_connection, fixed_count }; class server { public: using system_error = asio::system_error; using error_code = asio::error_code; using service = asio::io_service; using tcp = asio::ip::tcp; using address = asio::ip::address; lsignal::signal<void(std::shared_ptr<connection>)> connected; lsignal::signal<void(std::shared_ptr<connection>)> disconnected; lsignal::signal<void(std::shared_ptr<connection>, int, const std::string&)> error; lsignal::signal<void(std::shared_ptr<connection>, std::unique_ptr<istream>)> received; server(); ~server(); server_thread_policy thread_policy() const; void set_thread_policy(server_thread_policy thread_policy, int32_t thread_count = -1); std::shared_ptr<encryption> encryption_info() const; void start(const std::string& addr, int port); void stop(); std::list<std::shared_ptr<connection>> connections(); private: bool _running; std::mutex _mutex; server_thread_policy _thread_policy; int32_t _thread_count; service _service; tcp::endpoint _endpoint; std::shared_ptr<tcp::acceptor> _acceptor; std::shared_ptr<encryption> _encryption; std::list<std::shared_ptr<connection>> _connections; std::map<std::shared_ptr<connection>, std::shared_ptr<server_session>> _sessions; void wait_first_connection(); void wait_next_connection(); void wait_connection(bool first = false); void create_session(); void connected_handler(server_session *session, std::shared_ptr<connection> conn, const error_code& err); void add_connection(std::shared_ptr<connection> conn, std::shared_ptr<server_session> session); void remove_connection(std::shared_ptr<connection> conn); void init_service_threads(); void create_service_thread(); }; } #endif // LNETLIB_SERVER_H <|start_filename|>lnetlib/lnetlib/server_session_ssl.cpp<|end_filename|> /* The MIT License (MIT) Copyright (c) 2015 <NAME> 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. */ #include "server_session_ssl.h" namespace lnetlib { server_session_ssl::server_session_ssl(service& srv, std::shared_ptr<tcp::acceptor> acceptor, std::shared_ptr<encryption> encr) : _encryption(encr), _socket(new ssl_socket(srv, encr->context())), _acceptor(acceptor) { } server_session_ssl::~server_session_ssl() { } void server_session_ssl::start() { _socket->set_verify_mode(_encryption->verify_mode()); auto verify_callback = [this](bool preverified, verify_context& context) { return _encryption->verify_certificate(preverified, context); }; _socket->set_verify_callback(verify_callback); auto handler = std::bind(&server_session_ssl::accept_handler, this, std::placeholders::_1); _acceptor->async_accept(_socket->lowest_layer(), handler); } void server_session_ssl::accept_handler(const error_code& err) { if (err) { connected(nullptr, err); return; } auto handler = std::bind(&server_session_ssl::handshake_handler, this, std::placeholders::_1); _socket->async_handshake(ssl_stream_base::server, handler); } void server_session_ssl::handshake_handler(const error_code& err) { std::shared_ptr<connection> conn; if (!err) { std::shared_ptr<socket> sckt = std::make_shared<socket_ssl>(_socket); conn = std::make_shared<connection>(sckt); } connected(conn, err); } } <|start_filename|>lnetlib/lnetlib/encryption.h<|end_filename|> /* The MIT License (MIT) Copyright (c) 2015 <NAME> 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. */ #ifndef LNETLIB_ENCRYPTION_H #define LNETLIB_ENCRYPTION_H #include "config.h" #include <functional> #include "asio/ssl/context.hpp" #include "helper.h" namespace lnetlib { enum class encryption_method { sslv2 = asio::ssl::context::sslv2, sslv3 = asio::ssl::context::sslv3, tlsv1 = asio::ssl::context::tlsv1, sslv23 = asio::ssl::context::sslv23, tlsv11 = asio::ssl::context::tlsv11, tlsv12 = asio::ssl::context::tlsv12 }; enum ssl_verify_mode { ssl_verify_none = asio::ssl::verify_none, ssl_verify_peer = asio::ssl::verify_peer, ssl_verify_fail_if_no_peer_cert = asio::ssl::verify_fail_if_no_peer_cert, ssl_verify_client_once = asio::ssl::verify_client_once }; class encryption { public: using const_buffer = asio::const_buffer; using ssl_context = asio::ssl::context; using verify_context = asio::ssl::verify_context; using verify_callback = std::function<bool(bool, X509_STORE_CTX*)>; encryption(); ~encryption(); void init(encryption_method method); bool is_enabled() const; void set_enabled(bool enabled); std::string ca_filename() const; void set_ca_filename(const std::string& filename); std::string cert_filename() const; void set_cert_filename(const std::string& filename); std::string private_key_filename() const; void set_private_key_filename(const std::string& filename); int verify_mode() const; void set_verify_mode(int mode); void set_verify_callback(verify_callback callback); bool verify_certificate(bool preverified, verify_context& context); ssl_context& context(); std::string last_error() const; private: bool _enabled; encryption_method _method; std::string _ca_filename; std::string _cert_filename; std::string _private_key_filename; int _verify_mode; verify_callback _verify_callback; ssl_context _context; std::string _last_error; }; } #endif // LNETLIB_ENCRYPTION_H <|start_filename|>lnetlib/lnetlib/helper.cpp<|end_filename|> /* The MIT License (MIT) Copyright (c) 2015 <NAME> 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. */ #include "helper.h" namespace lnetlib { helper::file helper::read_binary_file(const std::string& filename) { uint64_t size = 0; char* data = nullptr; std::ifstream stream(filename, std::ios::binary | std::ios::ate); if (stream.is_open()) { size = stream.tellg(); data = new char[size]; stream.seekg(0); stream.read(data, size); } return file(std::unique_ptr<char>(data), size); } } <|start_filename|>lnetlib/lnetlib/socket.h<|end_filename|> /* The MIT License (MIT) Copyright (c) 2015 <NAME> 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. */ #ifndef LNETLIB_SOCKET_H #define LNETLIB_SOCKET_H #include "config.h" #include <functional> #include "asio/error.hpp" #include "asio/read.hpp" #include "asio/write.hpp" #include "asio/streambuf.hpp" namespace lnetlib { class socket { public: using error_code = asio::error_code; using stream_buffer = asio::streambuf; using package_buffer = std::vector<stream_buffer::const_buffers_type>; using completion_cond = std::function<std::size_t(const error_code&, std::size_t)>; using async_read_handler = std::function<void(const error_code&, std::size_t)>; using async_write_handler = std::function<void(const error_code&, std::size_t)>; socket(); virtual ~socket(); virtual bool is_open() const = 0; virtual void close() = 0; virtual void async_read(stream_buffer& buffer, completion_cond cond, async_read_handler handler) = 0; virtual void async_write(const package_buffer& buffer, async_write_handler handler) = 0; }; } #endif // LNETLIB_SOCKET_H <|start_filename|>lnetlib/lnetlib/ostream.h<|end_filename|> /* The MIT License (MIT) Copyright (c) 2015 <NAME> 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. */ #ifndef LNETLIB_OUT_STREAM_H #define LNETLIB_OUT_STREAM_H #include "config.h" #include <memory> #include <ostream> #include "asio/streambuf.hpp" #include "lsignal/lsignal.h" namespace lnetlib { class ostream : public std::ostream { public: using stream_buffer = asio::streambuf; lsignal::signal<void(std::unique_ptr<stream_buffer>)> dispatch; template<typename T> ostream(T command, uint64_t uid); ~ostream(); uint64_t uid() const; void write_int8(int8_t data); void write_uint8(uint8_t data); void write_int16(int16_t data); void write_uint16(uint16_t data); void write_int32(int32_t data); void write_uint32(uint32_t data); void write_int64(int64_t data); void write_uint64(uint64_t data); void write_float32(float data); void write_float64(double data); template<typename T = uint64_t> void write_string(const std::string& data); template<typename T = char, typename U = uint64_t> void write_data_chunk(const T *data, U size); template<typename T = char, typename U = uint64_t> void write_data_chunk(const std::vector<T>& data); void send(); private: std::unique_ptr<stream_buffer> _buffer; bool _sended; uint64_t _uid; template<typename T> void write_basic(T data); }; template<typename T> ostream::ostream(T command, uint64_t uid) : _buffer(new stream_buffer()), _sended(false), _uid(uid) { init(_buffer.get()); uint64_t cmd = static_cast<uint64_t>(command); this->write(reinterpret_cast<const char*>(&uid), sizeof(uint64_t)); this->write(reinterpret_cast<const char*>(&cmd), sizeof(uint64_t)); } template<typename T> void ostream::write_basic(T data) { write(reinterpret_cast<const char*>(&data), sizeof(T)); } template<typename T> void ostream::write_string(const std::string& data) { write_basic<T>(static_cast<T>(data.size())); write(data.data(), data.size()); } template<typename T, typename U> void ostream::write_data_chunk(const T *data, U size) { write_basic<U>(size); write(reinterpret_cast<const char*>(data), size * sizeof(T)); } template<typename T, typename U> void ostream::write_data_chunk(const std::vector<T>& data) { write_data_chunk<T, U>(data.data(), data.size()); } } #endif // LNETLIB_OUT_STREAM_H <|start_filename|>lnetlib/lnetlib/client.cpp<|end_filename|> /* The MIT License (MIT) Copyright (c) 2015 <NAME> 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. */ #include "client.h" namespace lnetlib { client::client() : _running(false), _encryption(new encryption()) { } client::~client() { } std::shared_ptr<encryption> client::encryption_info() const { return _encryption; } void client::connect(const std::string& hostname, int port) { if (_running) { return; } if (!_encryption->last_error().empty()) { error(-1, _encryption->last_error()); return; } _running = true; tcp::resolver resolver(_service); tcp::resolver::query resolver_query(hostname, std::to_string(port)); _endpoint = resolver.resolve(resolver_query); try_connect(); } void client::disconnect() { if (!_running) { return; } _service.stop(); _running = false; } std::shared_ptr<connection> client::conn() const { return _connection; } void client::try_connect() { create_session(); auto thread_func = [this]() { _service.run(); }; std::thread thread(thread_func); thread.detach(); } void client::create_session() { client_session *session = nullptr; if (!_encryption->is_enabled()) { session = new client_session_non_ssl(_service, _endpoint); } else { session = new client_session_ssl(_service, _endpoint, _encryption); } auto handler = std::bind(&client::connected_handler, this, session, std::placeholders::_1, std::placeholders::_2); session->connected.connect(handler); session->start(); } void client::connected_handler(client_session *session, std::shared_ptr<connection> conn, const error_code& err) { if (err) { switch (err.value()) { case asio::error::connection_refused: refused(); break; default: error(err.value(), err.message()); break; } return; } _connection = conn; _session = std::shared_ptr<client_session>(session); auto closed_slot = [this](std::shared_ptr<connection> conn) { (void)conn; disconnected(); }; auto error_slot = [this](std::shared_ptr<connection> conn, int code, const std::string& message) { (void)conn; error(code, message); }; auto received_slot = [this](std::shared_ptr<connection> conn, std::unique_ptr<istream> stream) { (void)conn; received(std::move(stream)); }; _connection->closed.connect(closed_slot); _connection->error.connect(error_slot); _connection->received.connect(received_slot); connected(); } void client::error_handler(std::shared_ptr<connection> conn, int code, const std::string& message) { (void)conn; error(code, message); } void client::received_handler(std::shared_ptr<connection> conn, std::unique_ptr<istream> stream) { (void)conn; received(std::move(stream)); } } <|start_filename|>lnetlib/lnetlib/socket_non_ssl.cpp<|end_filename|> /* The MIT License (MIT) Copyright (c) 2015 <NAME> 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. */ #include "socket_non_ssl.h" namespace lnetlib { socket_non_ssl::socket_non_ssl(std::shared_ptr<tcp::socket> socket) : _socket(socket) { } socket_non_ssl::~socket_non_ssl() { } bool socket_non_ssl::is_open() const { return _socket->is_open(); } void socket_non_ssl::close() { _socket->shutdown(socket_base::shutdown_both); _socket->close(); } void socket_non_ssl::async_read(stream_buffer& buffer, completion_cond cond, async_read_handler handler) { asio::async_read(*_socket, buffer, cond, handler); } void socket_non_ssl::async_write(const package_buffer& buffer, async_write_handler handler) { asio::async_write(*_socket, buffer, handler); } } <|start_filename|>lnetlib/lnetlib/socket_ssl.h<|end_filename|> /* The MIT License (MIT) Copyright (c) 2015 <NAME> 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. */ #ifndef LNETLIB_SOCKET_SSL_H #define LNETLIB_SOCKET_SSL_H #include "config.h" #include "asio/ip/tcp.hpp" #include "asio/ssl/stream.hpp" #include "socket.h" namespace lnetlib { class socket_ssl : public socket { public: using tcp = asio::ip::tcp; using socket_base = asio::socket_base; using ssl_socket = asio::ssl::stream<tcp::socket>; socket_ssl(std::shared_ptr<ssl_socket> socket); ~socket_ssl() override; bool is_open() const override; void close() override; void async_read(stream_buffer& buffer, completion_cond cond, async_read_handler handler) override; void async_write(const package_buffer& buffer, async_write_handler handler) override; private: std::shared_ptr<ssl_socket> _socket; }; } #endif // LNETLIB_SOCKET_SSL_H <|start_filename|>lnetlib/lnetlib/client.h<|end_filename|> /* The MIT License (MIT) Copyright (c) 2015 <NAME> 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. */ #ifndef LNETLIB_CLIENT_H #define LNETLIB_CLIENT_H #include "config.h" #include <memory> #include <string> #include <thread> #include "asio/error.hpp" #include "asio/io_service.hpp" #include "asio/ip/tcp.hpp" #include "asio/ssl/context.hpp" #include "lsignal/lsignal.h" #include "helper.h" #include "istream.h" #include "ostream.h" #include "encryption.h" #include "connection.h" #include "client_session.h" #include "client_session_ssl.h" #include "client_session_non_ssl.h" namespace lnetlib { class client { public: using error_code = asio::error_code; using service = asio::io_service; using tcp = asio::ip::tcp; using socket_base = asio::socket_base; using address = asio::ip::address; lsignal::signal<void()> refused; lsignal::signal<void()> connected; lsignal::signal<void()> disconnected; lsignal::signal<void(int, const std::string&)> error; lsignal::signal<void(std::unique_ptr<istream> stream)> received; client(); ~client(); std::shared_ptr<encryption> encryption_info() const; void connect(const std::string& hostname, int port); void disconnect(); std::shared_ptr<connection> conn() const; private: bool _running; service _service; tcp::resolver::iterator _endpoint; std::shared_ptr<encryption> _encryption; std::shared_ptr<connection> _connection; std::shared_ptr<client_session> _session; void try_connect(); void create_session(); void connected_handler(client_session *session, std::shared_ptr<connection> conn, const error_code& err); void error_handler(std::shared_ptr<connection> conn, int code, const std::string& message); void received_handler(std::shared_ptr<connection> conn, std::unique_ptr<istream> stream); }; } #endif // LNETLIB_CLIENT_H <|start_filename|>lnetlib/lnetlib/server_session.h<|end_filename|> /* The MIT License (MIT) Copyright (c) 2015 <NAME> 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. */ #ifndef LNETLIB_SERVER_SESSION_H #define LNETLIB_SERVER_SESSION_H #include "config.h" #include "asio/error.hpp" #include "asio/io_service.hpp" #include "asio/ip/tcp.hpp" #include "lsignal/lsignal.h" #include "connection.h" namespace lnetlib { class server_session { public: using error_code = asio::error_code; using service = asio::io_service; using tcp = asio::ip::tcp; lsignal::signal<void(std::shared_ptr<connection>, const error_code&)> connected; server_session(); virtual ~server_session(); virtual void start() = 0; }; } #endif // LNETLIB_SERVER_SESSION_H <|start_filename|>lnetlib/lnetlib/encryption.cpp<|end_filename|> /* The MIT License (MIT) Copyright (c) 2015 <NAME> 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. */ #include "encryption.h" namespace lnetlib { encryption::encryption() : _enabled(false), _method(encryption_method::tlsv11), _verify_mode(ssl_verify_none), _context(static_cast<ssl_context::method>(_method)) { } encryption::~encryption() { } void encryption::init(encryption_method method) { _last_error.clear(); _method = method; _ca_filename.clear(); _cert_filename.clear(); _private_key_filename.clear(); _verify_mode = ssl_verify_none; _verify_callback = verify_callback(); _context = std::move(ssl_context(static_cast<ssl_context::method>(_method))); } bool encryption::is_enabled() const { return _enabled; } void encryption::set_enabled(bool enabled) { _enabled = enabled; } std::string encryption::ca_filename() const { return _ca_filename; } void encryption::set_ca_filename(const std::string& filename) { _last_error.clear(); if (!filename.empty()) { auto file = helper::read_binary_file(filename); if (file.second > 0) { _context.add_certificate_authority(const_buffer(file.first.get(), file.second)); } else { _last_error = "Can't read CA file"; } } } std::string encryption::cert_filename() const { return _cert_filename; } void encryption::set_cert_filename(const std::string& filename) { _cert_filename = filename; _context.use_certificate_file(filename, ssl_context::pem); } std::string encryption::private_key_filename() const { return _private_key_filename; } void encryption::set_private_key_filename(const std::string& filename) { _private_key_filename = filename; _context.use_private_key_file(filename, ssl_context::pem); } int encryption::verify_mode() const { return _verify_mode; } void encryption::set_verify_mode(int mode) { _verify_mode = mode; } void encryption::set_verify_callback(verify_callback callback) { _verify_callback = callback; } bool encryption::verify_certificate(bool preverified, verify_context& context) { if (_verify_callback) { return _verify_callback(preverified, context.native_handle()); } return preverified; } std::string encryption::last_error() const { return _last_error; } encryption::ssl_context& encryption::context() { return _context; } } <|start_filename|>lnetlib/lnetlib/socket_ssl.cpp<|end_filename|> /* The MIT License (MIT) Copyright (c) 2015 <NAME> 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. */ #include "socket_ssl.h" namespace lnetlib { socket_ssl::socket_ssl(std::shared_ptr<ssl_socket> socket) : _socket(socket) { } socket_ssl::~socket_ssl() { } bool socket_ssl::is_open() const { return _socket->lowest_layer().is_open(); } void socket_ssl::close() { _socket->lowest_layer().shutdown(socket_base::shutdown_receive); _socket->lowest_layer().close(); } void socket_ssl::async_read(stream_buffer& buffer, completion_cond cond, async_read_handler handler) { asio::async_read(*_socket, buffer, cond, handler); } void socket_ssl::async_write(const package_buffer& buffer, async_write_handler handler) { asio::async_write(*_socket, buffer, handler); } } <|start_filename|>lnetlib/lnetlib/ostream.cpp<|end_filename|> /* The MIT License (MIT) Copyright (c) 2015 <NAME> 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. */ #include "ostream.h" namespace lnetlib { ostream::~ostream() { send(); } uint64_t ostream::uid() const { return _uid; } void ostream::write_int8(int8_t data) { write_basic<int8_t>(data); } void ostream::write_uint8(uint8_t data) { write_basic<uint8_t>(data); } void ostream::write_int16(int16_t data) { write_basic<int16_t>(data); } void ostream::write_uint16(uint16_t data) { write_basic<uint16_t>(data); } void ostream::write_int32(int32_t data) { write_basic<int32_t>(data); } void ostream::write_uint32(uint32_t data) { write_basic<uint32_t>(data); } void ostream::write_int64(int64_t data) { write_basic<int64_t>(data); } void ostream::write_uint64(uint64_t data) { write_basic<uint64_t>(data); } void ostream::write_float32(float data) { write_basic<float>(data); } void ostream::write_float64(double data) { write_basic<double>(data); } void ostream::send() { if (_sended) { return; } _sended = true; dispatch(std::move(_buffer)); } } <|start_filename|>lnetlib/lnetlib/istream.h<|end_filename|> /* The MIT License (MIT) Copyright (c) 2015 <NAME> 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. */ #ifndef LNETLIB_ISTREAM_H #define LNETLIB_ISTREAM_H #include "config.h" #include <istream> #include <memory> #include "asio/streambuf.hpp" #include "ostream.h" namespace lnetlib { class istream : public std::istream { public: using stream_buffer = asio::streambuf; lsignal::signal<void(std::unique_ptr<stream_buffer>)> response_dispatch; istream(std::shared_ptr<stream_buffer> buffer); ~istream(); template<typename T> T command() const; uint64_t uid() const; int8_t read_int8(); uint8_t read_uint8(); int16_t read_int16(); uint16_t read_uint16(); int32_t read_int32(); uint32_t read_uint32(); int64_t read_int64(); uint64_t read_uint64(); float read_float32(); double read_float64(); template<typename T = uint64_t> std::string read_string(); template<typename T = char, typename U = uint64_t> const T* read_data_chunk(U& size); template<typename T = char, typename U = uint64_t> std::vector<T> read_data_chunk(); std::unique_ptr<ostream> create_response(); private: std::shared_ptr<stream_buffer> _buffer; uint64_t _uid; uint64_t _command; template<typename T> T read_basic(); }; template<typename T> T istream::command() const { return static_cast<T>(_command); } template<typename T> std::string istream::read_string() { T size = read_basic<T>(); char data[size]; read(data, size); return std::string(data, 0, size); } template<typename T, typename U> const T* istream::read_data_chunk(U& size) { size = read_basic<U>(); T *data = new char[size]; read(reinterpret_cast<char*>(data), size * sizeof(T)); return data; } template<typename T, typename U> std::vector<T> istream::read_data_chunk() { U size = read_basic<U>(); std::vector<T> chunk(size); read(reinterpret_cast<char*>(chunk.data()), chunk.size() * sizeof(T)); return chunk; } template<typename T> T istream::read_basic() { T data; read(reinterpret_cast<char*>(&data), sizeof(T)); return data; } } #endif // LNETLIB_ISTREAM_H <|start_filename|>lnetlib/lnetlib/client_session_ssl.cpp<|end_filename|> /* The MIT License (MIT) Copyright (c) 2015 <NAME> 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. */ #include "client_session_ssl.h" namespace lnetlib { client_session_ssl::client_session_ssl(service& srv, tcp::resolver::iterator endpoint, std::shared_ptr<encryption> encr) : _encryption(encr), _socket(new ssl_socket(srv, encr->context())), _endpoint(endpoint) { } client_session_ssl::~client_session_ssl() { } void client_session_ssl::start() { _socket->set_verify_mode(_encryption->verify_mode()); auto verify_callback = [this](bool preverified, verify_context& context) { return _encryption->verify_certificate(preverified, context); }; _socket->set_verify_callback(verify_callback); auto handler = std::bind(&client_session_ssl::connect_handler, this, std::placeholders::_1); async_connect(_socket->lowest_layer(), _endpoint, handler); } void client_session_ssl::connect_handler(const error_code& err) { if (err) { connected(nullptr, err); return; } auto handler = std::bind(&client_session_ssl::handshake_handler, this, std::placeholders::_1); _socket->async_handshake(ssl_stream_base::client, handler); } void client_session_ssl::handshake_handler(const error_code& err) { std::shared_ptr<connection> conn; if (!err) { std::shared_ptr<socket> sckt = std::make_shared<socket_ssl>(_socket); conn = std::make_shared<connection>(sckt); } connected(conn, err); } } <|start_filename|>lnetlib/lnetlib/client_session_non_ssl.cpp<|end_filename|> /* The MIT License (MIT) Copyright (c) 2015 <NAME> 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. */ #include "client_session_non_ssl.h" namespace lnetlib { client_session_non_ssl::client_session_non_ssl(service& srv, tcp::resolver::iterator endpoint) : _socket(new tcp::socket(srv)), _endpoint(endpoint) { } client_session_non_ssl::~client_session_non_ssl() { } void client_session_non_ssl::start() { auto handler = std::bind(&client_session_non_ssl::connect_handler, this, std::placeholders::_1); async_connect(*_socket, _endpoint, handler); } void client_session_non_ssl::connect_handler(const error_code& err) { std::shared_ptr<connection> conn; if (!err) { std::shared_ptr<socket> sckt = std::make_shared<socket_non_ssl>(_socket); conn = std::make_shared<connection>(sckt); } connected(conn, err); } }
cpp11nullptr/lnetlib
<|start_filename|>app/scripts/post-processors/empty-array.js<|end_filename|> /** * Description: When the code have an empty array returns [1; * Input: const a = []; * Output: const a = [1; */ export function emptyArray(code) { return code.replace(/\[1;/g, '[];'); } <|start_filename|>app/scripts/post-processors/index.js<|end_filename|> export * from './template-string'; export * from './empty-array'; <|start_filename|>app/scripts/app.js<|end_filename|> import { createFilePicker } from './file-picker'; import { processImage } from './image-processor'; import { generateSandbox } from './sandbox'; import { bus, BusEvent } from './bus'; const $picker = document.querySelector('.js-picker'); const $result = document.querySelector('.js-result'); const $link = document.querySelector('.js-link'); const $loading = document.querySelector('.js-loading'); const HIDDEN_CLASS = 'is-hidden'; bus.on(BusEvent.ShowLoading, () => $loading.classList.remove(HIDDEN_CLASS)); bus.on(BusEvent.HideLoading, () => $loading.classList.add(HIDDEN_CLASS)); bus.on(BusEvent.ShowResults, () => $result.classList.remove(HIDDEN_CLASS)); bus.on(BusEvent.HideResults, () => $result.classList.add(HIDDEN_CLASS)); createFilePicker($picker); bus.on(BusEvent.FileAdded, processImage); bus.on(BusEvent.ImageProcessed, generateSandbox); bus.on(BusEvent.LinkGenerated, url => { $link.href = url; bus.emit(BusEvent.ShowResults); bus.emit(BusEvent.HideLoading); }); <|start_filename|>tests/e2e/specs/app.spec.js<|end_filename|> describe('My First Test', function() { it('Visits the Kitchen Sink', function() { cy.visit('/') }) }) <|start_filename|>app/scripts/bus.js<|end_filename|> import EventBus from 'js-event-bus'; export const bus = new EventBus(); export const BusEvent = { ShowLoading: 'ShowLoading', HideLoading: 'HideLoading', ShowResults: 'ShowResults', HideResults: 'HideResults', FileAdded: 'FileAdded', ImageProcessed: 'ImageProcessed', LinkGenerated: 'LinkGenerated' }; <|start_filename|>app/scripts/post-processors/template-string.js<|end_filename|> /** * Description: Tempalte string quotes are wrong * Input: const a = `1`; * Output: const a = ‘1‘; */ export function templateString(code) { return code.replace(/‘/g, '`'); } <|start_filename|>app/index.html<|end_filename|> <!DOCTYPE html> <html lang="en"> <head> <title>Screenshot to CodeSandbox conversor</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="shortcut icon" type="image/png" href="/assets/images/favicon.png" /> </head> <body> <div class="conversor container"> <div class="conversor-content"> <h1 class="conversor-title"> Screenshot to CodeSandbox conversor </h1> <p class="conversor-subtitle"> Convert your code screenshots to Code Sandbox projects in a second. </p> <div class="js-picker"></div> <p class="conversor-result is-hidden js-result"> Project generated!! <a href="#" class="js-link" target="_blank">click</a> to open in a new window and get a Code Sandbox link. </p> <div class="conversor-loading is-hidden js-loading"> <span class="conversor-spinner spinner-border"></span> </div> </div> </div> </body> </html> <|start_filename|>app/scripts/sandbox.js<|end_filename|> import { getParameters } from 'codesandbox/lib/api/define'; import { bus, BusEvent } from './bus'; // import { js } from 'js-beautify'; export function generateSandbox(code) { const parameters = getParameters({ files: { 'index.js': { content: code }, 'package.json': { content: { dependencies: {} } } } }); bus.emit(BusEvent.LinkGenerated, null, `https://codesandbox.io/api/v1/sandboxes/define?parameters=${parameters}`); } <|start_filename|>app/scripts/file-picker.js<|end_filename|> import * as FilePond from 'filepond'; import { bus, BusEvent } from './bus'; export function createFilePicker($container) { const file = FilePond.create({ multiple: true, name: 'file' }); $container.appendChild(file.element); $container.querySelector('.filepond--root').addEventListener('FilePond:addfile', () => { const data = file.getFile(); // TODO: Add validators here bus.emit(BusEvent.FileAdded, null, data.file); }); } <|start_filename|>app/scripts/image-processor.js<|end_filename|> import worker from 'tesseract.js'; import { bus, BusEvent } from './bus'; import { templateString, emptyArray } from './post-processors'; const postProcessors = [ templateString, emptyArray ]; function postProcessCode(code) { postProcessors.forEach(x => (code = x(code))); return code; } export function processImage(image) { bus.emit(BusEvent.HideResults); bus.emit(BusEvent.ShowLoading); worker .recognize(image) .then(result => { const processedCode = postProcessCode(result.text); bus.emit(BusEvent.ImageProcessed, null, processedCode); }); }
CKGrafico/screenshotToCodeSandbox
<|start_filename|>server/cron/knownAccounts.json<|end_filename|> [ { "alias": "NanoLooker", "account": "<KEY>" }, { "alias": "NanoBrowserQuest", "account": "<KEY>" }, { "alias": "imalfect", "account": "<KEY>" }, { "alias": "Kuyumcu", "account": "<KEY>" }, { "alias": "Dogecoin creator", "account": "<KEY>" }, { "alias": "NanoTicker speed test", "account": "<KEY>" }, { "alias": "NanoQuakeJS", "account": "<KEY>" }, { "alias": "NanoQuakeJS Payouts #1", "account": "<KEY>" }, { "alias": "NanoQuakeJS Payouts #2", "account": "<KEY>" }, { "alias": "NanoQuakeJS Payouts #3", "account": "<KEY>" }, { "alias": "NanoQuakeJS Payouts #4", "account": "<KEY>" }, { "alias": "NanoQuakeJS Payouts #5", "account": "<KEY>" }, { "alias": "NanoQuakeJS Payouts #6", "account": "<KEY>" }, { "alias": "NanoQuakeJS Payouts #7", "account": "nano_11ftuzfotdtn3bnkaaw8zrj3tmnc4e8pgd3itw7o4p3dn38heppe3xp7ehao" }, { "alias": "NanoQuakeJS Payouts #8", "account": "<KEY>" }, { "alias": "NanoQuakeJS Payouts #9", "account": "<KEY>" }, { "alias": "NanoQuakeJS Payouts #10", "account": "<KEY>" }, { "alias": "NanoQuakeJS Payouts #11", "account": "<KEY>" }, { "alias": "NanoQuakeJS Payouts #12", "account": "<KEY>" }, { "alias": "NanoQuakeJS Payouts #13", "account": "<KEY>" }, { "alias": "NanoQuakeJS Payouts #14", "account": "<KEY>" }, { "alias": "Fight for the future donation", "account": "<KEY>" }, { "alias": "Reddit Nano Giveaway", "account": "<KEY>" }, { "alias": "2miners Payouts", "account": "<KEY>" }, { "alias": "Crypto.com", "account": "<KEY>" } ] <|start_filename|>server/api/2minersStats.js<|end_filename|> const MongoClient = require("mongodb").MongoClient; const { Sentry } = require("../sentry"); const { nodeCache } = require("../client/cache"); const { EXPIRE_24h, MONGO_URL, MONGO_OPTIONS, MONGO_DB, MINERS_STATS, MINERS_STATS_COLLECTION, } = require("../constants"); const get2MinersStats = async () => { let minersStats = nodeCache.get(MINERS_STATS); if (minersStats) { return minersStats; } return new Promise(resolve => { let db; try { MongoClient.connect(MONGO_URL, MONGO_OPTIONS, (err, client) => { if (err) { throw err; } db = client.db(MONGO_DB); db.collection(MINERS_STATS_COLLECTION) .find() .sort({ date: -1 }) .toArray((_err, data = []) => { nodeCache.set(MINERS_STATS, data, EXPIRE_24h); client.close(); resolve(data); }); }); } catch (err) { console.log("Error", err); Sentry.captureException(err); resolve([]); } }); }; module.exports = { get2MinersStats, };
Verycutecat/nanolooker
<|start_filename|>lunboviewpager/src/main/java/com/xdandroid/lunboviewpager/Proxy.java<|end_filename|> package com.xdandroid.lunboviewpager; import android.support.v4.view.*; import android.view.*; import java.util.*; public class Proxy<T> { protected List<T> mList; protected long mInterval; protected Adapter mAdapter; protected SinglePictureAdapter mSinglePictureAdapter; public Proxy(List<T> list, long interval, Adapter pagerAdapter) { mList = list; mInterval = interval; mAdapter = pagerAdapter; mSinglePictureAdapter = new SinglePictureAdapter() { protected void onImageClick(View view, int position) {mAdapter.onImageClick(view, position);} protected View showImage(View inflatedLayout, int position) {return mAdapter.showImage(inflatedLayout, position);} protected int getViewPagerItemLayoutResId() {return mAdapter.getViewPagerItemLayoutResId();} }; } public void onBindView(ViewPager viewPager, CirclePageIndicator indicator) { if (mList.size() == 1) { indicator.setVisibility(View.GONE); viewPager.setAdapter(mSinglePictureAdapter); } else { indicator.setVisibility(View.VISIBLE); viewPager.setAdapter(mAdapter); viewPager.setCurrentItem(mList.size() * 500); indicator.setViewPager(viewPager, new PagerHandler(viewPager, mInterval)); } } } <|start_filename|>sample/src/main/java/com/xdandroid/sample/MainAdapter.java<|end_filename|> package com.xdandroid.sample; import android.content.*; import android.support.design.widget.*; import android.support.v4.view.*; import android.support.v7.widget.*; import android.view.*; import android.widget.*; import com.squareup.picasso.*; import com.xdandroid.lunboviewpager.Adapter; import com.xdandroid.lunboviewpager.*; import java.util.*; public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> { Context mContext; Proxy<Bean> mProxy; public MainAdapter(Context context, final List<Bean> list) { mContext = context; mProxy = new Proxy<>(list, 4000, new Adapter(context) { /** * 示例 : * ImageView imageView = (ImageView) inflatedLayout.findViewById(R.id.iv_lunbo); * Picasso.with(mContext).load(mList.get(position).imageResId).into(imageView); * return imageView; * @param inflatedLayout 根据getViewPagerItemLayoutResId指定的资源ID渲染出来的View * @param position position * @return 图片控件的对象(ImageView, DraweeView, etc..) */ protected View showImage(View inflatedLayout, int position) { ImageView imageView = (ImageView) inflatedLayout.findViewById(R.id.iv_lunbo); Picasso.with(mContext).load(list.get(position).imageResId).into(imageView); return imageView; } /** * @return ViewPager的每一页的Layout资源ID */ protected int getViewPagerItemLayoutResId() { return R.layout.item_in_viewpager; } /** * @return 总页数 */ protected int getImageCount() { return list.size(); } /** * 点击事件 * @param view inflatedLayout渲染出来的View * @param position position */ protected void onImageClick(View view, int position) { Snackbar.make(view,list.get(position).message,Snackbar.LENGTH_SHORT).show(); } }); } @Override public MainAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_in_recyclerview,parent,false)); } @Override public void onBindViewHolder(final MainAdapter.ViewHolder holder, int position) { //设置当前被选中的圆点的填充颜色 holder.indicator_lunbo.setFillColor(mContext.getResources().getColor(R.color.colorAccent)); //设置圆点半径 holder.indicator_lunbo.setRadius(UIUtils.dp2px(holder.indicator_lunbo.getContext(), 3.25f)); //设置圆点之间的距离相对于圆点半径的倍数 holder.indicator_lunbo.setDistanceBetweenCircles(3.0); mProxy.onBindView(holder.vp_lunbo,holder.indicator_lunbo); } @Override public int getItemCount() { return 1; } static final class ViewHolder extends RecyclerView.ViewHolder { ViewHolder(View itemView) { super(itemView); vp_lunbo = (ViewPager) itemView.findViewById(R.id.vp_lunbo); indicator_lunbo = (CirclePageIndicator) itemView.findViewById(R.id.indicator_lunbo); } ViewPager vp_lunbo; CirclePageIndicator indicator_lunbo; } } <|start_filename|>sample/src/main/java/com/xdandroid/sample/Bean.java<|end_filename|> package com.xdandroid.sample; import java.io.*; public class Bean implements Serializable { public Bean(String message, int imageResId) { this.message = message; this.imageResId = imageResId; } public String message; public int imageResId; } <|start_filename|>lunboviewpager/src/main/java/com/xdandroid/lunboviewpager/PagerHandler.java<|end_filename|> package com.xdandroid.lunboviewpager; import android.os.*; import android.support.v4.view.*; public class PagerHandler extends Handler { protected ViewPager mViewPager; protected int mCurrentItem; /** * 请求更新显示的View。 */ public static final int MSG_UPDATE_IMAGE = 1; /** * 请求暂停轮播。 */ public static final int MSG_KEEP_SILENT = 2; /** * 请求恢复轮播。 */ public static final int MSG_BREAK_SILENT = 3; /** * 记录最新的页号,当用户手动滑动时需要记录新页号,否则会使轮播的页面出错。 * 例如当前如果在第一页,本来准备播放的是第二页,而这时候用户滑动到了末页, * 则应该播放的是第一页,如果继续按照原来的第二页播放,则逻辑上有问题。 */ public static final int MSG_PAGE_CHANGED = 4; //轮播间隔时间 public static long MSG_DELAY = 4000; protected PagerHandler(ViewPager viewPager, long interval) { this.mViewPager = viewPager; MSG_DELAY = interval; this.mCurrentItem = (viewPager.getAdapter().getCount()) / 2; viewPager.setCurrentItem(this.mCurrentItem); } @Override public void handleMessage(Message msg) { super.handleMessage(msg); //检查消息队列并移除未发送的消息,这主要是避免在复杂环境下消息出现重复等问题。 removeCallbacksAndMessages(null); switch (msg.what) { case MSG_UPDATE_IMAGE: mCurrentItem++; mViewPager.setCurrentItem(mCurrentItem); //准备下次播放 this.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, MSG_DELAY); break; case MSG_KEEP_SILENT: //只要不发送消息就暂停了 break; case MSG_BREAK_SILENT: this.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, MSG_DELAY); break; case MSG_PAGE_CHANGED: //记录当前的页号,避免播放的时候页面显示不正确。 mCurrentItem = msg.arg1; break; default: break; } } } <|start_filename|>lunboviewpager/src/main/java/com/xdandroid/lunboviewpager/SinglePictureAdapter.java<|end_filename|> package com.xdandroid.lunboviewpager; import android.support.v4.view.*; import android.view.*; public abstract class SinglePictureAdapter extends PagerAdapter { @Override public int getCount() { return 1; } @Override public boolean isViewFromObject(View view, Object object) { return (view == object); } @Override public Object instantiateItem(ViewGroup container, final int position) { View view = LayoutInflater.from(container.getContext()).inflate(getViewPagerItemLayoutResId(), container, false); final View imageView = showImage(view, position); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onImageClick(imageView,position); } }); container.addView(view); return view; } /** * 点击事件 * @param view inflatedLayout渲染出来的View * @param position position */ protected abstract void onImageClick(View view, int position); /** * 示例 : * ImageView imageView = (ImageView) inflatedLayout.findViewById(R.id.iv_lunbo); * Picasso.with(mContext).load(mList.get(position).imageResId).into(imageView); * return imageView; * @param inflatedLayout 根据getViewPagerItemLayoutResId指定的资源ID渲染出来的View * @param position position * @return 图片控件的对象(ImageView, DraweeView, etc..) */ protected abstract View showImage(View inflatedLayout, int position); /** * @return ViewPager的每一页的Layout资源ID */ protected abstract int getViewPagerItemLayoutResId(); @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } } <|start_filename|>sample/src/main/java/com/xdandroid/sample/MainActivity.java<|end_filename|> package com.xdandroid.sample; import android.os.*; import android.support.design.widget.*; import android.support.v4.view.*; import android.support.v7.app.*; import android.support.v7.widget.*; import android.support.v7.widget.Toolbar; import android.view.*; import android.widget.*; import com.squareup.picasso.*; import com.xdandroid.lunboviewpager.Adapter; import com.xdandroid.lunboviewpager.*; import java.util.*; public class MainActivity extends AppCompatActivity { List<Bean> mList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); setupMockData(); setupViewPagerInRecyclerView(); setupViewPagerDirectlyInActivity(); } void setupMockData() { mList = new ArrayList<>(); mList.add(new Bean("小米MAX超耐久直播",R.mipmap.img1)); mList.add(new Bean("嘘——看我发现了什么",R.mipmap.img2)); mList.add(new Bean("母亲,您辛苦了",R.mipmap.img3)); mList.add(new Bean("哭过、笑过、真爱过。",R.mipmap.img4)); } void setupViewPagerInRecyclerView() { RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setAdapter(new MainAdapter(this, mList)); } void setupViewPagerDirectlyInActivity() { ViewPager vp_lunbo = (ViewPager) findViewById(R.id.vp_lunbo); CirclePageIndicator indicator_lunbo = (CirclePageIndicator) findViewById(R.id.indicator_lunbo); //设置当前被选中的圆点的填充颜色 indicator_lunbo.setFillColor(getResources().getColor(R.color.colorAccent)); //设置圆点半径 indicator_lunbo.setRadius(UIUtils.dp2px(this, 3.25f)); //设置圆点之间的距离相对于圆点半径的倍数 indicator_lunbo.setDistanceBetweenCircles(3.0); Proxy<Bean> proxy = new Proxy<>(mList, 4000, new Adapter(this) { /** * 示例 : * ImageView imageView = (ImageView) inflatedLayout.findViewById(R.id.iv_lunbo); * Picasso.with(mContext).load(mList.get(position).imageResId).into(imageView); * return imageView; * @param inflatedLayout 根据getViewPagerItemLayoutResId指定的资源ID渲染出来的View * @param position position * @return 图片控件的对象(ImageView, DraweeView, etc..) */ protected View showImage(View inflatedLayout, int position) { ImageView imageView = (ImageView) inflatedLayout.findViewById(R.id.iv_lunbo); Picasso.with(MainActivity.this).load(mList.get(position).imageResId).into(imageView); return imageView; } /** * @return ViewPager的每一页的Layout资源ID */ protected int getViewPagerItemLayoutResId() {return R.layout.item_in_viewpager;} /** * @return 总页数 */ protected int getImageCount() {return mList.size();} /** * 点击事件 * @param view inflatedLayout渲染出来的View * @param position position */ protected void onImageClick(View view, int position) {Snackbar.make(view, mList.get(position).message,Snackbar.LENGTH_SHORT).show();} }); proxy.onBindView(vp_lunbo,indicator_lunbo); } } <|start_filename|>lunboviewpager/src/main/java/com/xdandroid/lunboviewpager/Adapter.java<|end_filename|> package com.xdandroid.lunboviewpager; import android.content.*; import android.support.v4.view.*; import android.view.*; public abstract class Adapter extends PagerAdapter { protected Context mContext; protected View[] mInflatedViews = new View[20]; protected View[] mImageViews = new View[20]; public Adapter(Context context) { this.mContext = context; initImageViews(); } public void initImageViews() { for (int i = 0; i < getImageCount(); i++) { mInflatedViews[i] = LayoutInflater.from(mContext).inflate(getViewPagerItemLayoutResId(), null, false); mImageViews[i] = showImage(mInflatedViews[i], i); final int finalI = i; mImageViews[i].setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onImageClick(mImageViews[finalI], finalI); } }); } } @Override public int getCount() { return getImageCount() * 1000; } /** * 示例 : * ImageView imageView = (ImageView) inflatedLayout.findViewById(R.id.iv_lunbo); * Picasso.with(mContext).load(mList.get(position).imageResId).into(imageView); * return imageView; * @param inflatedLayout 根据getViewPagerItemLayoutResId指定的资源ID渲染出来的View * @param position position * @return 图片控件的对象(ImageView, DraweeView, etc..) */ protected abstract View showImage(View inflatedLayout, int position); /** * @return ViewPager的每一页的Layout资源ID */ protected abstract int getViewPagerItemLayoutResId(); /** * @return 总页数 */ protected abstract int getImageCount(); /** * 点击事件 * @param view inflatedLayout渲染出来的View * @param position position */ protected abstract void onImageClick(View view, int position); @Override public boolean isViewFromObject(View view, Object object) { return (view == object); } @Override public Object instantiateItem(ViewGroup container, int position) { View view = mInflatedViews[position % getImageCount()]; if (view.getParent() != null) { ((ViewGroup) (view.getParent())).removeView(view); } container.addView(view); return view; } @Override public void destroyItem(ViewGroup container, int position, Object object) {} }
xingda920813/LunboViewPager
<|start_filename|>static/main.css<|end_filename|> /* * BASIC STYLES */ *, *:after, *:before { box-sizing: border-box; } html, body { background: rgb(40, 40, 40); cursor: default; height: 100%; margin: 0; padding: 0; width: 100%; overflow: hidden; } .app { color: #FAFAFA; /* grey50 */ font-family: BlinkMacSystemFont, 'Helvetica Neue', Helvetica, sans-serif; font-size: 14px; line-height: 1.5em; } .app.is-win32 { font-family: 'Segoe UI', sans-serif; } #body { width: 100%; height: 100%; margin: 0; padding: 0; } table { table-layout: fixed; } ::-webkit-scrollbar { width: 10px; background-color: rgb(40, 40, 40); } ::-webkit-scrollbar-corner { background-color: rgb(40, 40, 40); } ::-webkit-scrollbar-thumb { border: 1px solid rgb(40, 40, 40); border-radius: 10px; background: linear-gradient(to right, rgb(90, 90, 90), rgb(80, 80, 80)) } ::-webkit-scrollbar-track { background-color: rgb(40, 40, 40); } @keyframes fadein { from { opacity: 0; } to { opacity: 1; } } .app { -webkit-user-select: none; -webkit-app-region: drag; height: 100%; display: flex; flex-flow: column; background: rgb(30, 30, 30); animation: fadein 0.5s; } .app:not(.is-focused) { background: rgb(40, 40, 40); } /* * MATERIAL ICONS */ @font-face { font-family: 'Material Icons'; font-style: normal; font-weight: 400; src: url('MaterialIcons-Regular.woff2') format('woff2'); } .icon { font-family: 'Material Icons'; font-weight: normal; font-style: normal; font-size: 24px; /* Preferred icon size */ display: inline-block; line-height: 1; text-transform: none; letter-spacing: normal; word-wrap: normal; white-space: nowrap; direction: ltr; opacity: 0.85; -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; } .icon.disabled { opacity: 0.3; } .icon:not(.disabled):hover { opacity: 1; } /* * UTILITY CLASSES */ .ellipsis { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .float-left { float: left; } .float-right { float: right; } /* * HEADER */ .header { background: rgb(40, 40, 40); border-bottom: 1px solid rgb(30, 30, 30); height: 38px; /* vertically center OS menu buttons (OS X) */ padding-top: 7px; overflow: hidden; flex: 0 1 auto; opacity: 1; position: fixed; left: 0; top: 0; right: 0; transition: opacity 0.15s ease-out; font-size: 14px; line-height: 1.5em; z-index: 1; } .app:not(.is-focused) .header { background: rgb(50, 50, 50); } .app.view-player .header { background: rgba(40, 40, 40, 0.8); border-bottom: none; } .app.view-player.is-win32 .header, .app.view-player.is-linux .header { background: none; } .app.hide-video-controls.view-player .header { opacity: 0; cursor: none; } .header .title { opacity: 0.7; position: absolute; margin-top: 1px; padding: 0 150px 0 150px; width: 100%; text-align: center; pointer-events: none; } .header .nav { font-weight: bold; } .header .nav.left { margin-left: 10px; } .header .nav.right { margin-right: 10px; } .app.is-darwin:not(.is-fullscreen) .header .nav.left { margin-left: 78px; } .header .back, .header .forward { font-size: 30px; margin-top: -3px; } /* * CONTENT */ .content { position: relative; width: 100%; overflow-x: hidden; overflow-y: overlay; flex: 1 1 auto; margin-top: 38px; } .app.view-player .content { margin-top: 0; } /* * MODAL POPOVERS */ .modal { z-index: 2; } .modal .modal-background { content: ' '; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: black; opacity: 0.5; } .modal .modal-content { position: fixed; top: 38px; left: 0; right: 0; margin: 0 auto; width: calc(100% - 20px); max-width: 600px; box-shadow: 2px 2px 10px 0px rgba(0,0,0,0.4); background-color: #eee; color: #222; padding: 20px; } .modal label { font-weight: bold; } .create-torrent { padding: 10px 25px; overflow: hidden; } .create-torrent .torrent-attribute { white-space: nowrap; margin: 8px 0; } .create-torrent .torrent-attribute>* { display: inline-block; } .create-torrent .torrent-attribute label { width: 100px; vertical-align: top; } .create-torrent .torrent-attribute>div { width: calc(100% - 100px); } .create-torrent .torrent-attribute div { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } /* * BUTTONS */ a, i { /* Links and icons */ cursor: default; -webkit-app-region: no-drag; } a:not(.disabled):hover, i:not(.disabled):hover { /* Show they're clickable without pointer: cursor */ -webkit-filter: brightness(1.3); } /* * INPUTS */ input, textarea, .control { font-size: 14px !important; } /* * TORRENT LIST */ .torrent-list { height: 100%; } .torrent { background: linear-gradient(to bottom right, #4B79A1, #283E51); background-repeat: no-repeat; background-size: cover; background-position: center; transition: -webkit-filter 0.1s ease-out; position: relative; animation: fadein 0.5s; } .torrent, .torrent-placeholder { height: 100px; } .torrent:not(:last-child) { border-bottom: 1px solid #282828; } .torrent .metadata { position: absolute; top: 20px; left: 15px; right: 15px; width: calc(100% - 30px); text-shadow: rgba(0, 0, 0, 0.5) 0 0 4px; } .torrent .metadata span:not(:last-child)::after { content: ' • '; opacity: 0.7; padding-left: 4px; padding-right: 4px; } .torrent:hover .metadata { width: calc(100% - 120px); } .torrent .torrent-controls { display: none; } .torrent:hover .torrent-controls { display: block; } .torrent .play { position: absolute; top: 23px; right: 45px; font-size: 55px; } .torrent .delete { position: absolute; top: 38px; right: 12px; } .torrent .download { vertical-align: -0.4em; margin-left: -2px; } .torrent .buttons .radial-progress { position: absolute; } .torrent .name { font-size: 20px; font-weight: bold; line-height: 1.5em; margin-bottom: 6px; } .torrent hr { position: absolute; bottom: 5px; left: calc(50% - 20px); width: 40px; height: 1px; background: #ccc; display: none; margin: 0; padding: 0; border: none; } .torrent:hover hr { display: block; } /* * TORRENT LIST: ERRORS */ .torrent-list p { margin: 10px 20px; } .torrent-list a { color: #99f; text-decoration: none; } /* * TORRENT LIST: DRAG-DROP TARGET */ .torrent-placeholder { padding: 10px; font-size: 1.1em; } .torrent-placeholder span { border: 5px #444 dashed; border-radius: 5px; color: #666; height: 100%; display: flex; align-items: center; justify-content: center; } body.drag .torrent-placeholder span { border-color: #def; color: #def; } body.drag .app::after { content: ' '; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); z-index: 3; } /* * TORRENT LIST: EXPANDED TORRENT DETAILS */ .torrent.selected { height: auto; } .torrent-details { padding: 8em 0 20px 0; } .torrent-details .warning { padding-left: 15px; } .torrent-details table { width: 100%; white-space: nowrap; border: none; border-spacing: 0; } .torrent-details tr { height: 28px; } .torrent-details td { overflow: hidden; padding: 0; vertical-align: middle; } .torrent-details td .icon { font-size: 18px; position: relative; top: 3px; } .torrent-details td.col-icon { width: 45px; padding-left: 16px; } .torrent-details td.col-icon .radial-progress { position: absolute; margin-top: 4px; margin-left: 0.5px; } .torrent-details td.col-name { width: auto; text-overflow: ellipsis; } .torrent-details td.col-progress { width: 60px; text-align: right; } .torrent-details td.col-size { width: 60px; text-align: right; } .torrent-details td.col-select { width: 45px; padding-right: 13px; text-align: right; } /* * PLAYER */ .player { position: absolute; width: 100%; height: 100%; background-color: #000; } .player .letterbox { width: 100%; height: 100%; display: flex; background-size: cover; background-position: center; } .player video { display: block; width: 100%; } .player .name { font-size: 20px; font-weight: bold; line-height: 1.5em; margin-bottom: 6px; } /* * PLAYER CONTROLS */ .player .controls { position: fixed; background: rgba(40, 40, 40, 0.8); width: 100%; height: 38px; bottom: 0; transition: opacity 0.15s ease-out; } .player .controls .icon { display: block; margin: 8px; font-size: 22px; opacity: 0.85; /* Make all icons have uniform spacing */ max-width: 23px; overflow: hidden; } .player .controls .icon:hover { opacity: 1; } .player .controls .icon.disabled { opacity: 0.3; } .player .controls .icon.skip-previous, .player .controls .icon.play-pause, .player .controls .icon.skip-next { font-size: 28px; margin: 5px; } .player .controls .volume-slider { -webkit-appearance: none; -webkit-app-region: no-drag; width: 60px; height: 3px; margin: 18px 8px 8px 0; border: none; padding: 0; opacity: 0.85; vertical-align: sub; } .player .controls .time, .player .controls .rate { font-weight: 100; font-size: 13px; margin: 9px 8px 8px 8px; opacity: 0.8; font-variant-numeric: tabular-nums; } .player .controls .icon.closed-caption { font-size: 26px; margin-top: 6px; } .player .controls .icon.multi-audio { font-size: 26px; margin-top: 6px; } .player .controls .icon.fullscreen { font-size: 26px; margin-right: 15px; margin-top: 6px; } .app.hide-video-controls .player .controls { opacity: 0; } .app.hide-video-controls .player { cursor: none; } /* invisible click target for scrubbing */ .player .controls .scrub-bar { position: absolute; width: 100%; height: 23px; /* 3px .loading-bar plus 10px above and below */ top: -10px; left: 0; -webkit-app-region: no-drag; } .player .controls .loading-bar { position: relative; width: 100%; top: -3px; height: 3px; background-color: rgba(0, 0, 0, 0.3); transition: all 0.1s ease-out; position: absolute; } .player .controls .loading-bar-part { position: absolute; background-color: #dd0000; top: 0; height: 100%; } .player .controls .playback-cursor { position: absolute; top: -3px; background-color: #FFF; width: 3px; height: 3px; border-radius: 50%; margin-top: 0; margin-left: 0; transition-property: width, height, top, margin-left; transition-duration: 0.1s; transition-timing-function: ease-out; } .player .controls .closed-caption.active, .player .controls .device.active { color: #9af; } .player .controls .volume-slider::-webkit-slider-thumb { -webkit-appearance: none; -webkit-app-region: no-drag; background-color: #fff; width: 13px; height: 13px; border-radius: 50%; } .player .controls .volume-slider:focus { outline: none; } .player .playback-bar:hover .loading-bar { height: 5px; } .player .playback-bar:hover .playback-cursor { top: -8px; margin-left: -5px; width: 14px; height: 14px; } .player .controls .options-list { position: fixed; background: rgba(40, 40, 40, 0.8); min-width: 100px; bottom: 45px; right: 3px; transition: opacity 0.15s ease-out; padding: 5px 10px; border-radius: 3px; margin: 0; list-style-type: none; color: rgba(255, 255, 255, 0.8); } .player .controls .options-list .icon { display: inline; font-size: 17px; vertical-align: bottom; line-height: 21px; margin: 4px; } /** * Set the cue text position so it appears above the player controls. */ video::-webkit-media-text-track-container { bottom: 60px; transition: bottom 0.1s ease-out; } .app.hide-video-controls video::-webkit-media-text-track-container { bottom: 30px; } ::cue { background: none; color: #FFF; text-shadow: #000 -1px 0 1px, #000 1px 0 1px, #000 0 -1px 1px, #000 0 1px 1px, rgba(50, 50, 50, 0.5) 2px 2px 0; } /* * CHROMECAST / AIRPLAY CONTROLS */ .cast-screen { width: 100%; height: 200px; color: #eee; text-align: center; line-height: 2; align-self: center; } .cast-screen .icon { font-size: 50px; } .cast-screen .cast-type, .cast-screen .cast-status { font-size: 32px; } .cast-screen .cast-type { font-weight: bold; } /* * MEDIA OVERLAY / AUDIO DETAILS */ .media-overlay-background { position: fixed; top: 0; left: 0; width: 100%; height: 100%; display: flex; background-size: cover; background-position: center center; } .media-overlay { max-width: calc(100% - 80px); white-space: nowrap; text-overflow: ellipsis; align-self: center; margin: 0 auto; font-weight: bold; font-size: 24px; line-height: 2; } .media-stalled .loading-spinner { width: 40px; height: 40px; margin: 40px auto; border-top: 6px solid rgba(255, 255, 255, 0.2); border-right: 6px solid rgba(255, 255, 255, 0.2); border-bottom: 6px solid rgba(255, 255, 255, 0.2); border-left: 6px solid #ffffff; border-radius: 50%; color: transparent; animation: spinning 1.1s infinite linear; } @keyframes spinning { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } .media-stalled .loading-status { font-size: 18px; font-weight: normal; text-align: center; } .audio-metadata div { overflow: hidden; text-overflow: ellipsis; } .audio-metadata .audio-title { font-size: 32px; } .audio-metadata label { display:inline-block; width: 120px; text-align: right; font-weight: normal; margin-right: 25px; } .audio-metadata .audio-format, .audio-metadata .audio-comments { font-weight: normal; } /* * ERRORS */ .error-popover { position: fixed; top: 36px; margin: 0; width: 100%; overflow: hidden; z-index: 1; } .error-popover.hidden { display: none; } .error-popover .error, .error-popover .title { padding: 10px; background-color: rgba(0, 0, 0, 0.8); border-bottom: 1px solid #444; } .error-popover .title { font-weight: bold; color: #c44; } .error-popover .error { color: #bbb; } .error-popover .error:last-child { border-bottom: none; } .error-text { color: #c44; } /* * RADIAL PROGRESS BAR */ .radial-progress { width: 16px; height: 16px; border-radius: 50%; background-color: #888; } .radial-progress .circle .mask, .radial-progress .circle .fill { width: 16px; height: 16px; position: absolute; border-radius: 50%; -webkit-backface-visibility: hidden; } .radial-progress .circle .mask { clip: rect(0px, 16px, 16px, 8px); } .radial-progress .circle .fill { clip: rect(0px, 8px, 16px, 0px); background-color: white; } .radial-progress .inset { position: absolute; width: 12px; height: 12px; margin: 2px 0 0 2px; border-radius: 50%; background-color: black; } .radial-progress-large { width: 40px; height: 40px; } .radial-progress-large .circle .mask, .radial-progress-large .circle .fill { width: 40px; height: 40px; } .radial-progress-large .circle .mask { clip: rect(0px, 40px, 40px, 20px); } .radial-progress-large .circle .fill { clip: rect(0px, 20px, 40px, 0px); background-color: white; } .radial-progress-large .inset { width: 32px; height: 32px; margin: 4px 0 0 4px; } /** * Use this class on Material UI components to get correct native app behavior: * * - Dragging the button should NOT drag the entire app window * - The cursor should be default, not a pointer (hand) like on the web */ .control { -webkit-app-region: no-drag; cursor: default !important; } .control * { cursor: default !important; }
suryatmodulus/webtorrent-desktop
<|start_filename|>build.cmd<|end_filename|> call "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.cmd" FOR /F %%i IN ('git mkver next') DO set VERSION=%%i call sbt assembly cd target\scala-2.12 call native-image -jar git-mkver-assembly-%VERSION%.jar --no-fallback del git-mkver.exe move git-mkver-assembly-%VERSION%.exe git-mkver.exe PowerShell -Command "Compress-Archive -Path 'git-mkver.exe' -DestinationPath 'git-mkver-windows-amd64-%VERSION%.zip'" PowerShell -Command "Get-FileHash git-mkver-windows-amd64-%VERSION%.zip | %% Hash" cd ..\..\
ExitoLab/git-mkver
<|start_filename|>src/main/java/com/github/signalr4j/client/InvalidStateException.java<|end_filename|> /* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved See License.txt in the project root for license information. */ package com.github.signalr4j.client; /** * Exception to indicate that an operation is not allowed with the connection in * a specific state */ public class InvalidStateException extends RuntimeException { private static final long serialVersionUID = 2754012197945989794L; public InvalidStateException(ConnectionState connectionState) { super("The operation is not allowed in the '" + connectionState.toString() + "' state"); } } <|start_filename|>src/main/java/com/github/signalr4j/client/MessageResult.java<|end_filename|> /* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved See License.txt in the project root for license information. */ package com.github.signalr4j.client; public class MessageResult { private boolean mDisconnect = false; private boolean mReconnect = false; private boolean mInitialize = false; public boolean disconnect() { return mDisconnect; } public void setDisconnect(boolean disconnect) { mDisconnect = disconnect; } public boolean reconnect() { return mReconnect; } public void setReconnect(boolean reconnect) { mReconnect = reconnect; } public boolean initialize() { return mInitialize; } public void setInitialize(boolean initialize) { mInitialize = initialize; } } <|start_filename|>src/main/java/com/github/signalr4j/client/transport/NegotiationException.java<|end_filename|> /* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved See License.txt in the project root for license information. */ package com.github.signalr4j.client.transport; public class NegotiationException extends Exception { public NegotiationException(String detailMessage, Throwable throwable) { super(detailMessage, throwable); } private static final long serialVersionUID = 5861305478561443777L; } <|start_filename|>src/main/java/com/github/signalr4j/client/UpdateableCancellableFuture.java<|end_filename|> /* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved See License.txt in the project root for license information. */ package com.github.signalr4j.client; /** * An updateable SignalRFuture that, when cancelled, triggers cancellation on an * internal instance */ public class UpdateableCancellableFuture<V> extends SignalRFuture<V> { SignalRFuture<?> mFuture = null; Object mSync = new Object(); public UpdateableCancellableFuture(SignalRFuture<?> token) { mFuture = token; } public void setFuture(SignalRFuture<?> token) { synchronized (mSync) { mFuture = token; } if (isCancelled()) { if (mFuture != null) { mFuture.cancel(); } } } @Override public void cancel() { synchronized (mSync) { super.cancel(); if (mFuture != null) { mFuture.cancel(); mFuture = null; } } } } <|start_filename|>src/main/java/com/github/signalr4j/client/http/InvalidHttpStatusCodeException.java<|end_filename|> /* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved See License.txt in the project root for license information. */ package com.github.signalr4j.client.http; /** * Exception thrown when an invalid HTTP Status code is received */ public class InvalidHttpStatusCodeException extends Exception { private static final long serialVersionUID = 7073157073424850921L; public InvalidHttpStatusCodeException(int statusCode, String responseContent, String responseHeaders) { super("Invalid status code: " + statusCode + "\nResponse: " + responseContent + "\nHeaders: " + responseHeaders); } } <|start_filename|>src/main/java/com/github/signalr4j/client/Credentials.java<|end_filename|> /* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved See License.txt in the project root for license information. */ package com.github.signalr4j.client; import com.github.signalr4j.client.http.Request; /** * Interface for credentials to be sent in a request */ public interface Credentials { /** * Adds the credentials to the request * * @param request * The request to prepare */ public void prepareRequest(Request request); } <|start_filename|>src/test/java/com/github/signalr4j/client/test/integration/java/Program.java<|end_filename|> /* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved See License.txt in the project root for license information. */ package com.github.signalr4j.client.test.integration.java; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import com.github.signalr4j.client.test.integration.ApplicationContext; import com.github.signalr4j.client.test.integration.framework.TestExecutionCallback; import com.github.signalr4j.client.test.integration.framework.TestGroup; import com.github.signalr4j.client.test.integration.framework.TestResult; import com.github.signalr4j.client.test.integration.framework.TestCase; import com.github.signalr4j.client.test.integration.tests.MiscTests; public class Program { /** * @param args */ public static void main(String[] args) { if (args.length != 1) { System.err.println("There must be one argument with the server url."); return; } String serverUrl = args[0]; JavaTestPlatformContext testPlatformContext = new JavaTestPlatformContext(serverUrl); testPlatformContext.setLoggingEnabled(false); ApplicationContext.setTestPlatformContext(testPlatformContext); List<TestGroup> testGroups = new ArrayList<TestGroup>(); testGroups.add(new MiscTests()); List<TestCase> tests = new ArrayList<TestCase>(); for (TestGroup group : testGroups) { for (TestCase test : group.getTestCases()) { tests.add(test); } } final Scanner scanner = new Scanner (System.in); String option = ""; while (!option.equals("q")) { System.out.println("Type a test number to execute the test. 'q' to quit:"); for (int i = 0; i < tests.size(); i++) { System.out.println(i + ". " + tests.get(i).getName()); } option = scanner.next(); if (!option.equals("q")) { int index = -1; try { index = Integer.decode(option); } catch (NumberFormatException ex) { } if (index > -1 && index < tests.size()) { TestCase test = tests.get(index); test.run(new TestExecutionCallback() { @Override public void onTestStart(TestCase test) { System.out.println("Starting test - " + test.getName()); } @Override public void onTestGroupComplete(TestGroup group, List<TestResult> results) { } @Override public void onTestComplete(TestCase test, TestResult result) { String extraData = ""; if (result.getException() != null) { extraData = " - " + result.getException().toString(); } System.out.println("Test completed - " + test.getName() + " - " + result.getStatus() + extraData); System.out.println("Press any key to continue..."); scanner.next(); } }); } } } } } <|start_filename|>src/test/java/com/github/signalr4j/client/tests/mocktransport/HttpClientTransportTests.java<|end_filename|> /* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved See License.txt in the project root for license information. */ package com.github.signalr4j.client.tests.mocktransport; import static org.junit.Assert.*; import org.junit.Ignore; import org.junit.Test; import java.util.UUID; import com.github.signalr4j.client.Action; import com.github.signalr4j.client.ErrorCallback; import com.github.signalr4j.client.Connection; import com.github.signalr4j.client.SignalRFuture; import com.github.signalr4j.client.tests.util.MockHttpConnection; import com.github.signalr4j.client.tests.util.MockConnection; import com.github.signalr4j.client.tests.util.MultiResult; import com.github.signalr4j.client.tests.util.Sync; import com.github.signalr4j.client.tests.util.TransportType; import com.github.signalr4j.client.tests.util.Utils; import com.github.signalr4j.client.transport.ClientTransport; import com.github.signalr4j.client.transport.DataResultCallback; import com.github.signalr4j.client.transport.NegotiationResponse; public abstract class HttpClientTransportTests { protected abstract TransportType getTransportType(); @Test public void testNegotiate() throws Exception { final MockHttpConnection httpConnection = new MockHttpConnection(); ClientTransport transport = Utils.createTransport(getTransportType(), httpConnection); Connection connection = new Connection("http://myUrl.com/"); SignalRFuture<NegotiationResponse> future = transport.negotiate(connection); NegotiationResponse negotiation = Utils.getDefaultNegotiationResponse(); String negotiationContent = Utils.getNegotiationResponseContent(negotiation); MockHttpConnection.RequestEntry entry = httpConnection.getRequest(); entry.response.writeLine(negotiationContent); Utils.finishMessage(entry); NegotiationResponse negotiationResponse = null; negotiationResponse = future.get(); assertEquals(negotiation.getConnectionId(), negotiationResponse.getConnectionId()); assertEquals(negotiation.getConnectionToken(), negotiationResponse.getConnectionToken()); assertEquals(negotiation.getProtocolVersion(), negotiationResponse.getProtocolVersion()); } protected void testSend() throws Exception { final MockHttpConnection httpConnection = new MockHttpConnection(); ClientTransport transport = Utils.createTransport(getTransportType(), httpConnection); MockConnection connection = new MockConnection(); String dataToSend = UUID.randomUUID().toString(); final MultiResult result = new MultiResult(); final String dataLock = "dataLock" + getTransportType().toString(); SignalRFuture<Void> send = transport.send(connection, dataToSend, new DataResultCallback() { @Override public void onData(String receivedData) { result.stringResult = receivedData.trim(); Sync.complete(dataLock); } }); MockHttpConnection.RequestEntry entry = httpConnection.getRequest(); entry.response.writeLine(entry.request.getContent()); Utils.finishMessage(entry); String sendUrl = connection.getUrl() + "send?transport=" + transport.getName() + "&connectionToken=" + Utils.encode(connection.getConnectionToken()) + "&connectionId=" + Utils.encode(connection.getConnectionId()) + "&connectionData=" + Utils.encode(connection.getConnectionData()) + "&" + connection.getQueryString(); Sync.waitComplete(dataLock); assertEquals(sendUrl, entry.request.getUrl()); assertEquals("data=" + dataToSend + "&", entry.request.getContent()); assertEquals("data=" + dataToSend + "&", result.stringResult); assertTrue(send.isDone()); } @Test public void testAbort() throws Exception { final MockHttpConnection httpConnection = new MockHttpConnection(); ClientTransport transport = Utils.createTransport(getTransportType(), httpConnection); MockConnection connection = new MockConnection(); final String connectLock = "connectLock" + getTransportType().toString(); SignalRFuture<Void> abort = transport.abort(connection); abort.done(new Action<Void>() { @Override public void run(Void obj) throws Exception { Sync.complete(connectLock); } }); MockHttpConnection.RequestEntry entry = httpConnection.getRequest(); entry.response.writeLine(entry.request.getContent()); Utils.finishMessage(entry); String abortUrl = connection.getUrl() + "abort?transport=" + transport.getName() + "&connectionToken=" + Utils.encode(connection.getConnectionToken()) + "&connectionId=" + Utils.encode(connection.getConnectionId()) + "&connectionData=" + Utils.encode(connection.getConnectionData()) + "&" + connection.getQueryString(); Sync.waitComplete(connectLock); assertEquals(abortUrl, entry.request.getUrl()); assertTrue(abort.isDone()); } @Test @Ignore public void testInvalidNegotiationData() throws Exception { final MockHttpConnection httpConnection = new MockHttpConnection(); ClientTransport transport = Utils.createTransport(getTransportType(), httpConnection); Connection connection = new Connection("http://myUrl.com/"); SignalRFuture<NegotiationResponse> future = transport.negotiate(connection); final MultiResult result = new MultiResult(); result.booleanResult = false; future.onError(new ErrorCallback() { @Override public void onError(Throwable error) { result.booleanResult = true; Sync.complete("invalidNegotiationData"); } }); future.done(new Action<NegotiationResponse>() { @Override public void run(NegotiationResponse obj) throws Exception { Sync.complete("invalidNegotiationData"); } }); String invalidNegotiationContent = "bad-data-123"; MockHttpConnection.RequestEntry entry = httpConnection.getRequest(); entry.response.writeLine(invalidNegotiationContent); Utils.finishMessage(entry); Sync.waitComplete("invalidNegotiationData"); assertTrue(result.booleanResult); } @Test @Ignore public void testInvalidNegotiationJsonData() throws Exception { final MockHttpConnection httpConnection = new MockHttpConnection(); ClientTransport transport = Utils.createTransport(getTransportType(), httpConnection); Connection connection = new Connection("http://myUrl.com/"); SignalRFuture<NegotiationResponse> future = transport.negotiate(connection); final MultiResult result = new MultiResult(); result.booleanResult = false; future.onError(new ErrorCallback() { @Override public void onError(Throwable error) { result.booleanResult = true; Sync.complete("invalidNegotiationData"); } }); future.done(new Action<NegotiationResponse>() { @Override public void run(NegotiationResponse obj) throws Exception { Sync.complete("invalidNegotiationData"); } }); String invalidNegotiationContent = "{\"myValue\":\"bad-data-123\"}"; MockHttpConnection.RequestEntry entry = httpConnection.getRequest(); entry.response.writeLine(invalidNegotiationContent); Utils.finishMessage(entry); Sync.waitComplete("invalidNegotiationData"); assertTrue(result.booleanResult); } } <|start_filename|>src/main/java/com/github/signalr4j/client/InvalidProtocolVersionException.java<|end_filename|> /* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved See License.txt in the project root for license information. */ package com.github.signalr4j.client; /** * Exception to indicate that the protocol version is different than expected */ public class InvalidProtocolVersionException extends Exception { private static final long serialVersionUID = -1655367340327068570L; public InvalidProtocolVersionException(String version) { super("Invalid protocol version " + version); } } <|start_filename|>src/main/java/com/github/signalr4j/client/Logger.java<|end_filename|> /* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved See License.txt in the project root for license information. */ package com.github.signalr4j.client; /** * Interface to define a Logger */ public interface Logger { /** * Logs a message * * @param message * Message to log * @param level * Message level */ public void log(String message, LogLevel level); } <|start_filename|>src/main/java/com/github/signalr4j/client/ErrorCallback.java<|end_filename|> /* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved See License.txt in the project root for license information. */ package com.github.signalr4j.client; public interface ErrorCallback { /** * Callback invoked when an error is found * * @param error * The error */ public void onError(Throwable error); } <|start_filename|>src/test/java/com/github/signalr4j/client/tests/util/MockClientTransport.java<|end_filename|> /* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved See License.txt in the project root for license information. */ package com.github.signalr4j.client.tests.util; import com.github.signalr4j.client.ConnectionBase; import com.github.signalr4j.client.SignalRFuture; import com.github.signalr4j.client.transport.ClientTransport; import com.github.signalr4j.client.transport.ConnectionType; import com.github.signalr4j.client.transport.DataResultCallback; import com.github.signalr4j.client.transport.NegotiationResponse; public class MockClientTransport implements ClientTransport { private boolean mSupportKeepAlive = false; private int mAbortInvocations = 0; public SignalRFuture<NegotiationResponse> negotiationFuture; public TransportOperation startOperation; public TransportOperation sendOperation; public SignalRFuture<Void> abortFuture; public void setSupportKeepAlive(boolean support) { mSupportKeepAlive = support; } @Override public String getName() { return "mock"; } @Override public boolean supportKeepAlive() { return mSupportKeepAlive; } @Override public SignalRFuture<NegotiationResponse> negotiate(ConnectionBase connection) { negotiationFuture = new SignalRFuture<NegotiationResponse>(); return negotiationFuture; } @Override public SignalRFuture<Void> start(ConnectionBase connection, ConnectionType connectionType, DataResultCallback callback) { startOperation = new TransportOperation(); startOperation.future = new SignalRFuture<Void>(); startOperation.callback = callback; return startOperation.future; } @Override public SignalRFuture<Void> send(ConnectionBase connection, String data, DataResultCallback callback) { sendOperation = new TransportOperation(); sendOperation.future = new SignalRFuture<Void>(); sendOperation.callback = callback; sendOperation.data = data; return sendOperation.future; } @Override public SignalRFuture<Void> abort(ConnectionBase connection) { mAbortInvocations++; abortFuture = new SignalRFuture<Void>(); return abortFuture; } public int getAbortInvocations() { return mAbortInvocations; } public class TransportOperation { public SignalRFuture<Void> future; public DataResultCallback callback; public Object data; } } <|start_filename|>src/test/java/com/github/signalr4j/client/test/integration/TestPlatformContext.java<|end_filename|> /* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved See License.txt in the project root for license information. */ package com.github.signalr4j.client.test.integration; import java.util.concurrent.Future; import com.github.signalr4j.client.test.integration.framework.TestCase; import com.github.signalr4j.client.test.integration.framework.TestExecutionCallback; import com.github.signalr4j.client.Logger; public interface TestPlatformContext { Logger getLogger(); String getServerUrl(); String getLogPostUrl(); Future<Void> showMessage(String message); void executeTest(TestCase testCase, TestExecutionCallback callback); void sleep(int seconds) throws Exception; } <|start_filename|>src/main/java/com/github/signalr4j/client/http/HttpConnection.java<|end_filename|> /* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved See License.txt in the project root for license information. */ package com.github.signalr4j.client.http; /** * Interface that defines a generic HttpConnection */ public interface HttpConnection { /** * Executes an request * * @param request * The request to execute * @param responseCallback * The callback to invoke when the response is returned * @return A Future for the operation */ public HttpConnectionFuture execute(final Request request, HttpConnectionFuture.ResponseCallback responseCallback); } <|start_filename|>src/test/java/com/github/signalr4j/client/tests/util/TransportType.java<|end_filename|> /* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved See License.txt in the project root for license information. */ package com.github.signalr4j.client.tests.util; public enum TransportType { ServerSentEvents, LongPolling } <|start_filename|>src/test/java/com/github/signalr4j/client/tests/realtransport/TestData.java<|end_filename|> /* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved See License.txt in the project root for license information. */ package com.github.signalr4j.client.tests.realtransport; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import com.github.signalr4j.client.Logger; import com.github.signalr4j.client.tests.util.ConsoleLogger; public class TestData { public static final String SERVER_ADDRESS = "10.0.0.133/signalrtestserver"; public static final String SERVER_URL = "http://" + SERVER_ADDRESS + "/testendpoint"; public static final String HUB_URL = "http://" + SERVER_ADDRESS + "/signalr"; public static final String CONNECTION_QUERYSTRING = "myVal=1"; public static final String HUB_NAME = "TestHub"; public static Logger getLogger() { return new ConsoleLogger(); } public static void triggerTestMessage() throws Exception { invokeServerAction("TriggerTestMessage"); } public static String getLastSentData() throws Exception { return invokeServerAction("LastSentData"); } public static String invokeServerAction(String action) throws Exception { URL url = new URL("http://" + TestData.SERVER_ADDRESS + "/home/" + action); URLConnection connection = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuilder sb = new StringBuilder(); while ((inputLine = in.readLine()) != null) { sb.append(inputLine); sb.append("\n"); } in.close(); return sb.toString().trim(); } public static String getLastHubData() throws Exception { return invokeServerAction("LastHubData"); } public static void triggerHubTestMessage() throws Exception { invokeServerAction("TriggerHubTestMessage"); } } <|start_filename|>src/test/java/com/github/signalr4j/client/test/integration/framework/TestResult.java<|end_filename|> /* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved See License.txt in the project root for license information. */ package com.github.signalr4j.client.test.integration.framework; public class TestResult { private TestStatus mStatus; private Exception mException; private TestCase mTestCase; public TestStatus getStatus() { return mStatus; } public void setStatus(TestStatus status) { this.mStatus = status; } public Exception getException() { return mException; } public void setException(Exception e) { this.mException = e; } public TestCase getTestCase() { return mTestCase; } public void setTestCase(TestCase testCase) { mTestCase = testCase; } } <|start_filename|>src/test/java/com/github/signalr4j/client/test/integration/framework/TestStatus.java<|end_filename|> /* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved See License.txt in the project root for license information. */ package com.github.signalr4j.client.test.integration.framework; public enum TestStatus { NotRun, Running, Failed, Passed } <|start_filename|>src/main/java/com/github/signalr4j/client/StateChangedCallback.java<|end_filename|> /* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved See License.txt in the project root for license information. */ package com.github.signalr4j.client; /** * Callback invoked when a connection changes its state */ public interface StateChangedCallback { public void stateChanged(ConnectionState oldState, ConnectionState newState); } <|start_filename|>src/test/java/com/github/signalr4j/client/test/integration/TransportType.java<|end_filename|> /* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved See License.txt in the project root for license information. */ package com.github.signalr4j.client.test.integration; public enum TransportType { ServerSentEvents, LongPolling, Auto } <|start_filename|>src/test/java/com/github/signalr4j/client/tests/realtransport/HttpClientTransportTests.java<|end_filename|> /* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved See License.txt in the project root for license information. */ package com.github.signalr4j.client.tests.realtransport; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.UUID; import com.github.signalr4j.client.tests.util.TransportType; import com.github.signalr4j.client.tests.util.Utils; import com.github.signalr4j.client.Connection; import com.github.signalr4j.client.Platform; import com.github.signalr4j.client.SignalRFuture; import com.github.signalr4j.client.tests.util.ConsoleLogger; import com.github.signalr4j.client.transport.ClientTransport; import com.github.signalr4j.client.transport.DataResultCallback; import com.github.signalr4j.client.transport.NegotiationResponse; import org.junit.Ignore; import org.junit.Test; @Ignore public abstract class HttpClientTransportTests { protected abstract TransportType getTransportType(); @Test @Ignore public void testNegotiate() throws Exception { ClientTransport transport = Utils.createTransport(getTransportType(), Platform.createHttpConnection(new ConsoleLogger())); Connection connection = new Connection(TestData.SERVER_URL, TestData.CONNECTION_QUERYSTRING, TestData.getLogger()); SignalRFuture<NegotiationResponse> future = transport.negotiate(connection); NegotiationResponse negotiationResponse = future.get(); assertNotNull(negotiationResponse); assertNotNull(negotiationResponse.getConnectionId()); assertNotNull(negotiationResponse.getConnectionToken()); assertNotNull(negotiationResponse.getDisconnectTimeout()); assertNotNull(negotiationResponse.getKeepAliveTimeout()); assertEquals("1.3", negotiationResponse.getProtocolVersion()); assertNotNull(negotiationResponse.getUrl()); } @Test @Ignore public void testSend() throws Exception { ClientTransport transport = Utils.createTransport(getTransportType(), Platform.createHttpConnection(new ConsoleLogger())); Connection connection = new Connection(TestData.SERVER_URL, TestData.CONNECTION_QUERYSTRING, TestData.getLogger()); connection.start(transport).get(); String dataToSend = UUID.randomUUID().toString(); transport.send(connection, dataToSend, new DataResultCallback() { @Override public void onData(String data) { // TODO Auto-generated method stub } }).get(); String lastSentData = TestData.getLastSentData(); assertEquals(dataToSend, lastSentData); } } <|start_filename|>src/main/java/com/github/signalr4j/client/NullLogger.java<|end_filename|> /* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved See License.txt in the project root for license information. */ package com.github.signalr4j.client; /** * Null logger implementation */ public class NullLogger implements Logger { @Override public void log(String message, LogLevel level) { } } <|start_filename|>src/test/java/com/github/signalr4j/client/test/integration/framework/TestExecutionCallback.java<|end_filename|> /* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved See License.txt in the project root for license information. */ package com.github.signalr4j.client.test.integration.framework; import java.util.List; public interface TestExecutionCallback { public void onTestStart(TestCase test); public void onTestComplete(TestCase test, TestResult result); public void onTestGroupComplete(TestGroup group, List<TestResult> results); } <|start_filename|>src/test/java/com/github/signalr4j/client/tests/realtransport/LongPollingTransportTests.java<|end_filename|> /* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved See License.txt in the project root for license information. */ package com.github.signalr4j.client.tests.realtransport; import com.github.signalr4j.client.tests.util.Sync; import com.github.signalr4j.client.tests.util.TransportType; import org.junit.Before; public class LongPollingTransportTests extends HttpClientTransportTests { @Before public void setUp() { Sync.reset(); } @Override protected TransportType getTransportType() { return TransportType.LongPolling; } } <|start_filename|>src/test/java/com/github/signalr4j/client/tests/util/MockHttpConnection.java<|end_filename|> /* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved See License.txt in the project root for license information. */ package com.github.signalr4j.client.tests.util; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Semaphore; import com.github.signalr4j.client.http.HttpConnection; import com.github.signalr4j.client.http.HttpConnectionFuture; import com.github.signalr4j.client.http.HttpConnectionFuture.ResponseCallback; import com.github.signalr4j.client.http.Request; public class MockHttpConnection implements HttpConnection { Semaphore mSemaphore = new Semaphore(0); Queue<RequestEntry> mRequests = new ConcurrentLinkedQueue<RequestEntry>(); List<Thread> mThreads = new ArrayList<Thread>(); @Override public HttpConnectionFuture execute(Request request, ResponseCallback responseCallback) { RequestEntry entry = new RequestEntry(); entry.request = request; entry.callback = responseCallback; entry.future = new HttpConnectionFuture(); entry.response = new MockResponse(200); mRequests.add(entry); mSemaphore.release(); return entry.future; } public class RequestEntry { public Request request; public ResponseCallback callback; public HttpConnectionFuture future; public MockResponse response; private boolean mResponseTriggered = false; private Object mSync = new Object(); public void finishRequest() { Thread t = new Thread(new Runnable() { @Override public void run() { response.finishWriting(); future.setResult(null); } }); mThreads.add(t); t.start(); } public void triggerResponse() { synchronized (mSync) { if (!mResponseTriggered) { mResponseTriggered = true; Thread t = new Thread(new Runnable() { @Override public void run() { try { callback.onResponse(response); } catch (Exception e) { } } }); mThreads.add(t); t.start(); } } } } public RequestEntry getRequest() throws InterruptedException { mSemaphore.acquire(); return mRequests.poll(); } } <|start_filename|>src/test/java/com/github/signalr4j/client/tests/util/ConsoleLogger.java<|end_filename|> /* Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved See License.txt in the project root for license information. */ package com.github.signalr4j.client.tests.util; import com.github.signalr4j.client.LogLevel; import com.github.signalr4j.client.Logger; public class ConsoleLogger implements Logger { @Override public void log(String message, LogLevel level) { System.out.println(level.toString() + " - " + message); } }
RaceTelemetry/signalr4j
<|start_filename|>plugins/grav-headless-plugin/package-lock.json<|end_filename|> { "name": "grav-headless-plugin", "version": "1.0.0", "lockfileVersion": 1, "requires": true, "dependencies": { "axios": { "version": "0.17.1", "resolved": "https://registry.npmjs.org/axios/-/axios-0.17.1.tgz", "integrity": "sha1-LY4+XQvb1zJ/kbyBT1xXZg+Bgk0=", "requires": { "follow-redirects": "1.4.0", "is-buffer": "1.1.6" } }, "debug": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", "integrity": "<KEY> "requires": { "ms": "2.0.0" } }, "follow-redirects": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.4.0.tgz", "integrity": "<KEY> "requires": { "debug": "3.1.0" } }, "gatsby-node-helpers": { "version": "0.1.3", "resolved": "https://registry.npmjs.org/gatsby-node-helpers/-/gatsby-node-helpers-0.1.3.tgz", "integrity": "sha1-VqqnjEc3m78HbuReh13GzIMVBq0=", "requires": { "json-stringify-safe": "5.0.1", "lodash": "4.17.4" } }, "is-buffer": { "version": "1.1.6", "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==" }, "json-stringify-safe": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=" }, "lodash": { "version": "4.17.4", "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.4.tgz", "integrity": "sha1-eCA6TRwyiuHYbcpkYONptX9AVa4=" }, "ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" }, "slug": { "version": "0.9.1", "resolved": "https://registry.npmjs.org/slug/-/slug-0.9.1.tgz", "integrity": "sha1-rwj2CKfBFRa2F3iqgA3OhMUYz9o=", "requires": { "unicode": "10.0.0" } }, "unicode": { "version": "10.0.0", "resolved": "https://registry.npmjs.org/unicode/-/unicode-10.0.0.tgz", "integrity": "sha1-5dUcH<KEY>=" } } } <|start_filename|>plugins/grav-headless-plugin/package.json<|end_filename|> { "name": "grav-headless-plugin", "version": "1.0.0", "description": "Sample plugin that generates Gatsby nodes from an API provided by Grav", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Snipcart", "license": "ISC", "dependencies": { "axios": "^0.17.1", "gatsby-node-helpers": "^0.1.3", "slug": "^0.9.1" } }
spences10/gatsby-netlify
<|start_filename|>微信小程序/app.json<|end_filename|> { "pages": [ "pages/index/index", "pages/hybrid-page/hybrid" ], "window": { "backgroundTextStyle": "light", "navigationBarBackgroundColor": "#333333", "backgroundColorTop": "#333333", "backgroundColorBottom": "#333333", "navigationBarTitleText": "Hybrid", "navigationBarTextStyle": "white" } } <|start_filename|>微信小程序/pages/hybrid-lib/handler.js<|end_filename|> var apis = {}; /** * @callback APIAction 业务指令的执行动作 * @param {Object} [params] 由H5提供过来的参数集合 * @param {Function} [callback] 小程序业务处理完毕后需要调用的回调方法,用于通知H5操作完成 */ /** * 定义业务指令 * @param {String} api 要定义的业务指令的代码,由 H5 发出,小程序 接收 * @param {APIAction} action 业务指令的执行动作 */ var defineApi = function(api, action){ if(api in apis) throw new Error("API: '" + api + "' exists already"); if(typeof action !== "function") throw new Error("Invalid action. Type of 'Function' is required"); apis[api] = action; }; /** * 样例:打开相机 */ defineApi("open-camera", function (params, callback) { params.msgFromMiniProgram = "OK!"; params.timeFromMiniProgram = Date.now(); setTimeout(function () { callback(JSON.stringify(params)); }, 1000); }); module.exports = apis; <|start_filename|>H5端/miniProgramHybrid.js<|end_filename|> /** * 对象序列化 * @param {Object} data 要序列化的对象 * @returns {String} */ var serialize = function (data) { var s = ""; for (var p in data) s += "&" + p + "=" + encodeURIComponent(data[p]).replace(/\+/gm, "%2B"); s = s.length > 0 ? s.substring(1) : s; return s; }; /** * 生成随机字符串 * @param {String} [prefix=""] 前缀 * @param {Number} [len=10] 除前缀外,要随机生成的字符串的长度 * @returns {String} */ var randomString = (function(){ var i = 0, tailLength = 2; var alphabet = "0123456789abcdefghijklmnopqrstuvwxyz"; var getTail = function(){ var s = (i++).toString(36); if(i > Math.pow(16, tailLength)) i = 0; return s.substring(s.length - tailLength); }; return function(prefix, len){ if(arguments.length < 2) len = 10; if(arguments.length < 1) prefix = ""; var minLen = tailLength + 1; if(len < minLen) throw new Error("Length should not be little than " + minLen); len -= tailLength; var str = ""; while(len-- > 0){ var index = Math.floor(Math.random() * alphabet.length); str += alphabet.charAt(index); } return prefix + str + getTail(); }; })(); var currentReq = null, currentCallback = null; /** * 调用微信小程序 * @param {String} api 业务指令 * @param {Object} params 业务参数 * @param {Function} [callback] 处理回调 */ var callMiniProgram = function(api, params, callback){ currentReq = randomString("H5Req_"); currentCallback = typeof callback === "function"? callback: null; wx.miniProgram.navigateTo({ url: "/pages/hybrid-page/hybrid?" + serialize({ cmd: JSON.stringify({ req: currentReq, api: api, params: params }) }) }); }; window.addEventListener("hashchange", function(e){ if(null == currentReq) return; if(!location.hash.startsWith("#" + currentReq + "=")) return; var params = {}; location.hash.substring(1).split("&").forEach(function(pair){ var tmp = pair.split("="); if(tmp.length < 1) return; params[decodeURIComponent(tmp[0].trim())] = decodeURIComponent(tmp[1].trim()); }); var result = params[currentReq]; if(typeof currentCallback !== "function"){ console.log(currentReq + " -> " + result); }else currentCallback(result); }); window.miniProgramHybrid = { call: callMiniProgram }; <|start_filename|>微信小程序/pages/hybrid-lib/driver.js<|end_filename|> var handler = require("./handler.js"); /** * * 【H5 与 小程序 的通讯模型】 * H5 主动通知小程序,并索要处理结果,小程序被动响应H5的请求,处理完毕后告知H5。 * * 【H5 主动通知 小程序 的方法】 * 1. H5 引入微信的 js-sdk(1.3.2版本及以上) * 2. H5 监听浏览器的 hashchange 事件,用于捕获小程序的处理结果 * 3. H5 通过调用 js-sdk 中的 api:wx.miniProgram.navigateTo({url: '微信小程序中响应H5请求的页面路径?cmd={req: "H5请求ID", api: "业务指令", params: {参数集合}}'}),实现主动通知的目的 * 其中,H5请求ID,代表由H5指定的,代表本次交互的,可被自己所识别的,时空唯一的hash,用于标识本次请求。如果没有指定该ID,则微信小程序将默认为:“miniProgramResult”。 * * 【小程序 响应 H5 请求的方法】 * 1. 在微信小程序中建立单独的页面,并在 onLoad 事件中解析 cmd 参数,用于响应 H5 请求 * 2. 使用 cmd 中的 api 更新此数据交换区中的 req 字段,并将 result 重置为空 * 3. 根据 cmd 中的 api 和 params 执行对应的业务指令 * 4. 得到执行结果后,无论成功或失败,更新此处设置的数据交换区,处理结果。约定:"0" 代表处理成功,其它取值代表处理失败的错误码。如果业务指令返回null或undefined,则认为处理成功,使用 "0" 代替 * 5. 调用 wx.navigateBack() 方法,返回 webview 所在的页面 * * 【小程序 通知 H5 处理结果的方法】 * 1. webview 所在的页面监听 onShow() 方法,使得当页面再次可见时,能够检索此处设置的数据交换区 * 2. 如果 req 不为空,则更新 webview 中的src,使其地址中 hash 变更为 #[req的取值]=[result的取值]&v=[时间戳] */ /** * 生成随机字符串 * @param {String} [prefix=""] 前缀 * @param {Number} [len=10] 除前缀外,要随机生成的字符串的长度 * @returns {String} */ var randomString = (function () { var i = 0, tailLength = 2; var alphabet = "0123456789abcdefghijklmnopqrstuvwxyz"; var getTail = function () { var s = (i++).toString(36); if (i > Math.pow(16, tailLength)) i = 0; return s.substring(s.length - tailLength); }; return function (prefix, len) { if (arguments.length < 2) len = 10; if (arguments.length < 1) prefix = ""; var minLen = tailLength + 1; if (len < minLen) throw new Error("Length should not be little than " + minLen); len -= tailLength; var str = ""; while (len-- > 0) { var index = Math.floor(Math.random() * alphabet.length); str += alphabet.charAt(index); } return prefix + str + getTail(); }; })(); /** * 给指定的url设置hash * @param {String} url 要设置hash的url * @param {String} hash 要设置的hash */ var setUrlHash = function (url, hash) { if (null == url || "" === (url = String(url).trim())) return url; var hashIndex = url.indexOf("#"); var urlWithoutQueryAndHash; if (-1 == hashIndex) { urlWithoutQueryAndHash = url; } else { urlWithoutQueryAndHash = url.substring(0, hashIndex); } return urlWithoutQueryAndHash + "#" + hash; }; /** * 返回webview所在的页面 */ var navigateBackToWebviewPage = function () { wx.navigateBack(); }; /** * 存储在全局变量中的,用于在小程序和H5之间交换数据的字段的key */ var hybridSwpKey = "__hybridSwp__" + randomString(); /** * 含有 webview 的小程序页面的 onShow 监听 * 该页面应当在 Page() 的 data 字段中定义 名称为 webviewSrc 的字段,以代表要打开的H5的链接地址 */ var onShow_webviewPageInMiniProgram = function(){ var swp = getApp()[hybridSwpKey]; if(null == swp || typeof swp !== "object") return; var req = swp.req; if(null == req || "" === (req = String(req.trim()))) return; var pages = getCurrentPages(); var page = pages[pages.length - 1]; console.log(">> " + swp.result); var newWebViewUrl = setUrlHash(page.data.webviewSrc, req + "=" + encodeURIComponent(swp.result) + "&v=" + Date.now()); console.log("Set webview url to " + newWebViewUrl); page.setData({ webviewSrc: newWebViewUrl }); }; /** * 处理 H5 请求的小程序页面的 onLoad 监听 * @param {Object} options 页面参数 */ var onLoad_requestHandlePageInMiniProgram = function (options){ var cmd = options.cmd; if (null == cmd || "" === (cmd = cmd.trim())) { console.warn("No command found"); navigateBackToWebviewPage(); return; } cmd = JSON.parse(decodeURIComponent(cmd)); var api = cmd.api; if (null == api || "" === (api = String(api).trim())) { console.warn("No api found"); navigateBackToWebviewPage(); return; } if (!(api in handler)) { navigateBackToWebviewPage(); return; } var req = cmd.req; if (null == req || "" === (req = String(req).trim())) req = "miniProgramResult"; var appInstance = getApp(); appInstance[hybridSwpKey] = { req: req, result: "" }; handler[api](cmd.params || {}, function(rst){ if (null === rst || undefined === rst) rst = "0"; rst = String(rst); var pages = getCurrentPages(); var page = pages[pages.length - 2];/* webview 页面 */ console.log(">> " + rst); var newWebViewUrl = setUrlHash(page.data.webviewSrc, req + "=" + encodeURIComponent(rst) + "&v=" + Date.now()); console.log("Set webview url to " + newWebViewUrl); page.setData({ webviewSrc: newWebViewUrl }); navigateBackToWebviewPage(); }); }; module.exports = { onLoad_requestHandlePageInMiniProgram: onLoad_requestHandlePageInMiniProgram }; <|start_filename|>微信小程序/pages/hybrid-page/hybrid.js<|end_filename|> var hybridLib = require("../hybrid-lib/driver.js"); Page({ onLoad: function (options) { hybridLib.onLoad_requestHandlePageInMiniProgram(options); } }) <|start_filename|>微信小程序/pages/index/index.js<|end_filename|> var hybridLib = require("../hybrid-lib/driver.js"); Page({ data: { /** * webview 链接的H5页面地址。开发者需根据自身情况,更改H5页面地址 * 注:webViewSrc 关键字保留,开发者不能改动 */ webviewSrc: "http://192.168.2.26/test/lab/wxMiniProgram.html" } })
RedTeapot/WxMiniProgramHybrid
<|start_filename|>test/Dockerfile<|end_filename|> # syntax=docker/dockerfile:experimental FROM python:3 WORKDIR /app RUN --mount=type=cache,target=/var/cache/apt --mount=type=cache,target=/var/lib/apt \ apt-get update \ && apt-get install taskwarrior COPY . . RUN --mount=type=cache,target=/root/.cache/pip \ pip install . ENTRYPOINT [ "/bin/bash", "-c" ] CMD [ "/app/test/test.sh" ]
Zebradil/powerline-taskwarrior
<|start_filename|>app/components/SpinnerHOC/styles.js<|end_filename|> import { StyleSheet } from 'react-native'; const transpBlack = 'rgba(0, 0, 0, 0.5)'; const styles = StyleSheet.create({ indicator: { backgroundColor: transpBlack, justifyContent: 'center' } }); export default styles; <|start_filename|>app/components/CoffeeItem/styles.js<|end_filename|> import { StyleSheet } from 'react-native'; import AppStyles from 'app/config/styles'; const styles = StyleSheet.create({ item: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', padding: 12, borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: AppStyles.color.COLOR_GREY }, img: { width: 56, height: 56, resizeMode: 'contain' }, title: { flex: 1, paddingHorizontal: 12, fontSize: 16 } }); export default styles; <|start_filename|>ios/Coffee/BatteryStatus.h<|end_filename|> // // BatteryStatus.h // Coffee // // Created by <NAME> on 10/09/18. // Copyright © 2018 Facebook. All rights reserved. // #import <Foundation/Foundation.h> #import <React/RCTBridgeModule.h> #import <React/RCTEventEmitter.h> @interface BatteryStatus : RCTEventEmitter <RCTBridgeModule> @end <|start_filename|>app/screens/Profile/styles.js<|end_filename|> import { StyleSheet } from 'react-native'; import AppStyles from 'app/config/styles'; const styles = StyleSheet.create({ container: { flex: 1 }, btn: { margin: 24 }, loginText: { color: AppStyles.color.COLOR_WHITE } }); export default styles; <|start_filename|>app/screens/Location/LocationView.js<|end_filename|> import React, { Component } from 'react'; import { View, Text, Platform } from 'react-native'; import { NativeModules } from 'react-native'; import Icon from 'react-native-vector-icons/MaterialIcons'; import Toolbar from 'app/components/Toolbar'; import styles from './styles'; import AppStyles from 'app/config/styles'; class LocationView extends Component { state = { batteryLevel: '' }; componentDidMount() { NativeModules.BatteryStatus.getBatteryStatus(batteryLevel => { this.setState({ batteryLevel: Platform.OS === 'ios' ? -1 * batteryLevel.level : batteryLevel }); }); } render() { return ( <View style={styles.container}> <Toolbar title="SEARCH SHOPS" /> <View style={styles.battery}> <Icon name="battery-alert" size={100} color={AppStyles.color.COLOR_PRIMARY} /> <Text>Battery Level : {this.state.batteryLevel}</Text> </View> </View> ); } } export default LocationView; <|start_filename|>app/screens/Cart/index.js<|end_filename|> import CartContainer from './CartContainer'; export default CartContainer; <|start_filename|>app/components/KeyboardAwareImage/KeyboardAwareImage.js<|end_filename|> import React, { Component } from 'react'; import { Animated, Keyboard, Platform } from 'react-native'; import PropTypes from 'prop-types'; import styles from './styles'; import Metrics from 'app/config/metrics'; const IMAGE_HEIGHT = Metrics.screenHeight / 3; const IMAGE_HEIGHT_SMALL = Metrics.screenHeight / 5; export default class KeyboardAwareImage extends Component { constructor(props) { super(props); this.imageHeight = new Animated.Value(IMAGE_HEIGHT); } componentDidMount() { if (Platform.OS === 'ios') { this.keyboardWillShowSub = Keyboard.addListener( 'keyboardWillShow', this.keyboardWillShow ); this.keyboardWillHideSub = Keyboard.addListener( 'keyboardWillHide', this.keyboardWillHide ); } else { this.keyboardWillShowSub = Keyboard.addListener( 'keyboardDidShow', this.keyboardWillShow ); this.keyboardWillHideSub = Keyboard.addListener( 'keyboardDidHide', this.keyboardWillHide ); } } componentWillUnmount() { this.keyboardWillShowSub.remove(); this.keyboardWillHideSub.remove(); } keyboardWillShow = () => { Animated.timing(this.imageHeight, { duration: 240, toValue: IMAGE_HEIGHT_SMALL }).start(); }; keyboardWillHide = () => { Animated.timing(this.imageHeight, { duration: 240, toValue: IMAGE_HEIGHT }).start(); }; render() { const { source } = this.props; return ( <Animated.Image source={source} style={[ styles.icon, { width: this.imageHeight, height: this.imageHeight } ]} /> ); } } KeyboardAwareImage.propTypes = { source: PropTypes.number }; <|start_filename|>app/screens/__tests__/screens/Login.js<|end_filename|> import 'react-native'; import React from 'react'; import Index from '../../Login/LoginView'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; test('renders correctly', () => { const wrapper = () => renderer.create(<Index />).toJSON(); expect(wrapper).toMatchSnapshot(); }); <|start_filename|>app/components/Dialog/index.js<|end_filename|> import * as React from 'react'; import { Paragraph, Button, Portal, Dialog, Colors } from 'react-native-paper'; import PropTypes from 'prop-types'; const UndismissableDialog = ({ visible, description, onSubmit, onCancel }) => ( <Portal> <Dialog onDismiss={onCancel} visible={visible} dismissable={false}> <Dialog.Title>COFFEE</Dialog.Title> <Dialog.Content> <Paragraph>{description}</Paragraph> </Dialog.Content> <Dialog.Actions> <Button color={Colors.grey500} onPress={onCancel}> Cancel </Button> <Button primary onPress={onSubmit}> OK </Button> </Dialog.Actions> </Dialog> </Portal> ); UndismissableDialog.propTypes = { visible: PropTypes.bool, description: PropTypes.string, onCancel: PropTypes.func, onSubmit: PropTypes.func }; export default UndismissableDialog; <|start_filename|>app/components/KeyboardAwareImage/index.js<|end_filename|> import KeyboardAwareImage from './KeyboardAwareImage'; export default KeyboardAwareImage; <|start_filename|>app/screens/Location/LocationContainer.js<|end_filename|> import React, { Component } from 'react'; import LocationView from './LocationView'; import { connect } from 'react-redux'; class LocationContainer extends Component { constructor(props) { super(props); } render() { return <LocationView {...this.props} />; } } function mapStateToProps(state) { return {}; } function mapDispatchToProps() { return {}; } export default connect( mapStateToProps, mapDispatchToProps )(LocationContainer); <|start_filename|>app/screens/Profile/ProfileContainer.js<|end_filename|> import React, { Component } from 'react'; import ProfileView from './ProfileView'; import { connect } from 'react-redux'; import * as loginActions from 'app/actions/loginActions'; class ProfileContainer extends Component { constructor(props) { super(props); } render() { return <ProfileView {...this.props} />; } } function mapStateToProps(state) { return {}; } function mapDispatchToProps(dispatch) { return { onLogOut: () => dispatch(loginActions.onLogOut()) }; } export default connect( mapStateToProps, mapDispatchToProps )(ProfileContainer); <|start_filename|>app/screens/Home/HomeView.js<|end_filename|> import React, { Component } from 'react'; import { BackHandler, View, FlatList } from 'react-native'; import { Searchbar } from 'react-native-paper'; import _ from 'lodash'; import Toolbar from 'app/components/Toolbar'; import CoffeeItem from 'app/components/CoffeeItem'; import styles from './styles'; const data = [ { id: 1, type: 'Espresso' }, { id: 2, type: 'Cappuccino' }, { id: 3, type: 'Coffee' }, { id: 4, type: 'Macciato' }, { id: 5, type: 'Mocha' }, { id: 6, type: 'Latte' } ]; class HomeView extends Component { constructor(props) { super(props); this.lastBackButtonPress = null; this.state = { query: '' }; } componentDidMount() { BackHandler.addEventListener('hardwareBackPress', this.backPress); } componentWillUnmount() { BackHandler.removeEventListener('hardwareBackPress', this.backPress); } backPress = () => { if (this.lastBackButtonPress + 2000 >= new Date().getTime()) { BackHandler.exitApp(); return true; } this.lastBackButtonPress = new Date().getTime(); return true; }; renderItem = ({ item }) => { return <CoffeeItem item={item} />; }; onQueryChange = query => { this.setState({ query }); }; filterCoffee = () => { const formatQuery = this.state.query.toLowerCase(); return _.filter(data, item => { return this.contains(item.type, formatQuery); }); }; contains = (name, query) => { if (name.toLowerCase().includes(query)) { return true; } return false; }; render() { const filteredData = this.filterCoffee(); return ( <View style={styles.container}> <Toolbar title="HOME" /> <Searchbar placeholder="Search" onChangeText={this.onQueryChange} value={this.state.firstQuery} /> <FlatList data={filteredData} renderItem={this.renderItem} extraData={this.state.query} keyExtractor={item => item.id.toString()} /> </View> ); } } export default HomeView; <|start_filename|>app/components/CoffeeItem/index.js<|end_filename|> import CoffeeItem from './CoffeeItem'; export default CoffeeItem; <|start_filename|>app/screens/Login/LoginView.js<|end_filename|> import React, { Component } from 'react'; import { View, TouchableWithoutFeedback, Keyboard } from 'react-native'; import { SafeAreaView } from 'react-navigation'; import { TextInput, Button, Text, Snackbar } from 'react-native-paper'; import PropTypes from 'prop-types'; import KeyboardAwareImage from 'app/components/KeyboardAwareImage'; import SpinnerHOC from 'app/components/SpinnerHOC'; import Images from 'app/config/images'; import styles from './styles'; //HOC For showing fullscreen loader about the screen const FullScreenSpinnerView = SpinnerHOC(View); class LoginView extends Component { state = { email: '', password: '', visible: false, snack: '' }; onPress = () => { this.dismissKeyboard(); const { email, password } = this.state; if (email.length > 0 && password.length > 0) { this.props.onLogin(email, password); } else { this.setState({ visible: true, snack: 'Missing Credentials' }); } }; onEmailChanged = text => { this.setState({ email: text }); }; onPasswordChanged = text => { this.setState({ password: text }); }; dismissKeyboard = () => { Keyboard.dismiss(); }; onRegister = () => { this.setState({ visible: true, snack: 'Register not implemented yet' }); }; onForgot = () => {}; renderLogo = () => { return ( <View style={styles.imgView}> <KeyboardAwareImage source={Images.coffee} /> </View> ); }; renderSnackBar = () => { return ( <Snackbar visible={this.state.visible} onDismiss={() => this.setState({ visible: false })} action={{ label: 'OK', onPress: () => { // Do something } }} > {this.state.snack} </Snackbar> ); }; renderInputView = () => { return ( <View style={styles.inputView}> <TextInput label="Email" mode="outlined" value={this.state.email} style={styles.input} onChangeText={this.onEmailChanged} error={this.state.emailError} /> <TextInput label="Password" mode="outlined" secureTextEntry value={this.state.password} style={styles.input} onChangeText={this.onPasswordChanged} /> <Button mode="contained" onPress={this.onPress} style={styles.btn} > <Text style={styles.loginText}>LOGIN</Text> </Button> <Button mode="flat" onPress={this.onForgot} style={styles.forgot} > <Text>Forgot Password</Text> </Button> <Text style={styles.account}>Dont have an account</Text> <Button mode="flat" onPress={this.onRegister}> <Text style={styles.regText}>Register</Text> </Button> </View> ); }; render() { return ( <FullScreenSpinnerView spinner={this.props.isLoading} style={styles.main} > <SafeAreaView style={styles.container}> <TouchableWithoutFeedback onPress={this.dismissKeyboard}> <View style={styles.container}> {this.renderLogo()} {this.renderInputView()} {this.renderSnackBar()} </View> </TouchableWithoutFeedback> </SafeAreaView> </FullScreenSpinnerView> ); } } LoginView.propTypes = { onLogin: PropTypes.func, theme: PropTypes.object, isLoading: PropTypes.bool }; export default LoginView; <|start_filename|>app/config/images.js<|end_filename|> /* App config for images */ const images = { coffee: require('../assets/images/coffee.png'), icons: { cappuccino: require('../assets/images/icons/cappuccino.png'), coffee: require('../assets/images/icons/coffee.png'), espresso: require('../assets/images/icons/espresso.png'), latte: require('../assets/images/icons/cappuccino.png'), macciato: require('../assets/images/icons/macciato.png'), mocha: require('../assets/images/icons/mocha.png') } }; export default images; <|start_filename|>app/components/SpinnerHOC/index.js<|end_filename|> import React from 'react'; import { View, StyleSheet, ActivityIndicator } from 'react-native'; import AppStyles from 'app/config/styles'; import styles from './styles'; export default (Comp: ReactClass<*>) => { return ({ spinner, children, ...props }: Object) => ( <View style={{ flex: 1 }}> <Comp {...props}>{children}</Comp> {spinner && ( <View style={[StyleSheet.absoluteFill, styles.indicator]}> <ActivityIndicator size="large" color={AppStyles.color.COLOR_PRIMARY} /> </View> )} </View> ); }; <|start_filename|>app/components/Toolbar/Toolbar.js<|end_filename|> import React, { Component } from 'react'; import { View, Text, Platform } from 'react-native'; import { Appbar } from 'react-native-paper'; import PropTypes from 'prop-types'; import CustomStatusBar from '../CustomStatusBar'; import AppStyles from 'app/config/styles'; import styles from './styles'; const MORE_ICON = Platform.OS === 'ios' ? 'more-horiz' : 'more-vert'; export default class Toolbar extends Component { constructor(props) { super(props); this.state = {}; } render() { const { title } = this.props; return ( <View> <CustomStatusBar backgroundColor={AppStyles.color.COLOR_PRIMARY} /> <Appbar> <Appbar.Action color={AppStyles.color.COLOR_WHITE} icon="menu" onPress={() => {}} /> <Appbar.Content title={title} titleStyle={styles.title} /> {true && ( <Appbar.Action color={AppStyles.color.COLOR_WHITE} icon={MORE_ICON} onPress={() => {}} /> )} </Appbar> </View> ); } } Toolbar.propTypes = { title: PropTypes.string }; <|start_filename|>app/navigation/SignedIn.js<|end_filename|> import React from 'react'; import { createMaterialBottomTabNavigator } from 'react-navigation-material-bottom-tabs'; import Home from 'app/screens/Home'; import Location from 'app/screens/Location'; import Cart from 'app/screens/Cart'; import Profile from 'app/screens/Profile'; import TabIcon from 'app/components/TabIcon'; import AppStyles from 'app/config/styles'; import PropTypes from 'prop-types'; const HomeTabIcon = ({ tintColor }) => ( <TabIcon name="home" tintColor={tintColor} /> ); HomeTabIcon.propTypes = { tintColor: PropTypes.number }; const LocationTabIcon = ({ tintColor }) => ( <TabIcon name="location-on" tintColor={tintColor} /> ); LocationTabIcon.propTypes = { tintColor: PropTypes.number }; const CartTabIcon = ({ tintColor }) => ( <TabIcon name="shopping-cart" tintColor={tintColor} /> ); CartTabIcon.propTypes = { tintColor: PropTypes.number }; const ProfileTabIcon = ({ tintColor }) => ( <TabIcon name="face" tintColor={tintColor} /> ); ProfileTabIcon.propTypes = { tintColor: PropTypes.number }; const SignedInNavigator = createMaterialBottomTabNavigator( { Home: { screen: Home, navigationOptions: { header: null, tabBarIcon: HomeTabIcon } }, Location: { screen: Location, navigationOptions: { header: null, tabBarIcon: LocationTabIcon } }, Cart: { screen: Cart, navigationOptions: { header: null, tabBarIcon: CartTabIcon } }, Profile: { screen: Profile, navigationOptions: { header: null, tabBarIcon: ProfileTabIcon } } }, { labeled: false, activeTintColor: AppStyles.color.COLOR_PRIMARY, inactiveTintColor: AppStyles.color.COLOR_GREY, pressColor: '#7f8c8d', barStyle: { backgroundColor: 'white' } } ); export default SignedInNavigator; <|start_filename|>index.js<|end_filename|> import { AppRegistry } from 'react-native'; import App from './app/Entrypoint'; AppRegistry.registerComponent('Coffee', () => App); <|start_filename|>app/navigation/NavigationStack.js<|end_filename|> import { createStackNavigator } from 'react-navigation'; import Login from 'app/screens/Login'; import Register from 'app/screens/Register'; import SignedIn from './SignedIn'; const SignedOutNavigator = createStackNavigator({ Login: { screen: Login, navigationOptions: { header: null, gesturesEnabled: false } }, Register: { screen: Register, navigationOptions: { header: null, gesturesEnabled: false } }, SignedIn: { screen: SignedIn, navigationOptions: { header: null, gesturesEnabled: false } } }); export default SignedOutNavigator; <|start_filename|>app/components/CoffeeItem/CoffeeItem.js<|end_filename|> import React, { Component } from 'react'; import { View, Image } from 'react-native'; import { Text, TouchableRipple } from 'react-native-paper'; import Icon from 'react-native-vector-icons/MaterialIcons'; import PropTypes from 'prop-types'; import Images from 'app/config/images'; import styles from './styles'; export default class CoffeeItem extends Component { shouldComponentUpdate(nextProps) { if (this.props.item.id === nextProps.item.id) { return false; } return true; } getImage = type => { switch (type) { case 'Espresso': return Images.icons.espresso; case 'Cappuccino': return Images.icons.cappuccino; case 'Coffee': return Images.icons.coffee; case 'Macciato': return Images.icons.macciato; case 'Mocha': return Images.icons.mocha; case 'Latte': return Images.icons.latte; } }; onPress = () => {}; render() { const { item } = this.props; return ( <TouchableRipple onPress={this.onPress} rippleColor="rgba(0, 0, 0, .32)" > <View style={styles.item}> <Image source={this.getImage(item.type)} style={styles.img} /> <Text style={styles.title}>{item.type}</Text> <Icon style={styles.iconStyle} name="keyboard-arrow-right" size={24} color="grey" /> </View> </TouchableRipple> ); } } CoffeeItem.propTypes = { item: PropTypes.object }; <|start_filename|>app/screens/Cart/CartContainer.js<|end_filename|> import React, { Component } from 'react'; import CartView from './CartView'; import { connect } from 'react-redux'; class CartContainer extends Component { constructor(props) { super(props); } render() { return <CartView {...this.props} />; } } function mapStateToProps(state) { return {}; } function mapDispatchToProps() { return {}; } export default connect( mapStateToProps, mapDispatchToProps )(CartContainer); <|start_filename|>app/screens/Login/styles.js<|end_filename|> import { StyleSheet } from 'react-native'; import AppStyles from 'app/config/styles'; const styles = StyleSheet.create({ main: { flex: 1 }, container: { flex: 1, backgroundColor: AppStyles.color.COLOR_WHITE, padding: 8 }, imgView: { alignItems: 'center', marginVertical: 12 }, inputView: { marginTop: 16 }, input: { marginTop: 8 }, loginText: { color: AppStyles.color.COLOR_WHITE, fontSize: 16, fontWeight: 'bold' }, regText: { color: AppStyles.color.COLOR_PRIMARY, fontSize: 14, fontWeight: 'bold' }, btn: { marginTop: 10 }, account: { textAlign: 'center', marginTop: 12 }, forgot: { alignItems: 'flex-end', marginTop: 16 } }); export default styles; <|start_filename|>app/actions/navigationActions.js<|end_filename|> /* * Reducer actions related with navigation */ import { NavigationActions } from 'react-navigation'; import NavigationService from 'app/navigation/NavigationService'; export function navigateToSignedInStack(params) { NavigationService.navigate('SignedIn', params); } <|start_filename|>app/components/CustomStatusBar/CustomStatusBar.js<|end_filename|> /* StatuBar component * only works/needed on Android */ import React from 'react'; import { View, StatusBar, Platform } from 'react-native'; import styles from './styles'; import PropTypes from 'prop-types'; const CustomStatusBar = props => { // if (Platform.OS === 'ios') { // return ( // <View style={[styles.iOsStatusBar]}> // <StatusBar // translucent // backgroundColor={props.backgroundColor} // barStyle="light-content" // {...props} // /> // </View> // ); // } return ( <View style={[ styles.statusBar, { backgroundColor: props.backgroundColor } ]} > <StatusBar translucent backgroundColor={props.backgroundColor} barStyle="light-content" {...props} /> </View> ); }; CustomStatusBar.propTypes = { backgroundColor: PropTypes.string }; export default CustomStatusBar; <|start_filename|>app/screens/Profile/ProfileView.js<|end_filename|> import React, { Component } from 'react'; import { View } from 'react-native'; import { Button, Text } from 'react-native-paper'; import PropTypes from 'prop-types'; import Toolbar from 'app/components/Toolbar'; import Dialog from 'app/components/Dialog'; import styles from './styles'; class ProfileView extends Component { state = { visible: false }; onPress = () => { this.setState({ visible: true }); }; onSubmit = () => { this.setState( { visible: false }, () => { this.props.onLogOut(); this.props.navigation.navigate('Login'); } ); }; onCancel = () => { this.setState({ visible: false }); }; render() { return ( <View style={styles.container}> <Toolbar title="PROFILE" /> <Button mode="contained" onPress={this.onPress} style={styles.btn} > <Text style={styles.loginText}>LOG OUT</Text> </Button> <Dialog visible={this.state.visible} onSubmit={this.onSubmit} onCancel={this.onCancel} description="Are you sure you want to log out?" /> </View> ); } } ProfileView.propTypes = { navigation: PropTypes.object, onLogOut: PropTypes.func }; export default ProfileView;
victorkvarghese/rn-coffee
<|start_filename|>util.lisp<|end_filename|> ;;;; util.lisp (in-package #:snakes) (defun xsubseq (sequence start end &key (type 'sequence)) "Returns sequence with start->end chopped out of it" (concatenate type (subseq sequence 0 start) (subseq sequence (1+ end)))) ;removes found keywords from list, returning cleaned list as second val (defun extract-keywords (keywords alist &optional stack) (if keywords (let ((pos (position (car keywords) alist))) (extract-keywords (cdr keywords) (if pos (xsubseq alist pos (1+ pos) :type 'list) alist) (if pos (acons (car keywords) (elt alist (1+ pos)) stack) stack))) (values stack alist))) (defun last-car (list) (car (last list))) <|start_filename|>snakes.asd<|end_filename|> ;;;; snakes.asd (asdf:defsystem #:snakes :serial t :description "Python style generators for Common Lisp." :author "<NAME> <<EMAIL>>" :license "Apache 2.0" :depends-on (#:cl-cont #:closer-mop #:fiveam #:iterate #:cl-utilities #:alexandria) :components ((:file "package") (:file "util") (:file "snakes" :depends-on ("util")) (:file "do-generators") (:file "itertools") (:file "iterate"))) <|start_filename|>snakes.lisp<|end_filename|> ;;;; snakes.lisp (in-package #:snakes) ;;; "snakes" goes here. Hacks and glory await! (define-condition snakes-error (error) ()) (define-condition insufficient-items (snakes-error) () (:documentation "Generator has run out of items before expected.")) (defparameter *snakes-multi-mode* :values) (defclass basic-generator () () (:metaclass closer-mop:funcallable-standard-class)) (defmethod initialize-instance :after ((g basic-generator) &key function) (with-slots () g (when function (closer-mop:set-funcallable-instance-function g function)))) (defgeneric generatorp (obj)) (defmethod generatorp ((obj t)) nil) (defmethod generatorp ((obj basic-generator)) t) (defmacro gen-lambda (params &body rest) "Version of lambda that wraps the anonymous function in an instance of the basic-generator class. This allows the lambda to be identified as a generator by its type. Basic-generator objects are derived from funcallable-standard-class, therefore they can be called as functions." `(let ((values-handler (create-values-handler))) (declare (ignorable values-handler)) (make-instance 'basic-generator :function (lambda ,params ,@rest)))) (defun create-values-handler () "Returns a function to transform ready-to-be-yielded values according to *snakes-multi-mode*. This should be set up at generator creation time, not at consumption time, so that generators in a chain can be set individually." (case *snakes-multi-mode* (:values #'identity) (:list #'list) (otherwise (error "*snakes-multi-mode* setting not supported")))) (defmacro with-yield (&body body) (let ((point (gensym)) (current (gensym))) `(let (,point ,current) (with-call/cc (labels ((yield (&rest values) (setf ,current values) (let/cc k (setf ,point k)))) ,@body (setf ,point nil))) (gen-lambda () (cond ((null ,point) 'generator-stop) (t (let ((current ,current)) (funcall ,point nil) ;values-handler: see gen-lambda (apply #'values (funcall values-handler current))))))))) (defmacro defgenerator (name arguments &body body) (multiple-value-bind (remaining-forms declarations doc-string) (alexandria:parse-body body :documentation t) `(defun ,name ,arguments ,doc-string ,@declarations (with-yield ,@remaining-forms)))) (defmacro if-generator ((var gen) true-clause &optional false-clause) "Pulls a single iteration out of gen. If a single var is specified, it places all the values from the iteration in a list under var. If var is a list, destructures values into the vars in the list. If the generator has stopped, evaluates false-clause, otherwise evaluates true-clause." `(,@(if (listp var) `(multiple-value-bind ,var (funcall ,gen)) `(let ((,var (multiple-value-list (funcall ,gen)))))) (if (eq 'generator-stop ,(if (listp var) (car var) `(car ,var))) ,false-clause ,true-clause))) (defmacro do-generator ((var &rest vars-and-generator) &body body) "Steps through the specified generator, binding the value it returns to var, then executing the body for each step. If multiple variables are specified and the generator returns multiple values, the extra values will be bound to the extra variables." (let ((g (gensym))) `(let ((,g ,(car (last vars-and-generator)))) (loop do (if-generator ((,var ,@(butlast vars-and-generator)) ,g) (progn ,@body) (return)))))) (defmacro do-generator-value-list ((var generator) &body body) "Like do-generator, except all values emitted by the generator are placed in a list under the user defined variable." (let ((g (gensym))) `(let ((,g ,generator)) (loop do (if-generator (,var ,g) (progn ,@body) (return)))))) (defun mapc-generator (function generator) (do-generator (item generator) (funcall function item)) (values)) (defun mapcar-generator (function generator) (let ((result ())) (do-generator (item generator) (push (funcall function item) result)) (nreverse result))) (defmacro yield-all (generator) "Walks through generator, re-yielding all of the items in it. Only meant for use inside of a defgenerator or with-yield block." (let ((x (gensym))) `(do-generator (,x ,generator) (yield ,x)))) (defmacro sticky-stop-lambda (params &body body) "Once a generator function has sent a generator-stop symbol, it should continue to do so every time it is called. This macro helps with obeying that rule." (let ((state (gensym)) (exit (gensym))) `(let ((,state t)) (lambda ,params (if ,state (block ,exit (labels ((sticky-stop () (setf ,state nil) (return-from ,exit 'generator-stop))) ,@body)) 'generator-stop))))) (defmacro gen-lambda-with-sticky-stop (&rest rest) `(make-instance 'basic-generator :function (sticky-stop-lambda ,@rest))) (defun take (n gen &key (fail-if-short t)) "Takes n items from generator gen, returning them as a list. If the generator contains less than n items, take will return what is available if fail-if-short is set to nil, otherwise it will raise an error." (let ((stor (if-generator (tmp gen) (mapcar #'list tmp)))) (when stor (dotimes (i (1- n)) (if-generator (vals gen) (loop for val in vals for j from 0 do (push val (elt stor j))) (if fail-if-short (error 'insufficient-items "Insufficient items in generator") (return (apply #'values (mapcar #'reverse stor)))))) (apply #'values (mapcar #'nreverse stor))))) (defun consume (n gen &key (fail-if-short t)) "Takes N items from generator gen, returning nothing. If the generator contains less than n items, consume will empty the generator silently if fail-if-short is set to nil, otherwise it will raise an error." (dotimes (i n) (if-generator (x gen) nil (if fail-if-short (error 'insufficient-items "Insufficient items in generator") (return nil)))) nil) ;;;;;;;;;;;;;;;;;;;;;;; ;Adaptors ;;;;;;;;;;;;;;;;;;;;;;; (defun function->generator (source-func predicate) "Returns a generator that repeatedly calls source-func, tests the result against the predicate function, terminates when the predicate tests false, otherwise yielding the result" (gen-lambda-with-sticky-stop () (let ((res (funcall source-func))) (if (funcall predicate res) res (sticky-stop))))) (defun value-func->generator (source) "Converts to a generator that sort of function which uses the second value as a completion signal. Will keep emitting the first return value of the source function until the second value is a nil." (gen-lambda-with-sticky-stop () (multiple-value-bind (res signal) (funcall source) (if signal res (sticky-stop))))) (defun list->generator (source) (let ((data source)) (gen-lambda () (if (not data) 'generator-stop (prog1 (car data) (setf data (cdr data))))))) (defun list->generator-with-tail (source) (let ((data source)) (gen-lambda () (if (not data) 'generator-stop (prog1 data (setf data (cdr data))))))) (defun generator->list (gen) (let ((stor (if-generator (tmp gen) (mapcar #'list tmp)))) (do-generator-value-list (g gen) (setf stor (loop for pile in stor for new in g collect (cons new pile)))) (apply #'values (mapcar #'nreverse stor)))) (defun sequence->generator (seq) (let ((seqlen (length seq)) (i 0)) (gen-lambda () (if (> i (1- seqlen)) 'generator-stop (prog1 (elt seq i) (incf i)))))) (defun stream->generator (stream) "Emits stream line at a time as a generator." (with-yield (loop for line = (read-line stream nil 'eof) until (eq line 'eof) do (yield line)))) (defun file->generator (path) "Given a path, will attempt to open the file specified and emit it line by line. Note: it will not close the file until the generator is exhausted." (let ((file (open path))) (with-yield (loop for line = (read-line file nil 'eof) until (eq line 'eof) do (yield line)) (close file)))) ;;;Ideas: ;adaptors for SERIES, others? ;file to generator ;port itertools, my tools, perhaps pytoolz <|start_filename|>package.lisp<|end_filename|> ;;;; package.lisp (defpackage #:snakes (:use #:cl #:cl-cont #:iterate) (:import-from #:iterate #:defmacro-driver #:generate #:for #:with #:next) (:import-from #:alexandria #:ensure-list) (:shadowing-import-from #:cl-utilities #:with-collectors) (:export #:generator-stop #:with-yield #:yield #:defgenerator #:basic-generator #:generatorp #:do-generator #:do-generator-value-list #:mapc-generator #:mapcar-generator #:yield-all #:take #:consume #:do-generators #:multi-gen #:*snakes-multi-mode* ;Adaptors #:function->generator #:value-func->generator #:list->generator #:list->generator-with-tail #:generator->list #:sequence->generator #:file->generator ;Construction tools #:gen-lambda #:gen-lambda-with-sticky-stop #:sticky-stop ;Itertools #:icount #:cycle #:repeat #:chain #:enumerate #:izip #:izip-longest #:compress #:dropwhile #:takewhile #:groupby #:ifilter #:ifilter-false #:islice #:imap #:starmap #:tee #:product #:permutations #:combinations #:combinations-with-replacement #:in-generator)) <|start_filename|>do-generators.lisp<|end_filename|> (in-package :snakes) (defun next-generator-value (gen) (let ((data (multiple-value-list (funcall gen)))) (if (eq 'generator-stop (car data)) (values nil nil) (apply #'values t data)))) (defun next-generator-value-filled (fill) "Returns a closure that acts like next-generator-value, but returns fill when the generator runs out. The :filled keyword instead of T in the first value slot still evaluates as true, but indicates that the generator has ended." (lambda (gen) (let ((x (multiple-value-list (next-generator-value gen)))) (if (car x) (apply #'values x) (values :filled fill))))) (defun fill-info (fillspec) (if fillspec (values t (cdr (assoc :fill-value fillspec))) (values nil nil))) (defun get-generator (g) (if (atom g) g (car g))) (defun get-nextval-func (genspec) (if (atom genspec) #'next-generator-value (multiple-value-bind (sig val) (fill-info (extract-keywords '(:fill-value) genspec)) (if sig (next-generator-value-filled val) #'next-generator-value)))) (defun multi-gen (&rest genspecs) (let ((generators (mapcar #'get-generator genspecs)) (valfuncs (mapcar #'get-nextval-func genspecs)) (stor nil) (sigs nil)) (gen-lambda-with-sticky-stop () (loop for g in generators for v in valfuncs do (let ((data (multiple-value-list (funcall v g)))) (if (car data) (progn (push (car data) sigs) (push (cdr data) stor)) (sticky-stop)))) (when (= 0 (length (remove-if (lambda (x) (eq x :filled)) sigs))) (sticky-stop)) (let ((tmp stor)) (setf stor nil) (setf sigs nil) (apply #'values (nreverse tmp)))))) (defun proc-list-spec (spec) (if (eq :list (car spec)) (labels ((proc (rspec) (when (atom rspec) (error ":list spec needs at least a var a list")) (if (or (keywordp (second rspec)) (not (cdr rspec))) (cons `(list->generator ,(car rspec)) (cdr rspec)) (cons (car rspec) (proc (cdr rspec)))))) (proc (cdr spec))) spec)) (defun process-genspecs (genspecs) (with-collectors (varnames< short-specs<) (dolist (genspec genspecs) (multiple-value-bind (fill spec) (extract-keywords '(:fill-value) genspec) (varnames< (butlast spec)) (short-specs< (if fill (list 'list (last-car spec) :fill-value (cdr (assoc :fill-value fill))) (last-car spec))))))) (defun bind-clause (datavar varnames body) `(let ,(with-collectors (col<) (loop for vnames in varnames for i from 0 do (loop for vn in vnames for j from 0 do (col< `(,vn (elt (elt ,datavar ,i) ,j)))))) ,@body)) (defmacro do-generators (genspecs &body body) "Simultaneously iterate through multiple generators at once. By default do-generators terminates when the shortest generator ends, but individual generators can be padded out with the :fill-value keyword. Do-generators can also iterate over lists in parallel with generators. To use lists, start the genspec with the :list keyword. Eg: (do-generators ((a (repeat 2)) (:list b '(4 5 6)) (c (list->generator '(8 9)) :fill-value 30)) (print (* a (+ b c)))) 24 28 72 NIL" (let ((genspecs (mapcar #'proc-list-spec genspecs)) (genr (gensym)) (data (gensym)) (sig (gensym))) (multiple-value-bind (varnames specs) (process-genspecs genspecs) `(let ((,genr (multi-gen ,@specs))) (loop do (destructuring-bind (,sig . ,data) (multiple-value-list (next-generator-value ,genr)) (unless ,sig (return)) ,(bind-clause data varnames body))))))) <|start_filename|>tests.lisp<|end_filename|> ;;;; -*- lisp -*- (defpackage #:snakes-test (:shadowing-import-from #:snakes #:repeat) (:use #:cl #:snakes #:fiveam #:iterate #:snakes)) (in-package :snakes-test) (eval-when (:compile-toplevel :load-toplevel :execute) (def-suite snakes-test)) (in-suite snakes-test) (defvar data '(1 2 3 4 5)) (test with-yield (is (functionp (with-yield (dolist (x data) (yield x))))) (is (= 1 (funcall (with-yield (dolist (x data) (yield x)))))) (is (equal data (generator->list (with-yield (dolist (x data) (yield x)))))) (is (equal data (generator->list (with-yield (do-generator (x (list->generator data)) (yield x))))))) (defgenerator some-numbers () (loop for i from 1 upto 3 do (yield i)) (dotimes (j 3) (yield (- 10 j)))) (test defgenerator (is (functionp (some-numbers))) (is (= 33 (reduce #'+ (generator->list (some-numbers)))))) (test multiple-value-generator (is (= 2 (do-generator (a b (with-yield (dolist (x data) (yield x (1+ x))))) a (return b))))) (test mapcar-generator (is (= 39 (reduce #'+ (mapcar-generator #'1+ (some-numbers)))))) (defgenerator flatten (list) (when list (cond ((atom list) (yield list)) (t (yield-all (flatten (car list))) (yield-all (flatten (cdr list))))))) (test yield-all (is (equal '(a b c d e f g h) (mapcar-generator #'identity (flatten '((a (b c) d) (e) f (g h))))))) (test generator-stop (eq 'generator-stop (funcall (list->generator nil)))) (test adaptors (is (equal '(#\a #\s #\d #\f) (generator->list (sequence->generator "asdf")))) (is (equal '(1 2 3) (generator->list (value-func->generator (let ((x 0)) (lambda () (incf x) (if (< 3 x) (values nil nil) (values x t))))))))) (test do-generators (is (= 40 (reduce #'+ (generator->list (with-yield (do-generators ((g (some-numbers)) (:list l data)) (yield (+ l g)))))))) (is (= 48 (reduce #'+ (generator->list (with-yield (do-generators ((g (some-numbers)) (:list l data :fill-value 0)) (yield (+ l g))))))))) (test consume (is (= 3 (let ((gen (some-numbers))) (consume 2 gen) (funcall gen))))) (test icount (is (equal '(10 12 14 16) (take 4 (icount 10 2))))) (test cycle (is (= 163 (reduce #'+ (take 30 (cycle '(4 5 6 7))))))) (test repeat (is (= 20 (reduce #'+ (generator->list (repeat 2 10)))))) (test chain (is (= 66 (reduce #'+ (generator->list (chain (some-numbers) (some-numbers))))))) (test izip-longest (is (= 179 (let ((x 0)) (do-generator (a b (izip-longest (list->generator data) (some-numbers) :fill-value 10)) (incf x (* a b))) x)))) (test compress (is (equal '(a c e f) (generator->list (compress (list->generator '(a b c d e f)) (list->generator '(t nil t nil t t))))))) (test dropwhile (is (equal '(6 4 1) (generator->list (dropwhile (lambda (x) (< x 5)) (list->generator '(1 4 6 4 1))))))) (test takewhile (is (equal '(1 4) (generator->list (takewhile (lambda (x) (< x 5)) (list->generator '(1 4 6 4 1))))))) (test groupby (is (= 4 (length (car (nth-value 1 (take 1 (groupby (list->generator '(A A A A B B B C C)))))))))) (test ifilter (is (= 20 (reduce #'+ (generator->list (ifilter #'evenp (some-numbers)))))) (is (= 13 (reduce #'+ (generator->list (ifilter-false #'evenp (some-numbers))))))) (test islice (is (equal '(a b) (generator->list (islice (list->generator '(a b c d e f g)) 2)))) (is (equal '(c d) (generator->list (islice (list->generator '(a b c d e f g)) 2 4)))) (is (equal '(c d e f g) (generator->list (islice (list->generator '(a b c d e f g)) 2 nil)))) (is (equal '(a c e g) (generator->list (islice (list->generator '(a b c d e f g)) 0 nil 2))))) (test imap (is (equal '(8 15 24) (generator->list (imap #'* (list->generator '(2 3 4)) (list->generator '(4 5 6))))))) (test starmap (is (equal '(32 9 1000) (generator->list (starmap #'expt (list->generator '((2 5) (3 2) (10 3)))))))) (test tee (is (= 33 (reduce #'+ (multiple-value-bind (a b) (tee (some-numbers) 2) (consume 6 a) (generator->list b)))))) (test product (is (equal '(1 1 1 1 1 2) (take 6 (product data data))))) (test permutations (is (equal '((1 2)) (take 1 (let ((*snakes-multi-mode* :list)) (permutations data 2)))))) (test combinations-with-replacement (is (= 6 (length (nth-value 1 (generator->list (combinations-with-replacement '(2 3 4) 2))))))) (test combinations (is (= 3 (length (nth-value 1 (generator->list (combinations '(2 3 4) 2))))))) (test iterate (is (equal data (generator->list (with-yield (iterate:iterate (for i in data) (yield i)))))) (is (= 33 (iterate (for (x) in-generator (some-numbers)) (summing x)))) (is (= 39 (reduce #'+ (generator->list (with-yield (iterate (for (x) in-generator (some-numbers)) (yield (1+ x))))))))) <|start_filename|>iterate.lisp<|end_filename|> ;;;Driver for snakes generator consumption in iterate macro. (in-package :snakes) (defmacro-driver (FOR var IN-GENERATOR gen) "Iterate through a snakes generator" (let ((g (gensym)) (tmp (gensym)) (kwd (if generate 'generate 'for))) `(progn (with ,g = ,gen) (,kwd ,var next (if-generator (,tmp ,g) ,tmp (terminate))))))
shamazmazum/snakes
<|start_filename|>test/Portal.test.js<|end_filename|> import { render } from "@testing-library/svelte"; import TestPortalWrapper from "./TestPortalWrapper.svelte"; import TestLifecycle from "./TestLifecycle.svelte"; import { tick } from "svelte"; describe("<Portal /> target", () => { let wrapper; beforeEach(() => { let { container } = render(TestPortalWrapper); wrapper = container; }); it("should be rendererd in a specific HTML element", () => { const renderedDivInFooter = wrapper.querySelector( "footer #renderedInFooter" ); expect(renderedDivInFooter).not.toBe(null); }); it("should be rendererd in a specific HTML element with id", () => { const renderedDivInTargetId = wrapper.querySelector( "#target #renderedInTarget" ); expect(renderedDivInTargetId).not.toBe(null); }); it("should be rendererd in a specific HTML element with class", () => { const renderedDivInTargetClass = wrapper.querySelector( ".target #renderedInTargetClass" ); expect(renderedDivInTargetClass).not.toBe(null); }); it("should not render a Portal at the origin", () => { const portalContainer = wrapper.querySelector("#portalCtn"); const isPortalContainerEmpty = portalContainer.innerHTML.trim().length === 0; expect(isPortalContainerEmpty).toBe(true); }); }); describe("<Portal /> lifecycle", () => { let targetEl; let lifecycleComponent; beforeEach(() => { let { container, component } = render(TestLifecycle); lifecycleComponent = component; targetEl = container.querySelector("#modals"); }); it("should be added and removed from dom", async () => { expect(targetEl.children).toHaveLength(1); lifecycleComponent.$set({ modalVisible: false }); await tick(); expect(targetEl.children).toHaveLength(0); lifecycleComponent.$set({ modalVisible: true }); await tick(); expect(targetEl.children).toHaveLength(1); }); it("should be removed from dom after after outro", async () => { lifecycleComponent.$set({ containerVisible: false }); await tick(); expect(targetEl.children).toHaveLength(1); await new Promise((resolve) => { const unsubscribe = lifecycleComponent.$on("outroend", () => { resolve(); unsubscribe(); }); }); expect(targetEl.children).toHaveLength(0); }); });
trasherdk/svelte-portal
<|start_filename|>tests/common/offset_ptr.h<|end_filename|> //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #pragma once #include <cassert> #include <cstdint> #include <iterator> template <typename T, typename OffsetT = std::int32_t> class offset_ptr { public: // NOTE: We satisfy everything for RandomAccessIterator _except_ being CopyConstructible using value_type = T; using reference = T&; using pointer = T*; using difference_type = OffsetT; using iterator_category = std::random_access_iterator_tag; offset_ptr() = default; // NOTE: Since we're dealing with offsets, Copying becomes very awkward, so explicitly prohibit it. The equivalent // functionality can be achieved by converting to pointer and back offset_ptr(const offset_ptr&) = delete; offset_ptr& operator=(const offset_ptr&) = delete; void reset(T* ptr) noexcept { m_offset = static_cast<OffsetT>(reinterpret_cast<std::uint8_t*>(ptr) - reinterpret_cast<std::uint8_t*>(this)); assert(get() == ptr); } T* get() noexcept { if (!m_offset) { return nullptr; } return reinterpret_cast<T*>(reinterpret_cast<char*>(this) + m_offset); } const T* get() const noexcept { if (!m_offset) { return nullptr; } return reinterpret_cast<const T*>(reinterpret_cast<const char*>(this) + m_offset); } operator T*() noexcept { return get(); } operator const T*() const noexcept { return get(); } T* operator->() noexcept { return get(); } const T* operator->() const noexcept { return get(); } // NOTE: The index shouldn't be bound by the limitations of our internal offset type T& operator[](std::ptrdiff_t index) noexcept { return get()[index]; } const T& operator[](std::ptrdiff_t index) const noexcept { return get()[index]; } // NOTE: In the effort to avoid copies, we return pointers for operations that expect something somewhat equivalent offset_ptr& operator++() noexcept { m_offset += sizeof(T); return *this; } pointer operator++(int) noexcept { auto result = get(); ++(*this); return result; } offset_ptr& operator+=(difference_type distance) noexcept { m_offset += distance * sizeof(T); return *this; } offset_ptr& operator--() noexcept { m_offset -= sizeof(T); return *this; } pointer operator--(int) noexcept { auto result = get(); --(*this); return result; } offset_ptr& operator-=(difference_type distance) noexcept { m_offset -= distance * sizeof(T); return *this; } friend pointer operator+(const offset_ptr& lhs, std::ptrdiff_t rhs) noexcept { return lhs.get() + rhs; } friend pointer operator+(std::ptrdiff_t lhs, const offset_ptr& rhs) noexcept { return rhs.get() + lhs; } friend pointer operator-(const offset_ptr& lhs, std::ptrdiff_t rhs) noexcept { return lhs.get() - rhs; } friend std::ptrdiff_t operator-(const offset_ptr& lhs, const offset_ptr& rhs) noexcept { return lhs.get() - rhs.get(); } friend bool operator==(const offset_ptr& lhs, const offset_ptr& rhs) noexcept { return lhs.get() == rhs.get(); } friend bool operator!=(const offset_ptr& lhs, const offset_ptr& rhs) noexcept { return lhs.get() != rhs.get(); } friend bool operator<(const offset_ptr& lhs, const offset_ptr& rhs) noexcept { return lhs.get() < rhs.get(); } friend bool operator<=(const offset_ptr& lhs, const offset_ptr& rhs) noexcept { return lhs.get() <= rhs.get(); } friend bool operator>(const offset_ptr& lhs, const offset_ptr& rhs) noexcept { return lhs.get() > rhs.get(); } friend bool operator>=(const offset_ptr& lhs, const offset_ptr& rhs) noexcept { return lhs.get() >= rhs.get(); } private: OffsetT m_offset = 0; }; <|start_filename|>include/detour_transaction.h<|end_filename|> //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #pragma once #include <cassert> #include <windows.h> #include <detours.h> #include "win32_error.h" namespace detours { // RAII wrapper around DetourTransactionBegin/Abort/Commit that ensures either Abort or Commit gets called struct transaction { transaction() { check_win32(::DetourTransactionBegin()); } transaction(const transaction&) = delete; transaction& operator=(const transaction&) = delete; transaction(transaction&& other) noexcept : m_abort(std::exchange(other.m_abort, false)) { } ~transaction() { if (m_abort) { ::DetourTransactionAbort(); } } void commit() { assert(m_abort); check_win32(::DetourTransactionCommit()); m_abort = false; } private: // If not explicitly told to commit, assume an error occurred and abort bool m_abort = true; }; } <|start_filename|>tests/scenarios/LongPathsTest/paths.h<|end_filename|> //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #pragma once #include <filesystem> #include <file_paths.h> constexpr wchar_t g_programFilesRelativeTestPath[] = LR"(this\is\a\moderately\long\path\and\will\turn\into\an\even\longer\path\when\we\take\into\account\the\fact\that\it\will\have\the\package\path\appended\to\it\when\the\app\is\installed\to\the\WindowsApps\directory)"; inline const auto g_programFilesPath = psf::known_folder(FOLDERID_ProgramFiles); inline const auto g_testPath = g_programFilesPath / g_programFilesRelativeTestPath; inline const auto g_testFilePath = g_testPath / L"file.txt"; constexpr char g_expectedFileContents[] = "You are reading from the package path"; <|start_filename|>tests/fixups/TraceFixup/PreserveError.h<|end_filename|> //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #pragma once #include <windows.h> // Preserves the result of GetLastError, restoring it on destruction of the object. Useful when any post-processing may // change the result of GetLastError that you wish to ignore (e.g. such as logging) struct preserve_last_error { DWORD value = ::GetLastError(); ~preserve_last_error() { ::SetLastError(value); } }; <|start_filename|>tests/scenarios/LongPathsTest/CreateDeleteFileTests.cpp<|end_filename|> //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include <test_config.h> #include "paths.h" static int DoCreateDeleteFileTest() { clean_redirection_path(); trace_messages(L"Opening existing file: ", info_color, g_testFilePath.native(), new_line); auto file = ::CreateFileW( g_testFilePath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (file == INVALID_HANDLE_VALUE) { return trace_last_error(L"CreateFile failed"); } // The file should have successfully gotten copied over char buffer[256]; DWORD bytesRead; if (!::ReadFile(file, buffer, sizeof(buffer) - 1, &bytesRead, nullptr)) { ::CloseHandle(file); return trace_last_error(L"ReadFile failed"); } else if (buffer[bytesRead] = '\0'; std::strcmp(g_expectedFileContents, buffer)) { ::CloseHandle(file); trace_message(L"ERROR: Copied file contents do not match expected contents\n", error_color); trace_messages(error_color, L"ERROR: Expected contents: ", error_info_color, g_expectedFileContents, new_line); trace_messages(error_color, L"ERROR: File contents: ", error_info_color, buffer, new_line); return ERROR_ASSERTION_FAILURE; } ::CloseHandle(file); trace_message(L"File successfully opened/read. Modifying its contents to validate that we don't copy it again on the next access\n"); const char newContents[] = "You are reading from the redirected location"; write_entire_file(g_testFilePath.c_str(), newContents); if (auto contents = read_entire_file(g_testFilePath.c_str()); contents != newContents) { trace_message(L"ERROR: File contents do not match expected contents\n", error_color); trace_messages(error_color, L"ERROR: Expected contents: ", error_info_color, newContents, new_line); trace_messages(error_color, L"ERROR: File contents: ", error_info_color, contents, new_line); return ERROR_ASSERTION_FAILURE; } auto path = g_testPath / L"new.txt"; trace_messages(L"Creating new file: ", info_color, path.native(), new_line); file = ::CreateFileW(path.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr); if (file == INVALID_HANDLE_VALUE) { return trace_last_error(L"CreateFile failed"); } ::CloseHandle(file); trace_message(L"File successfully created... Now trying to delete it\n"); if (!::DeleteFileW(path.c_str())) { return trace_last_error(L"DeleteFile failed"); } else if (std::filesystem::exists(path)) { trace_message(L"ERROR: DeleteFile succeeded, but the file still exists\n", error_color); return ERROR_ASSERTION_FAILURE; } return ERROR_SUCCESS; } int CreateDeleteFileTest() { test_begin("Create/Delete File Test"); auto result = DoCreateDeleteFileTest(); test_end(result); return result; } <|start_filename|>tests/scenarios/FileSystemTest/MoveFileTest.cpp<|end_filename|> //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include <filesystem> #include <functional> #include <test_config.h> #include "common_paths.h" auto MoveFileFunc = &::MoveFileW; auto MoveFileExFunc = [](LPCWSTR from, LPCWSTR to) { return ::MoveFileExW(from, to, MOVEFILE_WRITE_THROUGH); }; static int DoMoveFileTest( const std::function<BOOL(PCWSTR, PCWSTR)>& moveFn, const char* moveFnName, const std::filesystem::path& from, const std::filesystem::path& to, const char* expectedContents) { trace_messages(L"Moving file from: ", info_color, from.native(), new_line); trace_messages(L" to: ", info_color, to.native(), new_line); trace_messages(L" Using function: ", info_color, moveFnName, new_line); // The initial move should succeed if (!moveFn(from.c_str(), to.c_str())) { return trace_last_error(L"Initial move of the file failed"); } auto contents = read_entire_file(to.c_str()); trace_messages(L"Moved file contents: ", info_color, contents.c_str(), new_line); if (contents != expectedContents) { trace_message(L"ERROR: Moved file contents did not match the expected contents\n", error_color); trace_messages(error_color, L"ERROR: Expected contents: ", error_info_color, expectedContents, new_line); return ERROR_ASSERTION_FAILURE; } // Trying to move again should fail. Note that we might need to re-create the moved-from file since it should have // been deleted write_entire_file(from.c_str(), "You are reading the re-created file contents"); trace_message(L"Moving the file again to ensure that the call fails due to the destination already existing...\n"); if (moveFn(from.c_str(), to.c_str())) { trace_message(L"ERROR: Second move succeeded\n", error_color); return ERROR_ASSERTION_FAILURE; } else if (::GetLastError() != ERROR_ALREADY_EXISTS) { return trace_last_error(L"The second move failed as expected, but the error was not set to ERROR_ALREADY_EXISTS"); } return ERROR_SUCCESS; } static int DoMoveToReplaceFileTest(const std::filesystem::path& from, const std::filesystem::path& to) { const char newContents[] = "You are reading modified text"; write_entire_file(from.c_str(), newContents); trace_message(L"Validating that MoveFileEx can replace the target file...\n"); if (!::MoveFileExW(from.c_str(), to.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { return trace_last_error(L"Failed to replace the file"); } auto contents = read_entire_file(to.c_str()); trace_messages(L"File contents are now: ", info_color, contents.c_str(), new_line); if (contents != newContents) { trace_message(L"ERROR: Moved file contents did not match the expected contents\n", error_color); trace_messages(error_color, L"ERROR: Expected contents: ", error_info_color, newContents, new_line); return ERROR_ASSERTION_FAILURE; } return ERROR_SUCCESS; } int MoveFileTests() { int result = ERROR_SUCCESS; auto packageFilePath = g_packageRootPath / g_packageFileName; auto otherFilePath = g_packageRootPath / L"MôƲèFïℓè.txt"; // Move from a file in the package path test_begin("MoveFile From Package Path Test"); clean_redirection_path(); auto testResult = DoMoveFileTest(MoveFileFunc, "MoveFile", packageFilePath, otherFilePath, g_packageFileContents); result = result ? result : testResult; test_end(testResult); test_begin("MoveFileEx From Package Path Test"); clean_redirection_path(); testResult = DoMoveFileTest(MoveFileExFunc, "MoveFileEx", packageFilePath, otherFilePath, g_packageFileContents); result = result ? result : testResult; test_end(testResult); // MoveFileEx has the ability to replace an existing file, so go ahead and test that here test_begin("MoveFileEx Replace Redirected File Test"); testResult = DoMoveToReplaceFileTest(packageFilePath, otherFilePath); result = result ? result : testResult; test_end(testResult); // Move from a created file to a file in the package path // NOTE: Ideally the move with would fail, but due to the limitations around file deletion, we explicitly ensure // that the call won't fail. If this is ever changes, this test will start to fail, at which point we'll need // to update this assumption const char otherFileContents[] = "You are reading from the generated file"; test_begin("MoveFile Replace Package File Test"); clean_redirection_path(); write_entire_file(otherFilePath.c_str(), otherFileContents); testResult = DoMoveFileTest(MoveFileFunc, "MoveFile", otherFilePath, packageFilePath, otherFileContents); result = result ? result : testResult; test_end(testResult); test_begin("MoveFileEx Replace Package File Test"); clean_redirection_path(); write_entire_file(otherFilePath.c_str(), otherFileContents); testResult = DoMoveFileTest(MoveFileExFunc, "MoveFileEx", otherFilePath, packageFilePath, otherFileContents); result = result ? result : testResult; test_end(testResult); // Again, validate that MoveFileEx has the ability to replace an existing file test_begin("MoveFileEx Replace Redirected Package File Test"); testResult = DoMoveToReplaceFileTest(otherFilePath, packageFilePath); result = result ? result : testResult; test_end(testResult); return result; } <|start_filename|>include/reentrancy_guard.h<|end_filename|> //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------------------------------- // // Type that's useful to detect reentrancy. This can be useful at either global for function-static scope. Note however, // that either should be declared 'thread_local'. E.g. Use might look like: // void FooFixup() // { // thread_local psf::reentrancy_guard reentrancyGuard; // auto guard = reentrancyGuard.enter(); // if (guard) { /*fixup code here*/ } // return FooImpl(); // } #pragma once #include <utility> namespace psf { namespace details { struct restore_on_exit { restore_on_exit(bool& target, bool restoreValue) : m_target(&target), m_restoreValue(restoreValue) { } restore_on_exit(const restore_on_exit&) = delete; restore_on_exit& operator=(const restore_on_exit&) = delete; restore_on_exit(restore_on_exit&& other) : m_target(other.m_target), m_restoreValue(other.m_restoreValue) { other.m_target = nullptr; } ~restore_on_exit() { if (m_target) { *m_target = m_restoreValue; } } explicit operator bool() { return !m_restoreValue; } private: bool* m_target; bool m_restoreValue; }; } class reentrancy_guard { public: details::restore_on_exit enter() { auto restoreValue = std::exchange(m_isReentrant, true); return details::restore_on_exit{ m_isReentrant, restoreValue }; } private: bool m_isReentrant = false; }; } <|start_filename|>include/psf_constants.h<|end_filename|> //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #pragma once namespace psf { // Detours will auto-rename from *32.dll to *64.dll and vice-versa when doing cross-architectures launches. It will // _not_, however auto-rename when the architectures match, so we need to make sure that we reference the binary // name that's consistent with the current architecture. #ifdef _M_IX86 // 32-bit constexpr wchar_t runtime_dll_name[] = L"PsfRuntime32.dll"; // 32-bit binaries should invoke the 64-bit version of PsfRunDll constexpr char run_dll_name[] = "PsfRunDll64.exe"; constexpr wchar_t wrun_dll_name[] = L"PsfRunDll64.exe"; constexpr char arch_string[] = "32"; constexpr wchar_t warch_string[] = L"32"; #else // 64 bit constexpr wchar_t runtime_dll_name[] = L"PsfRuntime64.dll"; // 64-bit binaries should invoke the 32-bit version of PsfRunDll constexpr char run_dll_name[] = "PsfRunDll32.exe"; constexpr wchar_t wrun_dll_name[] = L"PsfRunDll32.exe"; constexpr char arch_string[] = "64"; constexpr wchar_t warch_string[] = L"64"; #endif } <|start_filename|>include/fancy_handle.h<|end_filename|> //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #pragma once #include <windows.h> namespace psf { struct fancy_handle { HANDLE value = INVALID_HANDLE_VALUE; fancy_handle() noexcept = default; fancy_handle(std::nullptr_t) noexcept { } fancy_handle(HANDLE value) noexcept : value(value) { } HANDLE get() const noexcept { return value; } operator HANDLE() const noexcept { return get(); } HANDLE normalize() const noexcept { return (value == INVALID_HANDLE_VALUE) ? nullptr : value; } explicit operator bool() const noexcept { return normalize() != nullptr; } friend bool operator==(const fancy_handle& lhs, const fancy_handle& rhs) { return lhs.normalize() == rhs.normalize(); } friend bool operator!=(const fancy_handle& lhs, const fancy_handle& rhs) { return lhs.normalize() != rhs.normalize(); } friend bool operator<(const fancy_handle& lhs, const fancy_handle& rhs) { return lhs.normalize() < rhs.normalize(); } friend bool operator<=(const fancy_handle& lhs, const fancy_handle& rhs) { return lhs.normalize() <= rhs.normalize(); } friend bool operator>(const fancy_handle& lhs, const fancy_handle& rhs) { return lhs.normalize() > rhs.normalize(); } friend bool operator>=(const fancy_handle& lhs, const fancy_handle& rhs) { return lhs.normalize() >= rhs.normalize(); } }; template <auto CloseFn> struct handle_deleter { using pointer = fancy_handle; void operator()(const pointer& handle) noexcept { if (handle) { CloseFn(handle); } } }; } <|start_filename|>tests/scenarios/FileSystemTest/FileAttributesTest.cpp<|end_filename|> //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include <filesystem> #include <functional> #include <test_config.h> #include "attributes.h" #include "common_paths.h" auto GetFileAttributesFunc = &::GetFileAttributesW; auto GetFileAttributesExFunc = [](PCWSTR path) { WIN32_FILE_ATTRIBUTE_DATA data; if (!::GetFileAttributesExW(path, GetFileExInfoStandard, &data)) { return INVALID_FILE_ATTRIBUTES; } return data.dwFileAttributes; }; static int DoFileAttributesTest(const std::function<DWORD(PCWSTR)>& getFn, const char* getFnName, const std::filesystem::path& path) { trace_messages(L"Querying the attributes for file: ", info_color, path.native(), new_line); trace_messages(L" Using function: ", info_color, getFnName, new_line); auto attr = getFn(path.c_str()); if (attr == INVALID_FILE_ATTRIBUTES) { return trace_last_error(L"Failed to query the file attributes"); } trace_messages(L"Initial file attributes: ", info_color, file_attributes(attr), new_line); if (attr == FILE_ATTRIBUTE_HIDDEN) { trace_message(L"WARNING: File already has the FILE_ATTRIBUTE_HIDDEN attribute\n", warning_color); trace_message(L"WARNING: This may cause false negatives\n", warning_color); } trace_messages(L"Setting the file's attributes to: ", info_color, L"FILE_ATTRIBUTE_HIDDEN\n"); if (!::SetFileAttributesW(path.c_str(), FILE_ATTRIBUTE_HIDDEN)) { return trace_last_error(L"Failed to set the file's attributes"); } attr = getFn(path.c_str()); if (attr == INVALID_FILE_ATTRIBUTES) { return trace_last_error(L"Failed to query the file attributes"); } trace_messages(L"New file attributes: ", info_color, file_attributes(attr), new_line); if (attr != FILE_ATTRIBUTE_HIDDEN) { trace_message(L"ERROR: File attributes set incorrectly\n", error_color); return ERROR_ASSERTION_FAILURE; } return ERROR_SUCCESS; } int FileAttributesTests() { int result = ERROR_SUCCESS; auto packageFilePath = g_packageRootPath / g_packageFileName; test_begin("GetFileAttributes Test"); clean_redirection_path(); auto testResult = DoFileAttributesTest(GetFileAttributesFunc, "GetFileAttributes", packageFilePath); result = result ? result : testResult; test_end(testResult); test_begin("GetFileAttributesEx Test"); clean_redirection_path(); testResult = DoFileAttributesTest(GetFileAttributesExFunc, "GetFileAttributesEx", packageFilePath); result = result ? result : testResult; test_end(testResult); return result; } <|start_filename|>tests/fixups/TraceFixup/FunctionImplementations.h<|end_filename|> //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------------------------------- // // Function pointers that always point to the underlying function implementation (at least so far as TraceFixup is // concerned) e.g. to avoid calling a fixed function during the implementation of another fixup function. #pragma once #include <cassert> #include <ntstatus.h> #include <windows.h> #include <winternl.h> // NOTE: Some enums/structs/functions are declared in winternl.h, but are incomplete. Namespace is to disambiguate namespace winternl { // Enum definitions not present in winternl.h typedef enum _FILE_INFORMATION_CLASS { FileDirectoryInformation = 1, FileFullDirectoryInformation, FileBothDirectoryInformation, FileBasicInformation, FileStandardInformation, FileInternalInformation, FileEaInformation, FileAccessInformation, FileNameInformation, FileRenameInformation, FileLinkInformation, FileNamesInformation, FileDispositionInformation, FilePositionInformation, FileFullEaInformation, FileModeInformation, FileAlignmentInformation, FileAllInformation, FileAllocationInformation, FileEndOfFileInformation, FileAlternateNameInformation, FileStreamInformation, FilePipeInformation, FilePipeLocalInformation, FilePipeRemoteInformation, FileMailslotQueryInformation, FileMailslotSetInformation, FileCompressionInformation, FileObjectIdInformation, FileCompletionInformation, FileMoveClusterInformation, FileQuotaInformation, FileReparsePointInformation, FileNetworkOpenInformation, FileAttributeTagInformation, FileTrackingInformation, FileIdBothDirectoryInformation, FileIdFullDirectoryInformation, FileValidDataLengthInformation, FileShortNameInformation, FileIoCompletionNotificationInformation, FileIoStatusBlockRangeInformation, FileIoPriorityHintInformation, FileSfioReserveInformation, FileSfioVolumeInformation, FileHardLinkInformation, FileProcessIdsUsingFileInformation, FileNormalizedNameInformation, FileNetworkPhysicalNameInformation, FileIdGlobalTxDirectoryInformation, FileIsRemoteDeviceInformation, FileUnusedInformation, FileNumaNodeInformation, FileStandardLinkInformation, FileRemoteProtocolInformation, FileRenameInformationBypassAccessCheck, FileLinkInformationBypassAccessCheck, FileVolumeNameInformation, FileIdInformation, FileIdExtdDirectoryInformation, FileReplaceCompletionInformation, FileHardLinkFullIdInformation, FileIdExtdBothDirectoryInformation, FileDispositionInformationEx, FileRenameInformationEx, FileRenameInformationExBypassAccessCheck, FileDesiredStorageClassInformation, FileStatInformation, FileMemoryPartitionInformation, FileMaximumInformation, FileStatLxInformation, FileCaseSensitiveInformation } FILE_INFORMATION_CLASS, *PFILE_INFORMATION_CLASS; typedef enum _KEY_INFORMATION_CLASS { KeyBasicInformation, KeyNodeInformation, KeyFullInformation, KeyNameInformation, KeyCachedInformation, KeyFlagsInformation, KeyVirtualizationInformation, KeyHandleTagsInformation, KeyTrustInformation, KeyLayerInformation, MaxKeyInfoClass } KEY_INFORMATION_CLASS; typedef enum _IO_PRIORITY_HINT { IoPriorityVeryLow, IoPriorityLow, IoPriorityNormal, IoPriorityHigh, IoPriorityCritical, MaxIoPriorityTypes } IO_PRIORITY_HINT; typedef enum _KEY_VALUE_INFORMATION_CLASS { KeyValueBasicInformation, KeyValueFullInformation, KeyValuePartialInformation, KeyValueFullInformationAlign64, KeyValuePartialInformationAlign64, KeyValueLayerInformation, MaxKeyValueInfoClass } KEY_VALUE_INFORMATION_CLASS; // Struct definitions not present in winternl.h typedef struct _FILE_DIRECTORY_INFORMATION { ULONG NextEntryOffset; ULONG FileIndex; LARGE_INTEGER CreationTime; LARGE_INTEGER LastAccessTime; LARGE_INTEGER LastWriteTime; LARGE_INTEGER ChangeTime; LARGE_INTEGER EndOfFile; LARGE_INTEGER AllocationSize; ULONG FileAttributes; ULONG FileNameLength; WCHAR FileName[1]; } FILE_DIRECTORY_INFORMATION, *PFILE_DIRECTORY_INFORMATION; typedef struct _FILE_FULL_DIR_INFORMATION { ULONG NextEntryOffset; ULONG FileIndex; LARGE_INTEGER CreationTime; LARGE_INTEGER LastAccessTime; LARGE_INTEGER LastWriteTime; LARGE_INTEGER ChangeTime; LARGE_INTEGER EndOfFile; LARGE_INTEGER AllocationSize; ULONG FileAttributes; ULONG FileNameLength; ULONG EaSize; WCHAR FileName[1]; } FILE_FULL_DIR_INFORMATION, *PFILE_FULL_DIR_INFORMATION; typedef struct _FILE_BOTH_DIR_INFORMATION { ULONG NextEntryOffset; ULONG FileIndex; LARGE_INTEGER CreationTime; LARGE_INTEGER LastAccessTime; LARGE_INTEGER LastWriteTime; LARGE_INTEGER ChangeTime; LARGE_INTEGER EndOfFile; LARGE_INTEGER AllocationSize; ULONG FileAttributes; ULONG FileNameLength; ULONG EaSize; CCHAR ShortNameLength; WCHAR ShortName[12]; WCHAR FileName[1]; } FILE_BOTH_DIR_INFORMATION, *PFILE_BOTH_DIR_INFORMATION; typedef struct _FILE_BASIC_INFORMATION { LARGE_INTEGER CreationTime; LARGE_INTEGER LastAccessTime; LARGE_INTEGER LastWriteTime; LARGE_INTEGER ChangeTime; ULONG FileAttributes; } FILE_BASIC_INFORMATION, *PFILE_BASIC_INFORMATION; typedef struct _FILE_STANDARD_INFORMATION { LARGE_INTEGER AllocationSize; LARGE_INTEGER EndOfFile; ULONG NumberOfLinks; BOOLEAN DeletePending; BOOLEAN Directory; } FILE_STANDARD_INFORMATION, *PFILE_STANDARD_INFORMATION; typedef struct _FILE_INTERNAL_INFORMATION { LARGE_INTEGER IndexNumber; } FILE_INTERNAL_INFORMATION, *PFILE_INTERNAL_INFORMATION; typedef struct _FILE_EA_INFORMATION { ULONG EaSize; } FILE_EA_INFORMATION, *PFILE_EA_INFORMATION; typedef struct _FILE_ACCESS_INFORMATION { ACCESS_MASK AccessFlags; } FILE_ACCESS_INFORMATION, *PFILE_ACCESS_INFORMATION; typedef struct _FILE_NAME_INFORMATION { ULONG FileNameLength; WCHAR FileName[1]; } FILE_NAME_INFORMATION, *PFILE_NAME_INFORMATION; typedef struct _FILE_RENAME_INFORMATION { union { BOOLEAN ReplaceIfExists; ULONG Flags; } DUMMYUNIONNAME; BOOLEAN ReplaceIfExists; HANDLE RootDirectory; ULONG FileNameLength; WCHAR FileName[1]; } FILE_RENAME_INFORMATION, *PFILE_RENAME_INFORMATION; typedef struct _FILE_LINK_INFORMATION { BOOLEAN ReplaceIfExists; HANDLE RootDirectory; ULONG FileNameLength; WCHAR FileName[1]; } FILE_LINK_INFORMATION, *PFILE_LINK_INFORMATION; typedef struct _FILE_NAMES_INFORMATION { ULONG NextEntryOffset; ULONG FileIndex; ULONG FileNameLength; WCHAR FileName[1]; } FILE_NAMES_INFORMATION, *PFILE_NAMES_INFORMATION; typedef struct _FILE_DISPOSITION_INFORMATION { BOOLEAN DeleteFile; } FILE_DISPOSITION_INFORMATION, *PFILE_DISPOSITION_INFORMATION; typedef struct _FILE_POSITION_INFORMATION { LARGE_INTEGER CurrentByteOffset; } FILE_POSITION_INFORMATION, *PFILE_POSITION_INFORMATION; typedef struct _FILE_FULL_EA_INFORMATION { ULONG NextEntryOffset; UCHAR Flags; UCHAR EaNameLength; USHORT EaValueLength; CHAR EaName[1]; } FILE_FULL_EA_INFORMATION, *PFILE_FULL_EA_INFORMATION; typedef struct _FILE_MODE_INFORMATION { ULONG Mode; } FILE_MODE_INFORMATION, *PFILE_MODE_INFORMATION; typedef struct _FILE_ALIGNMENT_INFORMATION { ULONG AlignmentRequirement; } FILE_ALIGNMENT_INFORMATION, *PFILE_ALIGNMENT_INFORMATION; typedef struct _FILE_ALL_INFORMATION { FILE_BASIC_INFORMATION BasicInformation; FILE_STANDARD_INFORMATION StandardInformation; FILE_INTERNAL_INFORMATION InternalInformation; FILE_EA_INFORMATION EaInformation; FILE_ACCESS_INFORMATION AccessInformation; FILE_POSITION_INFORMATION PositionInformation; FILE_MODE_INFORMATION ModeInformation; FILE_ALIGNMENT_INFORMATION AlignmentInformation; FILE_NAME_INFORMATION NameInformation; } FILE_ALL_INFORMATION, *PFILE_ALL_INFORMATION; typedef struct _FILE_ALLOCATION_INFORMATION { LARGE_INTEGER AllocationSize; } FILE_ALLOCATION_INFORMATION, *PFILE_ALLOCATION_INFORMATION; typedef struct _FILE_END_OF_FILE_INFORMATION { LARGE_INTEGER EndOfFile; } FILE_END_OF_FILE_INFORMATION, *PFILE_END_OF_FILE_INFORMATION; typedef struct _FILE_STREAM_INFORMATION { ULONG NextEntryOffset; ULONG StreamNameLength; LARGE_INTEGER StreamSize; LARGE_INTEGER StreamAllocationSize; WCHAR StreamName[1]; } FILE_STREAM_INFORMATION, *PFILE_STREAM_INFORMATION; typedef struct _FILE_PIPE_INFORMATION { ULONG ReadMode; ULONG CompletionMode; } FILE_PIPE_INFORMATION, *PFILE_PIPE_INFORMATION; typedef struct _FILE_PIPE_LOCAL_INFORMATION { ULONG NamedPipeType; ULONG NamedPipeConfiguration; ULONG MaximumInstances; ULONG CurrentInstances; ULONG InboundQuota; ULONG ReadDataAvailable; ULONG OutboundQuota; ULONG WriteQuotaAvailable; ULONG NamedPipeState; ULONG NamedPipeEnd; } FILE_PIPE_LOCAL_INFORMATION, *PFILE_PIPE_LOCAL_INFORMATION; typedef struct _FILE_PIPE_REMOTE_INFORMATION { LARGE_INTEGER CollectDataTime; ULONG MaximumCollectionCount; } FILE_PIPE_REMOTE_INFORMATION, *PFILE_PIPE_REMOTE_INFORMATION; typedef struct _FILE_MAILSLOT_QUERY_INFORMATION { ULONG MaximumMessageSize; ULONG MailslotQuota; ULONG NextMessageSize; ULONG MessagesAvailable; LARGE_INTEGER ReadTimeout; } FILE_MAILSLOT_QUERY_INFORMATION, *PFILE_MAILSLOT_QUERY_INFORMATION; typedef struct _FILE_MAILSLOT_SET_INFORMATION { PLARGE_INTEGER ReadTimeout; } FILE_MAILSLOT_SET_INFORMATION, *PFILE_MAILSLOT_SET_INFORMATION; typedef struct _FILE_COMPRESSION_INFORMATION { LARGE_INTEGER CompressedFileSize; USHORT CompressionFormat; UCHAR CompressionUnitShift; UCHAR ChunkShift; UCHAR ClusterShift; UCHAR Reserved[3]; } FILE_COMPRESSION_INFORMATION, *PFILE_COMPRESSION_INFORMATION; typedef struct _FILE_OBJECTID_INFORMATION { LONGLONG FileReference; UCHAR ObjectId[16]; union { struct { UCHAR BirthVolumeId[16]; UCHAR BirthObjectId[16]; UCHAR DomainId[16]; } DUMMYSTRUCTNAME; UCHAR ExtendedInfo[48]; } DUMMYUNIONNAME; } FILE_OBJECTID_INFORMATION, *PFILE_OBJECTID_INFORMATION; typedef struct _FILE_QUOTA_INFORMATION { ULONG NextEntryOffset; ULONG SidLength; LARGE_INTEGER ChangeTime; LARGE_INTEGER QuotaUsed; LARGE_INTEGER QuotaThreshold; LARGE_INTEGER QuotaLimit; SID Sid; } FILE_QUOTA_INFORMATION, *PFILE_QUOTA_INFORMATION; typedef struct _FILE_REPARSE_POINT_INFORMATION { LONGLONG FileReference; ULONG Tag; } FILE_REPARSE_POINT_INFORMATION, *PFILE_REPARSE_POINT_INFORMATION; typedef struct _FILE_NETWORK_OPEN_INFORMATION { LARGE_INTEGER CreationTime; LARGE_INTEGER LastAccessTime; LARGE_INTEGER LastWriteTime; LARGE_INTEGER ChangeTime; LARGE_INTEGER AllocationSize; LARGE_INTEGER EndOfFile; ULONG FileAttributes; } FILE_NETWORK_OPEN_INFORMATION, *PFILE_NETWORK_OPEN_INFORMATION; typedef struct _FILE_ATTRIBUTE_TAG_INFORMATION { ULONG FileAttributes; ULONG ReparseTag; } FILE_ATTRIBUTE_TAG_INFORMATION, *PFILE_ATTRIBUTE_TAG_INFORMATION; typedef struct _FILE_ID_BOTH_DIR_INFORMATION { ULONG NextEntryOffset; ULONG FileIndex; LARGE_INTEGER CreationTime; LARGE_INTEGER LastAccessTime; LARGE_INTEGER LastWriteTime; LARGE_INTEGER ChangeTime; LARGE_INTEGER EndOfFile; LARGE_INTEGER AllocationSize; ULONG FileAttributes; ULONG FileNameLength; ULONG EaSize; CCHAR ShortNameLength; WCHAR ShortName[12]; LARGE_INTEGER FileId; WCHAR FileName[1]; } FILE_ID_BOTH_DIR_INFORMATION, *PFILE_ID_BOTH_DIR_INFORMATION; typedef struct _FILE_ID_FULL_DIR_INFORMATION { ULONG NextEntryOffset; ULONG FileIndex; LARGE_INTEGER CreationTime; LARGE_INTEGER LastAccessTime; LARGE_INTEGER LastWriteTime; LARGE_INTEGER ChangeTime; LARGE_INTEGER EndOfFile; LARGE_INTEGER AllocationSize; ULONG FileAttributes; ULONG FileNameLength; ULONG EaSize; LARGE_INTEGER FileId; WCHAR FileName[1]; } FILE_ID_FULL_DIR_INFORMATION, *PFILE_ID_FULL_DIR_INFORMATION; typedef struct _FILE_VALID_DATA_LENGTH_INFORMATION { LARGE_INTEGER ValidDataLength; } FILE_VALID_DATA_LENGTH_INFORMATION, *PFILE_VALID_DATA_LENGTH_INFORMATION; typedef struct _FILE_IO_PRIORITY_HINT_INFORMATION { IO_PRIORITY_HINT PriorityHint; } FILE_IO_PRIORITY_HINT_INFORMATION, *PFILE_IO_PRIORITY_HINT_INFORMATION; typedef struct _FILE_LINK_ENTRY_INFORMATION { ULONG NextEntryOffset; LONGLONG ParentFileId; ULONG FileNameLength; WCHAR FileName[1]; } FILE_LINK_ENTRY_INFORMATION, *PFILE_LINK_ENTRY_INFORMATION; typedef struct _FILE_LINKS_INFORMATION { ULONG BytesNeeded; ULONG EntriesReturned; FILE_LINK_ENTRY_INFORMATION Entry; } FILE_LINKS_INFORMATION, *PFILE_LINKS_INFORMATION; typedef struct _FILE_NETWORK_PHYSICAL_NAME_INFORMATION { ULONG FileNameLength; WCHAR FileName[1]; } FILE_NETWORK_PHYSICAL_NAME_INFORMATION, *PFILE_NETWORK_PHYSICAL_NAME_INFORMATION; typedef struct _FILE_ID_GLOBAL_TX_DIR_INFORMATION { ULONG NextEntryOffset; ULONG FileIndex; LARGE_INTEGER CreationTime; LARGE_INTEGER LastAccessTime; LARGE_INTEGER LastWriteTime; LARGE_INTEGER ChangeTime; LARGE_INTEGER EndOfFile; LARGE_INTEGER AllocationSize; ULONG FileAttributes; ULONG FileNameLength; LARGE_INTEGER FileId; GUID LockingTransactionId; ULONG TxInfoFlags; WCHAR FileName[1]; } FILE_ID_GLOBAL_TX_DIR_INFORMATION, *PFILE_ID_GLOBAL_TX_DIR_INFORMATION; typedef struct _FILE_COMPLETION_INFORMATION { HANDLE Port; PVOID Key; } FILE_COMPLETION_INFORMATION, *PFILE_COMPLETION_INFORMATION; typedef struct _FILE_DISPOSITION_INFORMATION_EX { ULONG Flags; } FILE_DISPOSITION_INFORMATION_EX, *PFILE_DISPOSITION_INFORMATION_EX; typedef struct _KEY_BASIC_INFORMATION { LARGE_INTEGER LastWriteTime; ULONG TitleIndex; ULONG NameLength; WCHAR Name[1]; } KEY_BASIC_INFORMATION, *PKEY_BASIC_INFORMATION; typedef struct _KEY_NODE_INFORMATION { LARGE_INTEGER LastWriteTime; ULONG TitleIndex; ULONG ClassOffset; ULONG ClassLength; ULONG NameLength; WCHAR Name[1]; } KEY_NODE_INFORMATION, *PKEY_NODE_INFORMATION; typedef struct _KEY_FULL_INFORMATION { LARGE_INTEGER LastWriteTime; ULONG TitleIndex; ULONG ClassOffset; ULONG ClassLength; ULONG SubKeys; ULONG MaxNameLen; ULONG MaxClassLen; ULONG Values; ULONG MaxValueNameLen; ULONG MaxValueDataLen; WCHAR Class[1]; } KEY_FULL_INFORMATION, *PKEY_FULL_INFORMATION; typedef struct _KEY_NAME_INFORMATION { ULONG NameLength; WCHAR Name[1]; } KEY_NAME_INFORMATION, *PKEY_NAME_INFORMATION; typedef struct _KEY_CACHED_INFORMATION { LARGE_INTEGER LastWriteTime; ULONG TitleIndex; ULONG SubKeys; ULONG MaxNameLen; ULONG Values; ULONG MaxValueNameLen; ULONG MaxValueDataLen; ULONG NameLength; } KEY_CACHED_INFORMATION, *PKEY_CACHED_INFORMATION; typedef struct _KEY_VIRTUALIZATION_INFORMATION { ULONG VirtualizationCandidate; ULONG VirtualizationEnabled; ULONG VirtualTarget; ULONG VirtualStore; ULONG VirtualSource; ULONG Reserved; } KEY_VIRTUALIZATION_INFORMATION, *PKEY_VIRTUALIZATION_INFORMATION; typedef struct _KEY_VALUE_BASIC_INFORMATION { ULONG TitleIndex; ULONG Type; ULONG NameLength; WCHAR Name[1]; } KEY_VALUE_BASIC_INFORMATION, PKEY_VALUE_BASIC_INFORMATION; typedef struct _KEY_VALUE_FULL_INFORMATION { ULONG TitleIndex; ULONG Type; ULONG DataOffset; ULONG DataLength; ULONG NameLength; WCHAR Name[1]; } KEY_VALUE_FULL_INFORMATION, PKEY_VALUE_FULL_INFORMATION; typedef struct _KEY_VALUE_PARTIAL_INFORMATION { ULONG TitleIndex; ULONG Type; ULONG DataLength; UCHAR Data[1]; } KEY_VALUE_PARTIAL_INFORMATION, PKEY_VALUE_PARTIAL_INFORMATION; // Function declarations not present in winternl.h NTSTATUS __stdcall NtQueryInformationFile( HANDLE FileHandle, PIO_STATUS_BLOCK IoStatusBlock, PVOID FileInformation, ULONG Length, FILE_INFORMATION_CLASS FileInformationClass); NTSTATUS __stdcall NtQueryKey( HANDLE KeyHandle, KEY_INFORMATION_CLASS KeyInformationClass, PVOID KeyInformation, ULONG Length, PULONG ResultLength); NTSTATUS __stdcall NtQueryValueKey( HANDLE KeyHandle, PUNICODE_STRING ValueName, KEY_VALUE_INFORMATION_CLASS KeyValueInformationClass, PVOID KeyValueInformation, ULONG Length, PULONG ResultLength); } // NOTE: The functions in winternl.h are not included in any import lib and therefore must be manually loaded in template <typename Func> inline Func GetNtDllInternalFunction(const char* functionName) { static auto mod = ::LoadLibraryW(L"ntdll.dll"); assert(mod); // Ignore namespaces for (auto ptr = functionName; *ptr; ++ptr) { if (*ptr == ':') { functionName = ptr + 1; } } auto result = reinterpret_cast<Func>(::GetProcAddress(mod, functionName)); assert(result); return result; } #define WINTERNL_FUNCTION(Name) (GetNtDllInternalFunction<decltype(&Name)>(#Name)); namespace impl { inline auto NtQueryKey = WINTERNL_FUNCTION(winternl::NtQueryKey); inline auto NtQueryInformationFile = WINTERNL_FUNCTION(winternl::NtQueryInformationFile); inline auto NtQueryValueKey = WINTERNL_FUNCTION(winternl::NtQueryValueKey); } <|start_filename|>tests/scenarios/CompositionTest/main.cpp<|end_filename|> //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include <sstream> #include <windows.h> #include <test_config.h> int wmain(int argc, const wchar_t** argv) { auto result = parse_args(argc, argv); if (result == ERROR_SUCCESS) { test_initialize("Composition Tests", 1); test_begin("Composition Test"); // NOTE: trace_message will call MultiByteToWideChar if we give it a non-wide string, hence the duplication // below. Otherwise, we'll fix the message we're trying to print out! wchar_t buffer[256]; constexpr char inputMessage[] = "This message should have been fixed"; trace_messages(L"Initial text: ", info_color, L"This message should have been fixed", new_line); auto size = ::MultiByteToWideChar( CP_ACP, MB_ERR_INVALID_CHARS, inputMessage, static_cast<int>(std::size(inputMessage) - 1), buffer, static_cast<int>(std::size(buffer) - 1)); if (!size) { result = trace_last_error(L"MultiByteToWideChar failed"); } else { buffer[size] = '\0'; trace_messages(L"Result text: ", info_color, buffer, new_line); constexpr wchar_t expectedOutputMessage[] = L"You've been fixed! And you've been fixed again!"; if (std::wcsncmp(buffer, expectedOutputMessage, std::size(expectedOutputMessage) - 1) != 0) { result = ERROR_ASSERTION_FAILURE; trace_message(L"ERROR: Text did not match the expected output\n", error_color); } else { trace_message(L"SUCCESS: The text was modified successfully\n", success_color); } } test_end(result); test_cleanup(); } if (!g_testRunnerPipe) { system("pause"); } return result; } <|start_filename|>fixups/ElectronFixup/ElectronFixupForPartialTrustImpls.h<|end_filename|> #pragma once #include "psf_framework.h" #include "reentrancy_guard.h" inline thread_local psf::reentrancy_guard g_reentrancyGuard; namespace impl { // Directory Manipulation inline auto CreateDirectory = psf::detoured_string_function(&::CreateDirectoryA , &::CreateDirectoryW); inline auto RemoveDirectory = psf::detoured_string_function(&::RemoveDirectoryA , &::RemoveDirectoryW); // Attribute Manipulation inline auto GetFileAttributes = psf::detoured_string_function(&::GetFileAttributesA , &::GetFileAttributesW ); inline auto GetFileAttributesEx = psf::detoured_string_function(&::GetFileAttributesExA, &::GetFileAttributesExW); inline auto SetFileAttributes = psf::detoured_string_function(&::SetFileAttributesA , &::SetFileAttributesW ); // File Manipulation inline auto FindFirstFileEx = psf::detoured_string_function(&::FindFirstFileExA , &::FindFirstFileExW); inline auto MoveFile = psf::detoured_string_function(&::MoveFileA , &::MoveFileW ); inline auto MoveFileEx = psf::detoured_string_function(&::MoveFileExA , &::MoveFileExW ); inline auto CopyFile = psf::detoured_string_function(&::CopyFileA , &::CopyFileW ); inline auto ReplaceFile = psf::detoured_string_function(&::ReplaceFileA , &::ReplaceFileW ); inline auto DeleteFile = psf::detoured_string_function(&::DeleteFileA , &::DeleteFileW ); inline auto CreateFile = psf::detoured_string_function(&::CreateFileA , &::CreateFileW ); // Pipe Manipulation inline auto CreateNamedPipe = psf::detoured_string_function(&::CreateNamedPipeA , &::CreateNamedPipeW); inline auto CallNamedPipe = psf::detoured_string_function(&::CallNamedPipeA , &::CallNamedPipeW ); inline auto WaitNamedPipe = psf::detoured_string_function(&::WaitNamedPipeA , &::WaitNamedPipeW ); } // namespace impl <|start_filename|>tests/scenarios/FileSystemTest/ReplaceFileTest.cpp<|end_filename|> //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include <filesystem> #include <functional> #include <test_config.h> #include "common_paths.h" static int DoReplaceFileTest( const std::filesystem::path& from, const std::filesystem::path& to, const std::filesystem::path& backup, const char* expectedContents) { trace_messages(L"Replacing file: ", info_color, to.native(), new_line); trace_messages(L" with: ", info_color, from.native(), new_line); trace_messages(L" using backup: ", info_color, backup.native(), new_line); auto replacedContents = read_entire_file(to.c_str()); trace_messages(L"Replaced file initial contents: ", info_color, replacedContents.c_str(), new_line); if (!::ReplaceFileW(to.c_str(), from.c_str(), backup.c_str(), 0, nullptr, nullptr)) { return trace_last_error(L"Failed to replace the file"); } auto contents = read_entire_file(to.c_str()); trace_messages(L"Replaced file final contents: ", info_color, contents.c_str(), new_line); if (contents != expectedContents) { trace_message(L"ERROR: File contents did not match the expected value\n", error_color); trace_messages(error_color, L"ERROR: Expected contents: ", error_info_color, expectedContents, new_line); return ERROR_ASSERTION_FAILURE; } contents = read_entire_file(backup.c_str()); trace_messages(L"Backup file contents: ", info_color, contents.c_str(), new_line); if (contents != replacedContents) { trace_message(L"ERROR: Backup file contents should have matched the initial file contents\n", error_color); return ERROR_ASSERTION_FAILURE; } return ERROR_SUCCESS; } int ReplaceFileTests() { int result = ERROR_SUCCESS; auto packageFilePath = g_packageRootPath / g_packageFileName; auto otherFilePath = g_packageRootPath / L"MôƲèFïℓè.txt"; auto backupFilePath = g_packageRootPath / L"ßáçƙúƥFïℓè.txt"; // Copy from the package file test_begin("Replace Redirected File with Package File Test"); clean_redirection_path(); write_entire_file(otherFilePath.c_str(), "You are reading file contents that should have been replaced"); auto testResult = DoReplaceFileTest(packageFilePath, otherFilePath, backupFilePath, g_packageFileContents); result = result ? result : testResult; test_end(testResult); // Copy to the package file test_begin("Replace Package File with Redirected File Test"); clean_redirection_path(); const char generatedFileContents[] = "You are reading from the generated file"; write_entire_file(otherFilePath.c_str(), generatedFileContents); testResult = DoReplaceFileTest(otherFilePath, packageFilePath, backupFilePath, generatedFileContents); result = result ? result : testResult; test_end(testResult); // Copy from the redirected package file test_begin("Replace Redirected File with Redirected Package File Test"); clean_redirection_path(); const char replacedFileContents[] = "You are reading from the redirected package file"; write_entire_file(packageFilePath.c_str(), replacedFileContents); write_entire_file(otherFilePath.c_str(), "You are reading file contents that should have been replaced"); testResult = DoReplaceFileTest(packageFilePath, otherFilePath, backupFilePath, replacedFileContents); result = result ? result : testResult; test_end(testResult); return result; } <|start_filename|>tests/fixups/MultiByteToWideCharTestFixup/main.cpp<|end_filename|> //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #define PSF_DEFINE_EXPORTS #include <psf_framework.h> <|start_filename|>tests/common/error_logging.h<|end_filename|> //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #pragma once #include <iostream> #include <string> #include <system_error> #include "console_output.h" constexpr auto error_color = console::color::red; inline auto error_text() { return console::change_foreground(error_color); } constexpr auto error_info_color = console::color::dark_red; inline auto error_info_text() { return console::change_foreground(error_info_color); } constexpr auto warning_color = console::color::yellow; inline auto warning_text() { return console::change_foreground(warning_color); } constexpr auto warning_info_color = console::color::dark_yellow; inline auto warning_info_text() { return console::change_foreground(warning_info_color); } constexpr auto info_color = console::color::dark_gray; inline auto info_text() { return console::change_foreground(info_color); } constexpr auto success_color = console::color::green; inline auto success_text() { return console::change_foreground(success_color); } inline std::string error_message(int err) { // Remove the ".\r\n" that gets added to all messages auto msg = std::system_category().message(err); msg.resize(msg.length() - 3); return msg; } inline int print_error(int err, const char* msg = nullptr) { if (msg) { std::wcout << error_text() << "ERROR: " << msg << std::endl; } std::wcout << error_text() << "ERROR: " << error_message(err).c_str() << " (" << err << ")\n"; return err; } inline int print_last_error(const char* msg = nullptr) { return print_error(::GetLastError(), msg); } <|start_filename|>tests/scenarios/LongPathsTest/CreateRemoveDirectoryTest.cpp<|end_filename|> //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include <test_config.h> #include "paths.h" static int DoCreateRemoveDirectoryTest() { clean_redirection_path(); auto path = g_testPath / L"Foo"; trace_messages(L"Creating directory: ", info_color, path.native(), new_line); if (!::CreateDirectoryW(path.c_str(), nullptr)) { return trace_last_error(L"CreateDirectory failed"); } trace_message(L"Directory created successfully... Now trying to remove it\n"); if (!::RemoveDirectoryW(path.c_str())) { return trace_last_error(L"RemoveDirectory failed"); } else if (std::filesystem::exists(path)) { trace_message(L"ERROR: RemoveDirectory succeeded, but the directory still exists\n", error_color); return ERROR_ASSERTION_FAILURE; } return ERROR_SUCCESS; } int CreateRemoveDirectoryTest() { test_begin("Create/Remove Directory Test"); auto result = DoCreateRemoveDirectoryTest(); test_end(result); return result; } <|start_filename|>fixups/ElectronFixup/main.cpp<|end_filename|> #include <Windows.h> // Define the fixup declarations here #define PSF_DEFINE_EXPORTS #include "psf_framework.h" <|start_filename|>tests/scenarios/FileSystemTest/CreateHardLinkTest.cpp<|end_filename|> //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include <filesystem> #include <functional> #include <test_config.h> #include "common_paths.h" static int DoCreateHardLinkTest( const std::filesystem::path& linkPath, const std::filesystem::path& targetPath, const char* expectedInitialContents) { trace_messages(L"Creating a hard-link from: ", info_color, linkPath.native(), new_line); trace_messages(L" to: ", info_color, targetPath.native(), new_line); // NOTE: Call CreateHardLink _before_ reading file contents as reading the file will copy it to the redirected path, // if it is a file that exists in the package if (!::CreateHardLinkW(linkPath.c_str(), targetPath.c_str(), nullptr)) { return trace_last_error(L"Failed to create the hard-link"); } // Contents of the link file should match that of the target auto contents = read_entire_file(targetPath.c_str()); trace_messages(L"Initial target file contents: ", info_color, contents.c_str(), new_line); if (contents != expectedInitialContents) { trace_message(L"ERROR: Initial file contents does not match the expected value!\n", error_color); trace_messages(error_color, L"ERROR: Expected contents: ", error_info_color, expectedInitialContents, new_line); return ERROR_ASSERTION_FAILURE; } if (auto linkContents = read_entire_file(linkPath.c_str()); linkContents != contents) { trace_message(L"ERROR: Contents of the hard-link file do not match that of its target!\n", error_color); trace_messages(error_color, L"ERROR: Contents of the hard-link file: ", error_info_color, linkContents.c_str(), new_line); return ERROR_ASSERTION_FAILURE; } // Writing to the hard-link file should replace the contents of the target file const char* newFileContents = "You are reading the contents written to the hard-link file"; trace_messages(L"Writing to the hard-link file: ", info_color, newFileContents, new_line); if (!write_entire_file(linkPath.c_str(), newFileContents)) { return trace_last_error(L"Failed to write file contents"); } contents = read_entire_file(targetPath.c_str()); trace_messages(L"Current target file contents: ", info_color, contents.c_str(), new_line); if (contents != newFileContents) { trace_message(L"ERROR: File contents do not match!\n", error_color); return ERROR_ASSERTION_FAILURE; } return ERROR_SUCCESS; } int CreateHardLinkTests() { int result = ERROR_SUCCESS; auto otherFilePath = g_packageRootPath / L"Hářδ£ïñƙ.txt"; auto packageFilePath = g_packageRootPath / g_packageFileName; // Creating a link to a file in the package path should test/validate that we copy the package file to the // redirected location and create a link to that file (e.g. so that we can write to it) test_begin("CreateHardLink to Package File Test"); clean_redirection_path(); auto testResult = DoCreateHardLinkTest(otherFilePath, packageFilePath, g_packageFileContents); result = result ? result : testResult; test_end(testResult); // Replace the contents of the package file to ensure that we copy-on-read only if the file hasn't previously been // copied to the redirected path test_begin("CreateHardLink to Redirected File Test"); clean_redirection_path(); const char replacedFileContents[] = "You are reading from the package file in its redirected location"; write_entire_file(packageFilePath.c_str(), replacedFileContents); testResult = DoCreateHardLinkTest(otherFilePath, packageFilePath, replacedFileContents); result = result ? result : testResult; test_end(testResult); // NOTE: Ideally we'd expect failure if we try and use the path to a package file as the link path since // CreateHardLink is documented to fail if the file already exists. However, due to the limitations we // currently have surrounding deleting files, we intentionally don't handle this case at the moment, and // therefore expect it to work here test_begin("CreateHardLink Replace Package File Test"); clean_redirection_path(); const char otherFileContents[] = "You are reading from the generated file"; write_entire_file(otherFilePath.c_str(), otherFileContents); testResult = DoCreateHardLinkTest(packageFilePath, otherFilePath, otherFileContents); result = result ? result : testResult; test_end(testResult); return result; } <|start_filename|>PsfRuntime/JsonConfig.h<|end_filename|> //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #pragma once #include <unordered_map> #include <variant> #include <vector> #include <psf_config.h> struct json_null_impl : psf::json_null { }; struct json_string_impl : psf::json_string { json_string_impl(std::string_view value) : narrow_string(value), wide_string(widen(value)) {} virtual const char* narrow(_Out_opt_ unsigned* length) const noexcept override { if (length) { *length = static_cast<unsigned>(narrow_string.length()); } return narrow_string.c_str(); } virtual const wchar_t* wide(_Out_opt_ unsigned* length) const noexcept override { if (length) { *length = static_cast<unsigned>(wide_string.length()); } return wide_string.c_str(); } std::string narrow_string; std::wstring wide_string; }; struct json_number_impl : psf::json_number { template <typename T> json_number_impl(T value) : value(value) {} // NOTE: T _must_ be one of the three types used below virtual std::uint64_t get_unsigned() const noexcept override { return value_as<std::uint64_t>(); } virtual std::int64_t get_signed() const noexcept override { return value_as<std::int64_t>(); } virtual double get_float() const noexcept override { return value_as<double>(); } template <typename T> inline T value_as() const noexcept { switch (value.index()) { case 0: return static_cast<T>(std::get<std::int64_t>(value)); case 1: return static_cast<T>(std::get<std::uint64_t>(value)); case 2: return static_cast<T>(std::get<double>(value)); } assert(false); // valueless_by_exception, which shouldn't happen since construction has no business throwing return T{}; } std::variant<std::int64_t, std::uint64_t, double> value; }; struct json_boolean_impl : psf::json_boolean { json_boolean_impl(bool value) : value(value) {} virtual bool get() const noexcept override { return value; } bool value; }; struct json_object_impl : psf::json_object { using map_type = std::map<std::string, std::unique_ptr<psf::json_value>, std::less<>>; using iterator_type = map_type::const_iterator; virtual json_value* try_get(_In_ const char* key) const noexcept override { if (auto itr = values.find(key); itr != values.end()) { return itr->second.get(); } return nullptr; } // We can elide allocations if the iterator fits within the size of a pointer (which should always be the case when // building release) static constexpr bool handle_requires_allocation = sizeof(iterator_type) > sizeof(enumeration_handle*); virtual enumeration_handle* begin_enumeration(_Out_ enumeration_data* data) const noexcept override { auto itr = values.begin(); if (itr == values.end()) { *data = {}; return nullptr; } data->key = itr->first.c_str(); data->key_length = static_cast<unsigned>(itr->first.length()); data->value = itr->second.get(); if constexpr (handle_requires_allocation) { return reinterpret_cast<enumeration_handle*>(new iterator_type(itr)); } else { return handle_from_iterator(itr); } } virtual enumeration_handle* advance(_In_ enumeration_handle* handle, _Inout_ enumeration_data* data) const noexcept override { auto& itr = iterator_from_handle(handle); assert(itr != values.end()); ++itr; if (itr == values.end()) { if constexpr (handle_requires_allocation) { delete &itr; } *data = {}; return nullptr; } data->key = itr->first.c_str(); data->key_length = static_cast<unsigned>(itr->first.length()); data->value = itr->second.get(); return handle_from_iterator(itr); } virtual void cancel_enumeration(_In_ enumeration_handle* handle) const noexcept override { if constexpr (handle_requires_allocation) { delete &iterator_from_handle(handle); } } iterator_type& iterator_from_handle(enumeration_handle*& handle) const noexcept { assert(handle); if constexpr (handle_requires_allocation) { // Allocation means that the handle pointer is actually a pointer to a map iterator return *reinterpret_cast<iterator_type*>(handle); } else { // No allocation means that the handle pointer _is_ the map iterator, e.g. as if it were a union return reinterpret_cast<iterator_type&>(handle); } } enumeration_handle* handle_from_iterator(iterator_type& itr) const noexcept { assert(itr != values.end()); if constexpr (handle_requires_allocation) { // Allocation means that the handle pointer is actually a pointer to a map iterator return reinterpret_cast<enumeration_handle*>(&itr); } else { // No allocation means that the handle pointer _is_ the map iterator, e.g. as if it were a union // NOTE: We can reinterpret_cast a pointer to a reference, but not the other way around... return *reinterpret_cast<enumeration_handle**>(&itr); } } map_type values; }; struct json_array_impl : psf::json_array { virtual unsigned size() const noexcept override { return static_cast<unsigned>(values.size()); } virtual json_value* try_get_at(unsigned index) const noexcept override { if (index >= values.size()) { return nullptr; } return values[index].get(); } std::vector<std::unique_ptr<psf::json_value>> values; }; <|start_filename|>tests/fixups/MultiByteToWideCharTestFixup/MultiByteToWideCharFixup.cpp<|end_filename|> //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include <psf_framework.h> auto MultiByteToWideCharImpl = &::MultiByteToWideChar; int __stdcall MultiByteToWideCharFixup( _In_ UINT codePage, _In_ DWORD flags, _In_NLS_string_(cbMultiByte) LPCCH multiByteStr, _In_ int multiByteLength, _Out_writes_to_opt_(cchWideChar,return) LPWSTR wideCharStr, _In_ int wideCharLength) { // Only fixup the scenarios that we actually want to fixup constexpr char expectedMessage[] = "This message should have been fixed"; if ((multiByteLength == static_cast<int>(std::size(expectedMessage) - 1)) && (std::strncmp(multiByteStr, expectedMessage, multiByteLength) == 0)) { constexpr wchar_t fixedMessage[] = L"You've been fixed!"; constexpr int fixedLength = static_cast<int>(std::size(fixedMessage) - 1); if (wideCharLength >= fixedLength) { std::wcsncpy(wideCharStr, fixedMessage, fixedLength); return fixedLength; } } return MultiByteToWideCharImpl(codePage, flags, multiByteStr, multiByteLength, wideCharStr, wideCharLength); } DECLARE_FIXUP(MultiByteToWideCharImpl, MultiByteToWideCharFixup); <|start_filename|>include/known_folders.h<|end_filename|> //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #pragma once #include <cwctype> #include <filesystem> #include <windows.h> #include <combaseapi.h> #include <Shlobj.h> #include <KnownFolders.h> #include "dos_paths.h" namespace psf { struct cotaskmemfree_deleter { void operator()(wchar_t* ptr) { if (ptr) { ::CoTaskMemFree(ptr); } } }; using unique_cotaskmem_string = std::unique_ptr<wchar_t, cotaskmemfree_deleter>; inline std::filesystem::path remove_trailing_path_separators(std::filesystem::path path) { // To make string comparisons easier, don't terminate directory paths with trailing separators return path.has_filename() ? path : path.parent_path(); } inline std::filesystem::path known_folder(const GUID& id, DWORD flags = KF_FLAG_DEFAULT) { PWSTR path; if (FAILED(::SHGetKnownFolderPath(id, flags, nullptr, &path))) { throw std::runtime_error("Failed to get known folder path"); } unique_cotaskmem_string uniquePath(path); path[0] = std::towupper(path[0]); // For consistency, and therefore simplicity, ensure that all paths are drive-absolute if (auto pathType = path_type(path); (pathType == dos_path_type::root_local_device) || (pathType == dos_path_type::local_device)) { path += 4; } assert(path_type(path) == dos_path_type::drive_absolute); return remove_trailing_path_separators(path); } } <|start_filename|>tests/common/console_output.h<|end_filename|> //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #pragma once #include <optional> #include <type_traits> #include <windows.h> #include <win32_error.h> namespace console { enum class color : WORD { dark_red = FOREGROUND_RED, red = FOREGROUND_RED | FOREGROUND_INTENSITY, dark_green = FOREGROUND_GREEN, green = FOREGROUND_GREEN | FOREGROUND_INTENSITY, dark_blue = FOREGROUND_BLUE, blue = FOREGROUND_BLUE | FOREGROUND_INTENSITY, dark_magenta = FOREGROUND_RED | FOREGROUND_BLUE, magenta = FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY, dark_cyan = FOREGROUND_BLUE | FOREGROUND_GREEN, cyan = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY, dark_yellow = FOREGROUND_RED | FOREGROUND_GREEN, yellow = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY, black = 0, dark_gray = FOREGROUND_INTENSITY, gray = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE, white = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY, }; namespace details { struct set_foreground { color value; }; struct revert_foreground {}; } template <typename StreamT> struct change_foreground_t { change_foreground_t(StreamT& stream, color foreground) : m_outputStream(stream) { auto out = ::GetStdHandle(STD_OUTPUT_HANDLE); if (out == INVALID_HANDLE_VALUE) { throw_last_error(); } // NOTE: GetConsoleScreenBufferInfo can fail if we're re-directing output to a file, so ignore failures CONSOLE_SCREEN_BUFFER_INFO info; if (::GetConsoleScreenBufferInfo(out, &info)) { m_previousAttributes = info.wAttributes; m_outputStream.flush(); WORD attrib = (info.wAttributes & static_cast<WORD>(0xFF00)) | static_cast<WORD>(foreground); check_win32_bool(::SetConsoleTextAttribute(out, attrib)); } } ~change_foreground_t() { reset(); } void flush() { m_outputStream.flush(); } StreamT& reset() { if (m_previousAttributes) { if (auto out = ::GetStdHandle(STD_OUTPUT_HANDLE); out != INVALID_HANDLE_VALUE) { m_outputStream.flush(); ::SetConsoleTextAttribute(out, m_previousAttributes.value()); } } return m_outputStream; } change_foreground_t& operator<<(StreamT& (*fn)(StreamT&)) { m_outputStream << fn; return *this; } template < typename T, std::enable_if_t<!std::disjunction_v< std::is_same<std::decay_t<T>, details::set_foreground>, std::is_same<std::decay_t<T>, details::revert_foreground> >, int> = 0> change_foreground_t& operator<<(T&& arg) { m_outputStream << std::forward<T>(arg); return *this; } private: StreamT& m_outputStream; std::optional<WORD> m_previousAttributes; }; inline details::set_foreground change_foreground(color foreground) { return details::set_foreground{ foreground }; } inline details::revert_foreground revert_foreground() { return details::revert_foreground{}; } namespace details { template <typename StreamT> inline change_foreground_t<StreamT> operator<<(StreamT& stream, details::set_foreground foreground) { return change_foreground_t<StreamT>(stream, foreground.value); } template <typename StreamT> StreamT& operator<<(change_foreground_t<StreamT>& stream, details::revert_foreground) { return stream.reset(); } } } <|start_filename|>tests/scenarios/FileSystemTest/DeleteFileTest.cpp<|end_filename|> //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include <filesystem> #include <functional> #include <test_config.h> #include "common_paths.h" int DoDeleteFileTest() { auto packageFilePath = g_packageRootPath / g_packageFileName; // NOTE: Since we don't have any mechanism in place for remembering deletes to files in the package path, this test // is rather mundane. That said, the initial attempt to delete the file should at the very least appear as // though it succeeded. clean_redirection_path(); trace_messages(L"Attempting to delete the package file: ", info_color, packageFilePath.native(), new_line); if (!::DeleteFileW(packageFilePath.c_str())) { return trace_last_error(L"Attempt to delete package file failed"); } trace_message(L"Writing data to the file so that it exists in the redirected location...\n"); write_entire_file(packageFilePath.c_str(), "Redirected file contents"); auto actualPath = actual_path(packageFilePath.c_str()); trace_message(L"Deleting the file again...\n"); if (!::DeleteFileW(packageFilePath.c_str())) { return trace_last_error(L"Attempt to delete redirected file failed"); } else if (std::filesystem::exists(actualPath)) { trace_message(L"ERROR: DeleteFile returned success, but the redirected file still exists\n", error_color); trace_messages(error_color, L"ERROR: Redirected file path: ", error_info_color, actualPath.native(), new_line); return ERROR_ASSERTION_FAILURE; } return ERROR_SUCCESS; } int DeleteFileTests() { test_begin("DeleteFile Test"); auto result = DoDeleteFileTest(); test_end(result); return result; } <|start_filename|>tests/common/test_runner.h<|end_filename|> //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #pragma once #include <chrono> #include <cstdint> #include <memory> #include <string_view> #include <fancy_handle.h> #include "console_output.h" #include "offset_ptr.h" static constexpr wchar_t test_runner_pipe_name[] = LR"(\\.\pipe\CentennialFixupsTests)"; using unique_handle = std::unique_ptr<void, psf::handle_deleter<::CloseHandle>>; inline unique_handle test_client_connect() { using namespace std::literals; constexpr auto waitTimeout = std::chrono::duration_cast<std::chrono::milliseconds>(20s); unique_handle result; while (!result) { if (!::WaitNamedPipeW(test_runner_pipe_name, static_cast<DWORD>(waitTimeout.count()))) { print_last_error("Failed waiting for named pipe to become available"); break; } else { // Pipe is available. Try and connect to it. Note that we could fail if someone else beats us, but that's // okay. We shouldn't get starved since there's a finite number of tests result.reset(::CreateFileW( test_runner_pipe_name, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr)); } } return result; } enum class test_message_type : std::int16_t { init, cleanup, begin, end, trace, }; struct test_message { test_message_type type; std::int32_t size; // Size, in bytes, of the complete message }; inline const test_message* advance(const test_message* msg) noexcept { return reinterpret_cast<const test_message*>(reinterpret_cast<const std::uint8_t*>(msg) + msg->size); } struct init_test_message { test_message header = { test_message_type::init }; offset_ptr<char> name; std::int32_t count = 0; // Number of tests }; struct cleanup_test_message { test_message header = { test_message_type::cleanup }; }; struct test_begin_message { test_message header = { test_message_type::begin }; offset_ptr<char> name; }; struct test_end_message { test_message header = { test_message_type::end }; std::int32_t result = 0; }; struct test_trace_message { test_message header = { test_message_type::trace }; offset_ptr<wchar_t> text; console::color color = console::color::gray; std::int8_t print_new_line = false; // NOTE: Interpreted as a boolean value }; <|start_filename|>tests/TestRunner/message_pipe.h<|end_filename|> //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #pragma once #include <memory> #include <error_logging.h> #include <fancy_handle.h> #include <test_runner.h> enum class pipe_state { disconnected, connecting, connected }; class message_pipe { public: message_pipe() { m_buffer = std::make_unique<char[]>(m_bufferCapacity); m_pipeHandle.reset(::CreateNamedPipeW( test_runner_pipe_name, PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE, PIPE_UNLIMITED_INSTANCES, // MaxInstances 2048, // OutBufferSize 2048, // InBufferSize 0, // DefaultTimeOut (defaults to 50ms) nullptr)); if (!m_pipeHandle) { throw_win32(print_last_error("Failed to create named pipe")); } m_pipeEvent.reset(::CreateEventW(nullptr, true, false, nullptr)); if (!m_pipeEvent) { throw_win32(print_last_error("Failed to create event")); } m_overlapped.hEvent = m_pipeEvent.get(); InitiateConnection(); } pipe_state state() const noexcept { return m_state; } HANDLE wait_handle() const noexcept { return m_pipeEvent.get(); } template <typename Handler> // void(const test_message*) void on_signalled(Handler&& handler) { ::ResetEvent(m_pipeEvent.get()); if (m_state == pipe_state::connecting) { m_state = pipe_state::connected; InitiateRead(); return; } assert(m_state == pipe_state::connected); DWORD bytesRead; if (!::GetOverlappedResult(m_pipeHandle.get(), &m_overlapped, &bytesRead, false)) { if (::GetLastError() != ERROR_BROKEN_PIPE) { throw_win32(print_last_error("Failed to read from pipe")); } // Failure was because of client disconnecting. Disconnect and start listening for a new client InitiateReconnect(); return; } // We got signalled because we got more data m_bufferSize += bytesRead; auto msg = reinterpret_cast<const test_message*>(m_buffer.get()); if ((m_bufferSize >= sizeof(test_message)) && (m_bufferSize >= static_cast<DWORD>(msg->size))) { while ((m_bufferSize >= sizeof(test_message)) && (m_bufferSize >= static_cast<DWORD>(msg->size))) { handler(msg); m_bufferSize -= msg->size; msg = advance(msg); } std::memmove(m_buffer.get(), msg, m_bufferSize); } InitiateRead(); } private: void InitiateConnection() { assert(m_state == pipe_state::disconnected); [[maybe_unused]] auto result = ::ConnectNamedPipe(m_pipeHandle.get(), &m_overlapped); assert(!result); switch (::GetLastError()) { case ERROR_IO_PENDING: // Completing asynchronously m_state = pipe_state::connecting; break; case ERROR_PIPE_CONNECTED: // Client has already connected to the pipe m_state = pipe_state::connected; InitiateRead(); break; default: throw_win32(print_last_error("Failed to wait for client to connect to pipe")); } } void InitiateRead() { assert(m_state == pipe_state::connected); auto readResult = ::ReadFile( m_pipeHandle.get(), m_buffer.get() + m_bufferSize, m_bufferCapacity - m_bufferSize, nullptr, &m_overlapped); if (!readResult) { switch (::GetLastError()) { case ERROR_IO_PENDING: // This is the expected result. Nothing to do break; case ERROR_BROKEN_PIPE: // Pipe has been closed by the client. Open the pipe for use by other consumers InitiateReconnect(); break; default: throw_win32(print_last_error("Failed reading data from pipe")); } } else { assert(HasOverlappedIoCompleted(&m_overlapped)); } } void InitiateReconnect() { assert(m_state == pipe_state::connected); if (!::DisconnectNamedPipe(m_pipeHandle.get())) { throw_win32(print_last_error("Failed to disconnect the pipe from the client")); } m_state = pipe_state::disconnected; InitiateConnection(); } unique_handle m_pipeHandle; unique_handle m_pipeEvent; OVERLAPPED m_overlapped = {}; pipe_state m_state = pipe_state::disconnected; DWORD m_bufferCapacity = 2048; DWORD m_bufferSize = 0; std::unique_ptr<char[]> m_buffer; }; <|start_filename|>tests/scenarios/FileSystemTest/attributes.h<|end_filename|> //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #pragma once #include <windows.h> static constexpr bool flag_set(DWORD value, DWORD flag) { return (value & flag) == flag; } static std::wstring file_attributes(DWORD value) { std::wstring result; const wchar_t* prefix = L""; auto test_flag = [&](DWORD flag, const wchar_t* name) { if (flag_set(value, flag)) { result += prefix; result += name; prefix = L" | "; } }; test_flag(FILE_ATTRIBUTE_READONLY, L"FILE_ATTRIBUTE_READONLY"); test_flag(FILE_ATTRIBUTE_HIDDEN, L"FILE_ATTRIBUTE_HIDDEN"); test_flag(FILE_ATTRIBUTE_SYSTEM, L"FILE_ATTRIBUTE_SYSTEM"); test_flag(FILE_ATTRIBUTE_DIRECTORY, L"FILE_ATTRIBUTE_DIRECTORY"); test_flag(FILE_ATTRIBUTE_ARCHIVE, L"FILE_ATTRIBUTE_ARCHIVE"); test_flag(FILE_ATTRIBUTE_DEVICE, L"FILE_ATTRIBUTE_DEVICE"); test_flag(FILE_ATTRIBUTE_NORMAL, L"FILE_ATTRIBUTE_NORMAL"); test_flag(FILE_ATTRIBUTE_TEMPORARY, L"FILE_ATTRIBUTE_TEMPORARY"); test_flag(FILE_ATTRIBUTE_SPARSE_FILE, L"FILE_ATTRIBUTE_SPARSE_FILE"); test_flag(FILE_ATTRIBUTE_REPARSE_POINT, L"FILE_ATTRIBUTE_REPARSE_POINT"); test_flag(FILE_ATTRIBUTE_COMPRESSED, L"FILE_ATTRIBUTE_COMPRESSED"); test_flag(FILE_ATTRIBUTE_OFFLINE, L"FILE_ATTRIBUTE_OFFLINE"); test_flag(FILE_ATTRIBUTE_NOT_CONTENT_INDEXED, L"FILE_ATTRIBUTE_NOT_CONTENT_INDEXED"); test_flag(FILE_ATTRIBUTE_ENCRYPTED, L"FILE_ATTRIBUTE_ENCRYPTED"); test_flag(FILE_ATTRIBUTE_INTEGRITY_STREAM, L"FILE_ATTRIBUTE_INTEGRITY_STREAM"); test_flag(FILE_ATTRIBUTE_VIRTUAL, L"FILE_ATTRIBUTE_VIRTUAL"); test_flag(FILE_ATTRIBUTE_NO_SCRUB_DATA, L"FILE_ATTRIBUTE_NO_SCRUB_DATA"); test_flag(FILE_ATTRIBUTE_EA, L"FILE_ATTRIBUTE_EA"); test_flag(FILE_ATTRIBUTE_PINNED, L"FILE_ATTRIBUTE_PINNED"); test_flag(FILE_ATTRIBUTE_UNPINNED, L"FILE_ATTRIBUTE_UNPINNED"); test_flag(FILE_ATTRIBUTE_RECALL_ON_OPEN, L"FILE_ATTRIBUTE_RECALL_ON_OPEN"); test_flag(FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS, L"FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS"); #ifdef FILE_ATTRIBUTE_STRICTLY_SEQUENTIAL test_flag(FILE_ATTRIBUTE_STRICTLY_SEQUENTIAL, L"FILE_ATTRIBUTE_STRICTLY_SEQUENTIAL"); #endif return result; } <|start_filename|>samples/PSFSample/PSFSampleApp/Form1.cs<|end_filename|> //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace GameWithCommonIssues { public partial class PSFSample : Form { string exePath = ""; public PSFSample() { InitializeComponent(); } private void PSFSample_Load(object sender, EventArgs e) { string result = System.Reflection.Assembly.GetExecutingAssembly().Location; int index = result.LastIndexOf("\\"); exePath = result.Substring(0, index); label1.Text = exePath; label2.Text = Environment.CurrentDirectory; } private void buttonReadConfig_Click(object sender, EventArgs e) { try { System.IO.File.OpenRead("Config.txt"); MessageBox.Show("SUCCESS", "App Message"); } catch (Exception exc) { MessageBox.Show(exc.ToString(), "App Message"); } } private void buttonWriteLog_Click(object sender, EventArgs e) { string newFileName = exePath + "\\" + Guid.NewGuid().ToString() + ".log"; try { System.IO.File.CreateText(newFileName); MessageBox.Show("SUCCESS", "App Message"); } catch (Exception exc) { MessageBox.Show(exc.ToString(), "App Message"); } } } } <|start_filename|>tests/scenarios/FileSystemTest/common_paths.h<|end_filename|> //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #pragma once #include <algorithm> #include <filesystem> #include <known_folders.h> #include <windows.h> #include <file_paths.h> struct vfs_mapping { std::filesystem::path path; std::filesystem::path package_path; }; // All files placed in the package path have the same initial contents constexpr const char g_packageFileContents[] = "You are reading from the package path"; constexpr const wchar_t g_packageFileName[] = L"ÞáçƙáϱèFïℓè.txt"; inline std::filesystem::path g_packageRootPath; inline vfs_mapping g_systemX86Mapping; inline vfs_mapping g_programFilesX86Mapping; inline vfs_mapping g_programFilesCommonX86Mapping; #if !_M_IX86 inline vfs_mapping g_systemX64Mapping; inline vfs_mapping g_programFilesX64Mapping; inline vfs_mapping g_programFilesCommonX64Mapping; #endif inline vfs_mapping g_windowsMapping; inline vfs_mapping g_commonAppDataMapping; inline vfs_mapping g_system32CatrootMapping; inline vfs_mapping g_system32Catroot2Mapping; inline vfs_mapping g_system32DriversEtcMapping; inline vfs_mapping g_system32DriverStoreMapping; inline vfs_mapping g_system32LogFilesMapping; inline vfs_mapping g_system32SpoolMapping; inline const std::reference_wrapper<const vfs_mapping> g_vfsMappings[] = { g_systemX86Mapping, g_programFilesX86Mapping, g_programFilesCommonX86Mapping, #if !_M_IX86 g_systemX64Mapping, g_programFilesX64Mapping, g_programFilesCommonX64Mapping, #endif g_windowsMapping, g_commonAppDataMapping, g_system32CatrootMapping, g_system32Catroot2Mapping, g_system32DriversEtcMapping, g_system32DriverStoreMapping, g_system32LogFilesMapping, g_system32SpoolMapping, }; inline std::wstring test_filename(const vfs_mapping& mapping) { auto result = mapping.package_path.filename().native() + L"Fïℓè.txt"; // Remove any spaces result.erase(std::remove(result.begin(), result.end(), ' '), result.end()); // Remove 'AppVSystem32' prefix, if present constexpr std::wstring_view appvSystem32Prefix = L"AppVSystem32"; if (std::wstring_view(result).substr(0, appvSystem32Prefix.length()) == appvSystem32Prefix) { result.erase(0, appvSystem32Prefix.length()); } return result; } inline std::filesystem::path actual_path(HANDLE file) { auto len = ::GetFinalPathNameByHandleW(file, nullptr, 0, 0); if (!len) { return {}; } std::wstring result(len - 1, '\0'); len = ::GetFinalPathNameByHandleW(file, result.data(), len, 0); if (!len) { return {}; } assert(len <= result.length()); result.resize(len); return result; } inline std::filesystem::path actual_path(const wchar_t* path) { auto handle = ::CreateFileW(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (handle == INVALID_HANDLE_VALUE) { return {}; } try { auto result = actual_path(handle); ::CloseHandle(handle); return result; } catch (...) { ::CloseHandle(handle); throw; } }
ArianGhotbiMSFT/MSIX-PackageSupportFramework
<|start_filename|>src/assets/data/awesome.js<|end_filename|> export default [{ key: "books", icon: "book", name: "阅读", awesomes: [{ name: "A gentle guide to asynchronous programming with Eclipse Vert.x for Java developers", author: [ "<NAME>", "<NAME>", "<NAME>" ], tag: [], description: "", url: "http://vertx.io/docs/guide-for-java-devs/" }, { name: "Building Reactive Microservices in Java", author: [ "<NAME>" ], tag: [], description: "", url: "https://developers.redhat.com/promotions/building-reactive-microservices-in-java/" }, { name: "<NAME>", author: [ "<NAME>" ], tag: [], description: "", url: "https://www.manning.com/books/vertx-in-action" } ], awesomeGroups: [] }, { key: "build-tools", icon: "build", name: "构建", awesomes: [{ name: "Vert.x Maven plugin", author: [], tag: [], description: "", url: "https://github.com/reactiverse/vertx-maven-plugin" }, { name: "Vert.x Gradle plugin", author: [], tag: [], description: "", url: "https://plugins.gradle.org/plugin/io.vertx.vertx-plugin" }, { name: "Vert.x Codegen Gradle plugin", author: [], tag: [], description: "A Gradle plugin to facilitate the codegen usage for Vert.x Java projects", url: "https://plugins.gradle.org/plugin/io.vertx.vertx-plugin" } ], awesomeGroups: [] }, { key: "web-frameworks", icon: "api", name: "Web框架", awesomes: [{ name: "Vert.x Web", author: [], tag: [], description: "Full featured web toolkit for Vert.x.", url: "https://github.com/vert-x3/vertx-web" }, { name: "Vert.x Jersey", author: [], tag: [], description: "Create JAX-RS Jersey resources in Vert.x.", url: "https://github.com/englishtown/vertx-jersey" }, { name: "Kovert", author: [], tag: [], description: "Invisible REST framework for Kotlin + Vert.x Web.", url: "https://github.com/kohesive/kovert" }, { name: "Handlers", author: [], tag: [], description: "Open web framework for Vert.x.", url: "https://github.com/spriet2000/vertx-handlers-http" }, { name: "QBit", author: [], tag: [], description: "REST and WebSocket method call marshaling and reactive library.", url: "https://github.com/advantageous/qbit" }, { name: "vertx-rest-storage", author: [], tag: [], description: "Persistence for REST resources in the filesystem or a redis database.", url: "https://github.com/swisspush/vertx-rest-storage" }, { name: "Jubilee", author: [], tag: [], description: "A rack compatible Ruby HTTP server built on Vert.x 3.", url: "https://github.com/isaiah/jubilee" }, { name: "Knot.x", author: [], tag: [], description: "Efficient & high-performance integration platform for modern websites built on Vert.x 3.", url: "https://github.com/Cognifide/knotx" }, { name: "Vert.x Jspare", author: [], tag: [], description: "Improving your Vert.x 3 experience with Jspare Framework.", url: "https://github.com/jspare-projects/vertx-jspare" }, { name: "Irked", author: [], tag: [], description: "Annotations-based configuration for Vert.x 3 Web and controller framework.", url: "https://github.com/GreenfieldTech/irked" }, { name: "REST.VertX", author: [], tag: [], description: "Lightweight JAX-RS (RestEasy) like annotation processor for Vert.x verticals.", url: "https://github.com/zandero/rest.vertx" }, { name: "Atmosphere Vert.x ", author: [], tag: [], description: "Realtime Client Server Framework for the JVM, supporting WebSockets and Server Sent Events with Cross-Browser Fallbacks.", url: "https://github.com/Atmosphere/atmosphere-vertx" }, { name: "Vert.x Vaadin", author: [], tag: [], description: "Run Vaadin applications on Vert.x.", url: "https://github.com/mcollovati/vertx-vaadin" }, { name: "Serverx", author: [], tag: [], description: "Allows you to quickly and easily set up a Vert.x-powered server using only route handler annotations.", url: "https://github.com/lukehutch/server" } ], awesomeGroups: [] }, { key: "authentication-authorisation", icon: "safety", name: "认证与授权", awesomes: [], awesomeGroups: [] }, { key: "database-clients", icon: "database", name: "数据库客户端", awesomes: [], awesomeGroups: [] } ] <|start_filename|>src/store.js<|end_filename|> import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex); const USER_INFO_LOCAL_STORAGE_KEY ='loggedInUserInfo'; const PERSON_INDEX_USER_SESSION_STORAGE_KEY = "personalIndexFlag"; const EDIT_ARTICLE_FLAG = "editArticleFlag"; const EDIT_ARTICLE = "editArticle"; const USER_CACHE = "userCache"; export default new Vuex.Store({ state: { //从localStorage中获取用户信息 如果有 则处于登录状态 loggedInUserInfo: localStorage.getItem(USER_INFO_LOCAL_STORAGE_KEY) ? JSON.parse(localStorage.getItem(USER_INFO_LOCAL_STORAGE_KEY)) : null, //用于标记personalPage显示的用户 selfIndex:sessionStorage.getItem(PERSON_INDEX_USER_SESSION_STORAGE_KEY) == null ? false : sessionStorage.getItem(PERSON_INDEX_USER_SESSION_STORAGE_KEY) === "true", //用于标记是否为编辑状态的帖子 editArticleFlag: sessionStorage.getItem(EDIT_ARTICLE_FLAG) == null ? false : sessionStorage.getItem(EDIT_ARTICLE_FLAG) === "true", editArticle: sessionStorage.getItem(EDIT_ARTICLE) ? JSON.parse(sessionStorage.getItem(EDIT_ARTICLE)) : null, userCache : localStorage.getItem(USER_CACHE) ? JSON.parse(localStorage.getItem(USER_CACHE)) : {} }, getters:{ loggedIn: (state) => { return state.loggedInUserInfo; }, userBriefById : (state) => (id) => { return state.userCache[id]; } }, mutations: { addUserBriefToCache(state, userBrief){ let cacheJsonStr = localStorage.getItem(USER_CACHE); if (!cacheJsonStr) { //add user brief info to local-storage and vuex-store let ub = {}; ub[userBrief.id] = userBrief; localStorage.setItem(USER_CACHE,JSON.stringify(ub)); }else { let cachedObj = JSON.parse(cacheJsonStr); cachedObj[userBrief.id] = userBrief; localStorage.setItem(USER_CACHE,JSON.stringify(cachedObj)); } state.userCache[userBrief.id] = userBrief; }, //登录操作 doLogin(state,userInfo){ localStorage.setItem(USER_INFO_LOCAL_STORAGE_KEY,JSON.stringify(userInfo)); state.loggedInUserInfo = userInfo; }, //注销登录操作 doLogoff(state){ state.loggedInUserInfo = null; localStorage.removeItem(USER_INFO_LOCAL_STORAGE_KEY); }, setSelfIndex(state,flag){ sessionStorage.setItem(PERSON_INDEX_USER_SESSION_STORAGE_KEY,""+flag); state.selfIndex = flag; }, setEditArticleFlag(state,flag){ sessionStorage.setItem(EDIT_ARTICLE_FLAG,""+flag); state.editArticleFlag = flag; }, setEditArticle(state,article){ if (article){ sessionStorage.setItem(EDIT_ARTICLE,JSON.stringify(article)); state.editArticle = article; } else{ sessionStorage.removeItem(EDIT_ARTICLE); state.editArticle = null; } } }, actions: { } }) <|start_filename|>src/main.js<|end_filename|> import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' import './plugins/ant-design-vue' import './plugins/lottie' import './plugins/markdown' import './plugins/request' import nprogress from './plugins/nprogress' import Icon from './components/Icon' import i18n from './plugins/i18n' let requireAll = requireContext => requireContext.keys().map(requireContext); const req = require.context('./assets/icons', false, /\.svg$/); requireAll(req); Vue.use(Icon); Vue.config.productionTip = false; new Vue({ router, store, nprogress, i18n, render: h => h(App) }).$mount('#app'); <|start_filename|>src/plugins/markdown.js<|end_filename|> import Vue from 'vue'; import mavonEditor from 'mavon-editor' import 'mavon-editor/dist/css/index.css' import VueSimpleMarkdown from 'vue-simple-markdown' // You need a specific loader for CSS files like https://github.com/webpack/css-loader import 'vue-simple-markdown/dist/vue-simple-markdown.css' // index.vue code-block highlight import 'highlight.js/styles/github-gist.css' let markdownIt = mavonEditor.markdownIt; markdownIt.set({html:false}); Vue.use(mavonEditor); Vue.use(VueSimpleMarkdown); <|start_filename|>src/plugins/lottie.js<|end_filename|> "use strict"; import Vue from 'vue'; import lottie from 'vue-lottie'; Vue.component('lottie', lottie) <|start_filename|>src/router.js<|end_filename|> import Vue from 'vue' import Router from 'vue-router' import Layout from './layout/index.vue' // import Index from './views/index.vue' import Publish from './views/publish/index.vue' import Document from './views/document/index.vue' import Community from './views/community/index.vue' import Awesome from './views/awesome/index.vue' import Error from './views/common/error-pages/error' import NotFound from './views/common/error-pages/not-found-404' import Login from './views/common/login/login' import Register from './views/common/register/register' import Publications from './views/community/publications/publications' import MyCollect from './views/community/my-collect/my-collect' import MyFollowing from './views/community/my-following/my-following' import MyMsg from './views/community/my-msg/my-msg' import ServiceCenter from './views/community/service-center/service-center' import PubArticle from './views/community/pub-article/pub-article' import PersonalPage from './views/community/personal-page/personal-page' import PersonalEdit from './views/community/personal-edit/personal-edit' Vue.use(Router) export default new Router({ routes: [{ path: '/', name: 'Layout', component: Layout, children: [ // abandon original index { path: '/', name: 'Index', component: Document, }, { path: '/publish', name: 'Publish', component: Publish, }, { path: '/document', name: 'Document', component: Document, }, { path: '/community', name: 'Community', component: Community, children: [ { path: 'publications', component: Publications },{ path: 'my-collect', component: MyCollect },{ path: 'my-following', component: MyFollowing },{ path: 'my-msg', component: MyMsg },{ path: 'service-center', component: ServiceCenter },{ path: 'personal-page', component: PersonalPage },{ path: 'pub-article', component: PubArticle },{ path: 'personal-edit', component: PersonalEdit } ] }, { path: '/awesome', name: 'Awesome', component: Awesome, }, { path: '/error', name: 'Error', component: Error, },{ path: '/not-found', name: 'NotFound', component: NotFound, },{ path: '/login', name: 'Login', component: Login, },{ path: '/register', name: 'Register', component: Register, }] }] }) <|start_filename|>src/plugins/nprogress.js<|end_filename|> "use strict"; import Vue from 'vue'; import NProgress from 'vue-nprogress' const options = { latencyThreshold: 200, // Number of ms before progressbar starts showing, default: 100, router: true, // Show progressbar when navigating routes, default: true http: false // Show progressbar when doing Vue.http, default: true }; Vue.use(NProgress, options) const nprogress = new NProgress() export default nprogress
zf1976/social-vertex-website
<|start_filename|>integration_tests/send-metrics.js<|end_filename|> const { datadog, sendDistributionMetric } = require("datadog-lambda-js"); async function handle(event, context) { const responsePayload = { message: "hello, dog!" }; if (event.requestContext) { responsePayload.eventType = "APIGateway"; responsePayload.requestId = event.requestContext.requestId; } if (event.Records) { responsePayload.recordIds = []; event.Records.forEach((record) => { if (record.messageId) { responsePayload.eventType = "SQS"; responsePayload.recordIds.push(record.messageId); sendDistributionMetric( "serverless.integration_test.records_processed", 1, "tagkey:tagvalue", `eventsource:${responsePayload.eventType}`, ); } if (record.Sns) { responsePayload.eventType = "SNS"; responsePayload.recordIds.push(record.Sns.MessageId); sendDistributionMetric( "serverless.integration_test.records_processed", 1, "tagkey:tagvalue", `eventsource:${responsePayload.eventType}`, ); } }); } sendDistributionMetric( "serverless.integration_test.execution", 1, "tagkey:tagvalue", `eventsource:${responsePayload.eventType}`, ); console.log(`Processed ${responsePayload.eventType} request`); return responsePayload; } module.exports.handle = datadog(handle);
Next-Interactive/datadog-lambda-layer-js
<|start_filename|>tests/tnoverrun.c<|end_filename|> /* * Copyright 2011-2015 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <np.h> #include <stdio.h> #include <malloc.h> void do_a_small_overrun(char *buf) { strcpy(buf, "012345678901234567890123456789012"); } #if 0 /* This generates a vgcore, which is inconvenient */ static void test_stack_overrun_small(void) { char buf[32]; fprintf(stderr, "MSG about to overrun a buffer by a small amount\n"); do_a_small_overrun(buf); fprintf(stderr, "MSG overran\n"); } #endif static void test_heap_overrun_small(void) { char *buf = malloc(32); fprintf(stderr, "MSG about to overrun a buffer by a small amount\n"); do_a_small_overrun(buf); fprintf(stderr, "MSG overran\n"); free(buf); } #if 0 /* Valgrind doesn't detect overruns of static buffers */ static void test_static_overrun_small(void) { static char buf[32]; fprintf(stderr, "MSG about to overrun a buffer by a small amount\n"); do_a_small_overrun(buf); fprintf(stderr, "MSG overran\n"); } #endif <|start_filename|>np_priv.h<|end_filename|> /* * Copyright 2011-2012 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __NP_PRIV_H__ #define __NP_PRIV_H__ 1 #include "np/util/common.hxx" #include "np.h" #include "np/spiegel/spiegel.hxx" #include "np/spiegel/dwarf/state.hxx" #include "np/spiegel/platform/common.hxx" #include "np/util/filename.hxx" #include <vector> #include <list> #include <string> #include "np/types.hxx" #include "np/classifier.hxx" #include "np/child.hxx" #include "np/testnode.hxx" #include "np/listener.hxx" #include "np/text_listener.hxx" #include "np/proxy_listener.hxx" #include "np/plan.hxx" #include "np/testmanager.hxx" #include "np/redirect.hxx" #include "np/runner.hxx" extern void __np_terminate_handler(void); #endif /* __NP_PRIV_H__ */ <|start_filename|>tests/tnuninit.c<|end_filename|> /* * Copyright 2011-2015 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <unistd.h> #include <np.h> int function_one(int *ip) { return 42 + *ip; } static void test_uninitialized_int(void) { int never_initted; int x = function_one(&never_initted); static const char hexdigits[16] = "0123456789abcdef"; char buf[8] = "0xXXXX\n"; buf[2] = hexdigits[(x >> 12) & 0xf]; buf[3] = hexdigits[(x >> 8) & 0xf]; buf[4] = hexdigits[(x >> 4) & 0xf]; buf[5] = hexdigits[(x) & 0xf]; write(2, buf, 7); } <|start_filename|>doc/internal/mocking-experiments/Makefile<|end_filename|> PROGRAMS= \ foo \ bar \ baz \ quux \ all: $(PROGRAMS) CC= gcc CFLAGS= -Wall -g %: %.c $(LINK.c) -o $@ $< clean: $(RM) $(PROGRAMS) <|start_filename|>tests/tndynmock3.c<|end_filename|> /* * Copyright 2011-2012 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <np.h> #include <stdio.h> #include <stdlib.h> /* * Test for dynamic mocking derived from an example suggested by * <NAME> on the mailing list. Demonstrates using a * single mock function for every test in a .c file by installing * it during the setup function. */ int get_value(void) { return 0; } int find_answer(void) { return get_value() + 42; } static int return_100(void) { return 100; } static int setup(void) { np_mock(get_value, return_100); return 0; } static void test_one(void) { int answer; answer = find_answer(); NP_ASSERT_EQUAL(142, answer); } static void test_two(void) { int answer; answer = find_answer(); NP_ASSERT_EQUAL(142, answer); } static void test_three(void) { int answer; answer = find_answer(); NP_ASSERT_EQUAL(142, answer); } <|start_filename|>tests/d-globfunc.cxx<|end_filename|> /* * Copyright 2011-2012 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ struct coffee { int mcsweeneys; }; struct quinoa { int cosby; float sweater; struct coffee *milkshk; }; struct coffee *keffiyeh = 0; static int sartorial = 42; int dreamcatcher(struct quinoa *q) { return q->cosby + sartorial; } int main(int argc, char **argv) { return 0; } <|start_filename|>tests/tnbug20.c<|end_filename|> #include <inttypes.h> #include <np.h> #include <stdio.h> /* test code contributed by bernieh-atlnz https://github.com/novaprova/novaprova/issues/20 */ int called = 0; uint64_t m_func(void) { called = 2; return 0xa1a2a3a4a5a6a7a8LL; } uint64_t func(void) { called = 1; return 0x0102030405060708LL; } void test_uint64_bug(void) { np_mock(func, m_func); uint64_t asdf = func(); NP_ASSERT_EQUAL(asdf, 0xa1a2a3a4a5a6a7a8LL); NP_ASSERT_EQUAL(called, 2); } <|start_filename|>build/obs/test-ifdef/Makefile<|end_filename|> # # Copyright 2011-2015 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # all: run-tests TESTS= $(patsubst %.args,%,$(wildcard *.args)) run-tests: @nfailed=0 ; for test in $(TESTS) ; do \ res=FAIL ;\ ../ifdef.py `cat $$test.args` < $$test.in > $$test.out ;\ diff -u $$test.out $$test.exp && res=PASS ;\ echo "$$res $$test" ;\ if [ $$res == FAIL ]; then nfailed=`expr $$nfailed + 1` ; fi ;\ done ; echo "$$nfailed failures"
juewuer/novaprova
<|start_filename|>format-delimited/src/main/java/io/cdap/plugin/format/delimited/input/DelimitedConfig.java<|end_filename|> /* * Copyright © 2021 <NAME>, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package io.cdap.plugin.format.delimited.input; import com.google.common.base.Strings; import io.cdap.cdap.api.annotation.Description; import io.cdap.cdap.api.annotation.Macro; import io.cdap.cdap.api.data.schema.Schema; import io.cdap.cdap.api.dataset.lib.KeyValue; import io.cdap.cdap.api.plugin.PluginPropertyField; import io.cdap.cdap.etl.api.validation.FormatContext; import io.cdap.plugin.common.KeyValueListParser; import io.cdap.plugin.common.batch.JobUtils; import io.cdap.plugin.format.delimited.common.DataTypeDetectorStatusKeeper; import io.cdap.plugin.format.delimited.common.DataTypeDetectorUtils; import io.cdap.plugin.format.input.PathTrackingConfig; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.Job; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Nullable; /** * Common config for delimited related formats. */ public class DelimitedConfig extends PathTrackingConfig { // properties public static final String NAME_DELIMITER = "delimiter"; public static final String NAME_ENABLE_QUOTES_VALUES = "enableQuotedValues"; public static final String NAME_FORMAT = "format"; public static final String NAME_OVERRIDE = "override"; public static final String NAME_SAMPLE_SIZE = "sampleSize"; public static final String NAME_PATH = "path"; public static final String NAME_REGEX_PATH_FILTER = "fileRegex"; public static final Map<String, PluginPropertyField> DELIMITED_FIELDS; // description public static final String DESC_ENABLE_QUOTES = "Whether to treat content between quotes as a value. The default value is false."; public static final String DESC_SKIP_HEADER = "Whether to skip the first line of each file. The default value is false."; static { Map<String, PluginPropertyField> fields = new HashMap<>(FIELDS); fields.put("skipHeader", new PluginPropertyField("skipHeader", DESC_SKIP_HEADER, "boolean", false, true)); fields.put(NAME_ENABLE_QUOTES_VALUES, new PluginPropertyField(NAME_ENABLE_QUOTES_VALUES, DESC_ENABLE_QUOTES, "boolean", false, true)); DELIMITED_FIELDS = Collections.unmodifiableMap(fields); } @Macro @Nullable @Description(DESC_SKIP_HEADER) private Boolean skipHeader; @Macro @Nullable @Description(DESC_ENABLE_QUOTES) protected Boolean enableQuotedValues; public boolean getSkipHeader() { return skipHeader == null ? false : skipHeader; } public boolean getEnableQuotedValues() { return enableQuotedValues == null ? false : enableQuotedValues; } public Long getSampleSize() { return Long.parseLong(getProperties().getProperties().getOrDefault(NAME_SAMPLE_SIZE, "1000")); } @Nullable @Override public Schema getSchema() { if (containsMacro(NAME_SCHEMA)) { return null; } if (Strings.isNullOrEmpty(schema)) { try { return getDefaultSchema(null); } catch (IOException e) { throw new IllegalArgumentException("Invalid schema: " + e.getMessage(), e); } } return super.getSchema(); } /** * Reads delimiter from config. If not available returns default delimiter based on format. * * @return delimiter */ private String getDefaultDelimiter() { String delimiter = getProperties().getProperties().get(NAME_DELIMITER); if (delimiter != null) { return delimiter; } final String format = getProperties().getProperties().get(NAME_FORMAT); switch (format) { case "tsv": return "\t"; default: return ","; } } /** * Parses a list of key-value items of column names and their corresponding data types, manually set by the user. * * @return A hashmap of column names and their manually set schemas. */ public HashMap<String, Schema> getOverride() throws IllegalArgumentException { String override = getProperties().getProperties().get(NAME_OVERRIDE); HashMap<String, Schema> overrideDataTypes = new HashMap<>(); KeyValueListParser kvParser = new KeyValueListParser("\\s*,\\s*", ":"); if (!Strings.isNullOrEmpty(override)) { for (KeyValue<String, String> keyVal : kvParser.parse(override)) { String name = keyVal.getKey(); String stringDataType = keyVal.getValue(); Schema schema = null; switch (stringDataType) { case "date": schema = Schema.of(Schema.LogicalType.DATE); break; case "time": schema = Schema.of(Schema.LogicalType.TIME_MICROS); break; case "timestamp": schema = Schema.of(Schema.LogicalType.TIMESTAMP_MICROS); break; default: schema = Schema.of(Schema.Type.valueOf(stringDataType.toUpperCase())); } if (overrideDataTypes.containsKey(name)) { throw new IllegalArgumentException(String.format("Cannot convert '%s' to multiple types.", name)); } overrideDataTypes.put(name, schema); } } return overrideDataTypes; } /** * Gets the detected schema. * * @param context {@link FormatContext} * @return The detected schema. * @throws IOException If the data can't be read from the datasource. */ public Schema getDefaultSchema(@Nullable FormatContext context) throws IOException { final String format = getProperties().getProperties().getOrDefault(NAME_FORMAT, "delimited"); String delimiter = getDefaultDelimiter(); String regexPathFilter = getProperties().getProperties().get(NAME_REGEX_PATH_FILTER); String path = getProperties().getProperties().get(NAME_PATH); if (format.equals("delimited") && Strings.isNullOrEmpty(delimiter)) { throw new IllegalArgumentException("Delimiter is required when format is set to 'delimited'."); } Job job = JobUtils.createInstance(); Configuration configuration = job.getConfiguration(); for (Map.Entry<String, String> entry : getFileSystemProperties().entrySet()) { configuration.set(entry.getKey(), entry.getValue()); } Path filePath = getFilePathForSchemaGeneration(path, regexPathFilter, configuration, job); DataTypeDetectorStatusKeeper dataTypeDetectorStatusKeeper = new DataTypeDetectorStatusKeeper(); String line = null; String[] columnNames = null; String[] rowValue = null; try (FileSystem fileSystem = JobUtils.applyWithExtraClassLoader(job, getClass().getClassLoader(), f -> FileSystem.get(filePath.toUri(), configuration)); FSDataInputStream input = fileSystem.open(filePath); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input)); ) { for (int rowIndex = 0; rowIndex < getSampleSize() && (line = bufferedReader.readLine()) != null; rowIndex++) { rowValue = line.split(delimiter, -1); if (rowIndex == 0) { columnNames = DataTypeDetectorUtils.setColumnNames(line, skipHeader, delimiter); if (skipHeader) { continue; } } DataTypeDetectorUtils.detectDataTypeOfRowValues(getOverride(), dataTypeDetectorStatusKeeper, columnNames, rowValue); } dataTypeDetectorStatusKeeper.validateDataTypeDetector(); } catch (IOException e) { throw new RuntimeException(String.format("Failed to open file at path %s!", path), e); } List<Schema.Field> fields = DataTypeDetectorUtils.detectDataTypeOfEachDatasetColumn(getOverride(), columnNames, dataTypeDetectorStatusKeeper); return Schema.recordOf("text", fields); } } <|start_filename|>core-plugins/src/main/java/io/cdap/plugin/batch/connector/FileConnector.java<|end_filename|> /* * Copyright © 2021 <NAME>, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. * */ package io.cdap.plugin.batch.connector; import io.cdap.cdap.api.annotation.Category; import io.cdap.cdap.api.annotation.Description; import io.cdap.cdap.api.annotation.Name; import io.cdap.cdap.api.annotation.Plugin; import io.cdap.cdap.api.annotation.Requirements; import io.cdap.cdap.api.dataset.lib.FileSet; import io.cdap.cdap.api.plugin.PluginConfig; import io.cdap.cdap.etl.api.batch.BatchSource; import io.cdap.cdap.etl.api.connector.BrowseDetail; import io.cdap.cdap.etl.api.connector.BrowseEntity; import io.cdap.cdap.etl.api.connector.BrowseEntityPropertyValue; import io.cdap.cdap.etl.api.connector.BrowseRequest; import io.cdap.cdap.etl.api.connector.Connector; import io.cdap.cdap.etl.api.connector.ConnectorContext; import io.cdap.cdap.etl.api.connector.ConnectorSpec; import io.cdap.cdap.etl.api.connector.ConnectorSpecRequest; import io.cdap.cdap.etl.api.connector.PluginSpec; import io.cdap.plugin.batch.source.FileBatchSource; import io.cdap.plugin.common.Constants; import io.cdap.plugin.common.batch.JobUtils; import io.cdap.plugin.format.connector.AbstractFileConnector; import io.cdap.plugin.format.connector.FileTypeDetector; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.mapreduce.Job; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * File connector to browse flat file on local system */ @Plugin(type = Connector.PLUGIN_TYPE) @Name(FileConnector.NAME) @Description("Connection to browse and sample data from the local file system.") @Category("File") @Requirements(datasetTypes = FileSet.TYPE) public class FileConnector extends AbstractFileConnector<FileConnector.FileConnectorConfig> { public static final String NAME = "File"; static final String FILE_TYPE_KEY = "File Type"; static final String SIZE_KEY = "Size"; static final String LAST_MODIFIED_KEY = "Last Modified"; static final String OWNER_KEY = "Owner"; static final String GROUP_KEY = "Group"; static final String PERMISSION_KEY = "Permission"; private static final String DIRECTORY_TYPE = "directory"; private static final String FILE_TYPE = "file"; public FileConnector(FileConnectorConfig config) { super(config); } @Override public BrowseDetail browse(ConnectorContext connectorContext, BrowseRequest request) throws IOException { Path path = new Path(request.getPath()); Job job = JobUtils.createInstance(); Configuration conf = job.getConfiguration(); // need this to load the extra class loader to avoid ClassNotFoundException for the file system FileSystem fs = JobUtils.applyWithExtraClassLoader(job, getClass().getClassLoader(), f -> FileSystem.get(path.toUri(), conf)); if (!fs.exists(path)) { throw new IllegalArgumentException(String.format("The given path %s does not exist", path)); } // if it is not a directory, then it is not browsable, return the path itself FileStatus file = fs.getFileStatus(path); if (!file.isDirectory()) { return BrowseDetail.builder().setTotalCount(1).addEntity(generateBrowseEntity(file)).build(); } FileStatus[] files = fs.listStatus(path); Arrays.sort(files); int count = 0; int limit = request.getLimit() == null ? Integer.MAX_VALUE : request.getLimit(); BrowseDetail.Builder builder = BrowseDetail.builder(); for (FileStatus fileStatus : files) { // do not browse hidden files if (fileStatus.getPath().getName().startsWith(".")) { continue; } if (count >= limit) { break; } builder.addEntity(generateBrowseEntity(fileStatus)); count++; } return builder.setTotalCount(count).build(); } @Override protected void setConnectorSpec(ConnectorSpecRequest request, ConnectorSpec.Builder builder) { super.setConnectorSpec(request, builder); // not use ImmutableMap here in case any property is null Map<String, String> properties = new HashMap<>(); properties.put("path", request.getPath()); properties.put("format", FileTypeDetector.detectFileFormat( FileTypeDetector.detectFileType(request.getPath())).name().toLowerCase()); properties.put(Constants.Reference.REFERENCE_NAME, new File(request.getPath()).getName()); builder.addRelatedPlugin(new PluginSpec(FileBatchSource.NAME, BatchSource.PLUGIN_TYPE, properties)); } private BrowseEntity generateBrowseEntity(FileStatus file) throws IOException { Path path = file.getPath(); boolean isDirectory = file.isDirectory(); String filePath = path.toUri().getPath(); BrowseEntity.Builder builder = BrowseEntity.builder( path.getName(), filePath, isDirectory ? DIRECTORY_TYPE : FILE_TYPE); if (isDirectory) { builder.canBrowse(true).canSample(true); } else { String fileType = FileTypeDetector.detectFileType(filePath); builder.canSample(FileTypeDetector.isSampleable(fileType)); builder.addProperty(FILE_TYPE_KEY, BrowseEntityPropertyValue.builder( fileType, BrowseEntityPropertyValue.PropertyType.STRING).build()); builder.addProperty(SIZE_KEY, BrowseEntityPropertyValue.builder( String.valueOf(file.getLen()), BrowseEntityPropertyValue.PropertyType.SIZE_BYTES).build()); } builder.addProperty(LAST_MODIFIED_KEY, BrowseEntityPropertyValue.builder( String.valueOf(file.getModificationTime()), BrowseEntityPropertyValue.PropertyType.TIMESTAMP_MILLIS).build()); String owner = file.getOwner(); builder.addProperty(OWNER_KEY, BrowseEntityPropertyValue.builder( owner == null ? "" : owner, BrowseEntityPropertyValue.PropertyType.STRING).build()); builder.addProperty(GROUP_KEY, BrowseEntityPropertyValue.builder( file.getGroup(), BrowseEntityPropertyValue.PropertyType.STRING).build()); FsPermission permission = file.getPermission(); String perm = permission.getUserAction().SYMBOL + permission.getGroupAction().SYMBOL + permission.getOtherAction().SYMBOL; builder.addProperty(PERMISSION_KEY, BrowseEntityPropertyValue.builder( perm, BrowseEntityPropertyValue.PropertyType.STRING).build()); return builder.build(); } /** * {@link PluginConfig} for {@link FileConnector}, currently this class is empty but can be extended later if * we want to support more configs, for example, a scheme to support any file system. */ public static class FileConnectorConfig extends PluginConfig { } } <|start_filename|>format-delimited/src/main/java/io/cdap/plugin/format/delimited/input/SplitQuotesIterator.java<|end_filename|> /* * Copyright © 2021 <NAME>, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package io.cdap.plugin.format.delimited.input; import com.google.common.collect.AbstractIterator; /** * Iterator that provides the splits in the delimited string based on the delimiter. The delimiter * should not contain any quotes. The splitor will behave like this: 1. if there is no quote, it * will behave same as {@link String#split(String)} 2. if there are quotes in the string, the method * will find pairs of quotes, content within each pair of quotes will not get splitted even if there * is delimiter in that. For example, if string is a."b.c"."d.e.f" and delimiter is '.', it will get * split into [a, b.c, d.e.f]. if string is "val1.val2", then it will not get splitted since the '.' * is within pair of quotes. If the delimited string contains odd number of quotes, which mean the * quotes are not closed, an exception will be thrown. The quote within the value will always be * trimed. */ public class SplitQuotesIterator extends AbstractIterator<String> { private static final char QUOTE_CHAR = '\"'; private final String delimitedString; private final String delimiter; private int index; private boolean endingWithDelimiter = false; SplitQuotesIterator(String delimitedString, String delimiter) { this.delimitedString = delimitedString; this.delimiter = delimiter; index = 0; } @Override protected String computeNext() { // Corner case when the delimiter is in the end of the row if (endingWithDelimiter) { endingWithDelimiter = false; return ""; } if (index == delimitedString.length()) { return endOfData(); } boolean isWithinQuotes = false; StringBuilder split = new StringBuilder(); while (index < delimitedString.length()) { char cur = delimitedString.charAt(index); if (cur == QUOTE_CHAR) { isWithinQuotes = !isWithinQuotes; index++; continue; } // if the length is not enough for the delimiter or it's not a delimiter, just add it to split if (index + delimiter.length() > delimitedString.length() || !delimitedString.startsWith(delimiter, index)) { split.append(cur); index++; continue; } // find delimiter not within quotes if (!isWithinQuotes) { index += delimiter.length(); if (index == delimitedString.length()) { endingWithDelimiter = true; } return split.toString(); } // delimiter within quotes split.append(cur); index++; } if (isWithinQuotes) { throw new IllegalArgumentException( "Found a line with an unenclosed quote. Ensure that all values are properly" + " quoted, or disable quoted values."); } return split.toString(); } } <|start_filename|>format-delimited/src/test/java/io/cdap/plugin/format/delimited/input/SplitQuotesIteratorTest.java<|end_filename|> /* * Copyright © 2021 <NAME>, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package io.cdap.plugin.format.delimited.input; import com.google.common.collect.ImmutableList; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class SplitQuotesIteratorTest { private SplitQuotesIterator splitQuotesIterator; private List<String> getListFromIterator(Iterator<String> iterator) { List<String> result = new ArrayList(); while (iterator.hasNext()) { result.add(iterator.next()); } return result; } @Test public void testStringShorterThanDelimiter() throws Exception { String test = "a"; Assert.assertEquals(Arrays.asList(test.split(",,")), getListFromIterator(splitQuotesIterator = new SplitQuotesIterator(test, ",,"))); Assert.assertEquals(Arrays.asList(test.split("aa")), getListFromIterator(splitQuotesIterator = new SplitQuotesIterator(test, "aa"))); } @Test public void testStringWithConsecutiveDelimiter() throws Exception { String test = "aaa"; Assert.assertEquals(Arrays.asList(test.split("a", -1)), getListFromIterator(splitQuotesIterator = new SplitQuotesIterator(test, "a"))); Assert.assertEquals(Arrays.asList(test.split("aa", -1)), getListFromIterator(splitQuotesIterator = new SplitQuotesIterator(test, "aa"))); test = "aaaaaaa"; Assert.assertEquals(Arrays.asList(test.split("aa", -1)), getListFromIterator(splitQuotesIterator = new SplitQuotesIterator(test, "aa"))); test = "aaaaaaaa"; Assert.assertEquals(Arrays.asList(test.split("aa", -1)), getListFromIterator(splitQuotesIterator = new SplitQuotesIterator(test, "aa"))); } @Test public void testSimpleSplit() throws Exception { String test = "a,b,c,d,e"; Assert.assertEquals(Arrays.asList(test.split(",")), getListFromIterator(splitQuotesIterator = new SplitQuotesIterator(test, ","))); test = "a1,b1,c1,d1,e1"; Assert.assertEquals(Arrays.asList(test.split(",")), getListFromIterator(splitQuotesIterator = new SplitQuotesIterator(test, ","))); test = "1###sam###<EMAIL>###male"; Assert.assertEquals(Arrays.asList(test.split("###")), getListFromIterator(splitQuotesIterator = new SplitQuotesIterator(test, "###"))); test = "a1,,,b1,,,c1,,,d1,,,e1"; Assert.assertEquals(Arrays.asList(test.split(",")), getListFromIterator(splitQuotesIterator = new SplitQuotesIterator(test, ","))); } @Test public void testValidQuotesWithTrimedQuotes() throws Exception { String test = "a,\"b,c\""; List<String> expected = ImmutableList.of("a", "b,c"); Assert.assertEquals(expected, getListFromIterator(splitQuotesIterator = new SplitQuotesIterator(test, ","))); test = "a,\"aaaaa\"aaaab\"aaaac\",c"; expected = ImmutableList.of("a", "aaaaaaaaabaaaac", "c"); Assert.assertEquals(expected, getListFromIterator(splitQuotesIterator = new SplitQuotesIterator(test, ","))); test = "a,\"b,c\",\"d,e,f\""; expected = ImmutableList.of("a", "b,c", "d,e,f"); Assert.assertEquals(expected, getListFromIterator(splitQuotesIterator = new SplitQuotesIterator(test, ","))); test = "a###\"b###c\"###\"d###e###f\""; expected = ImmutableList.of("a", "b###c", "d###e###f"); Assert.assertEquals(expected, getListFromIterator(splitQuotesIterator = new SplitQuotesIterator(test, "###"))); } @Test public void testBadQuotes() throws Exception { String test = "Value1,value2.1 value2.2\"value2.2.1,value2.3\",val\"ue3,value4"; IllegalArgumentException exception = Assert.assertThrows(IllegalArgumentException.class, () -> { getListFromIterator(splitQuotesIterator = new SplitQuotesIterator(test, ",")); }); Assert.assertTrue(exception.getMessage().contains("Found a line with an unenclosed quote. Ensure that all" + " values are properly quoted, or disable quoted values.")); } } <|start_filename|>format-delimited/src/test/java/io/cdap/plugin/format/delimited/common/DataTypeDetectorUtilsTest.java<|end_filename|> /* * Copyright © 2021 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package io.cdap.plugin.format.delimited.common; import io.cdap.cdap.api.data.schema.Schema; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /** * Unit tests for {@link DataTypeDetectorUtils} */ public class DataTypeDetectorUtilsTest { @Test public void testExtractedColumnNames() { String headerLine = "column_A;column_B;column_C"; String[] actualColumnNames = DataTypeDetectorUtils.setColumnNames(headerLine, true, ";"); String[] expectedColumnNames = new String[]{"column_A", "column_B", "column_C"}; assertArrayEquals(expectedColumnNames, actualColumnNames); } @Test public void testExtractedColumnNamesRegexMetaCharacterDelimiter() { String headerLine = "column_A|column_B|column_C"; String[] actualColumnNames = DataTypeDetectorUtils.setColumnNames(headerLine, true, "|"); String[] expectedColumnNames = new String[]{"column_A", "column_B", "column_C"}; assertArrayEquals(expectedColumnNames, actualColumnNames); } @Test public void testGeneratedColumnNamesForRegexMetaCharacterDelimiter() { String dataLine = "John|Doe|27"; String[] actualColumnNames = DataTypeDetectorUtils.setColumnNames(dataLine, false, "|"); String[] expectedColumnNames = new String[]{"body_0", "body_1", "body_2"}; assertArrayEquals(expectedColumnNames, actualColumnNames); } @Test public void testGeneratedColumnNames() { String dataLine = "John;Doe;27"; String[] actualColumnNames = DataTypeDetectorUtils.setColumnNames(dataLine, false, ";"); String[] expectedColumnNames = new String[]{"body_0", "body_1", "body_2"}; assertArrayEquals(expectedColumnNames, actualColumnNames); } @Test public void testNonStandardFieldNamesShouldValidateSuccessfully() { String[] fieldNames = new String[]{"column", "column_1", "_column", "Column", "_COLUMN_1_2_"}; DataTypeDetectorUtils.validateSchemaFieldNames(fieldNames); } @Test(expected = IllegalArgumentException.class) public void testNonAvroStandardFieldNamesShouldThrowError() { String[] fieldNames = new String[]{"column-1", "1column", "1234", "column#a"}; DataTypeDetectorUtils.validateSchemaFieldNames(fieldNames); } @Test public void testDetectDataTypeOfEachDatasetColumn() { DataTypeDetectorStatusKeeper dataTypeDetectorStatusKeeper = new DataTypeDetectorStatusKeeper(); String[] columnNames = new String[]{"column_A", "column_B", "column_C", "column_D", "column_E", "column_F"}; Map<String, EnumSet<DataType>> status = new HashMap<>(); status.put(columnNames[0], EnumSet.of(DataType.INTEGER)); status.put(columnNames[1], EnumSet.of(DataType.INTEGER, DataType.LONG)); status.put(columnNames[2], EnumSet.of(DataType.INTEGER, DataType.DOUBLE)); status.put(columnNames[3], EnumSet.of(DataType.BOOLEAN)); status.put(columnNames[4], EnumSet.of(DataType.INTEGER, DataType.LONG, DataType.DOUBLE)); status.put(columnNames[5], EnumSet.of(DataType.DOUBLE, DataType.STRING)); dataTypeDetectorStatusKeeper.setDataTypeDetectionStatus(status); Map<String, Schema> override = new HashMap<>(); override.put("column_A", Schema.of(Schema.Type.DOUBLE)); List<Schema> actualFields = DataTypeDetectorUtils .detectDataTypeOfEachDatasetColumn(override, columnNames, dataTypeDetectorStatusKeeper) .stream().map(Schema.Field::getSchema).collect(Collectors.toList()); List<Schema> expectedFields = new ArrayList<>(Arrays.asList( Schema.Field.of(columnNames[0], Schema.of(Schema.Type.DOUBLE)), Schema.Field.of(columnNames[1], Schema.of(Schema.Type.LONG)), Schema.Field.of(columnNames[2], Schema.of(Schema.Type.DOUBLE)), Schema.Field.of(columnNames[3], Schema.of(Schema.Type.BOOLEAN)), Schema.Field.of(columnNames[4], Schema.of(Schema.Type.DOUBLE)), Schema.Field.of(columnNames[5], Schema.of(Schema.Type.STRING)) )).stream().map(Schema.Field::getSchema).collect(Collectors.toList()); assertEquals(expectedFields, actualFields); } @Test public void testDetectDataTypeOfRowValue() { DataTypeDetectorStatusKeeper actualDataTypeDetectorStatusKeeper = new DataTypeDetectorStatusKeeper(); String[] columnNames = new String[]{"column_A", "column_B", "column_C", "column_D", "column_E", "column_F"}; String[] rowValues = new String[]{"2", "24L", "3.14", "false", "100.05", "100A"}; DataTypeDetectorUtils.detectDataTypeOfRowValues(new HashMap<>(), actualDataTypeDetectorStatusKeeper, columnNames, rowValues); DataTypeDetectorStatusKeeper expectedDataTypeDetectorStatusKeeper = new DataTypeDetectorStatusKeeper(); Map<String, EnumSet<DataType>> status = new HashMap<>(); status.put(columnNames[0], EnumSet.of(DataType.INTEGER)); status.put(columnNames[1], EnumSet.of(DataType.LONG)); status.put(columnNames[2], EnumSet.of(DataType.DOUBLE)); status.put(columnNames[3], EnumSet.of(DataType.BOOLEAN)); status.put(columnNames[4], EnumSet.of(DataType.DOUBLE)); status.put(columnNames[5], EnumSet.of(DataType.STRING)); expectedDataTypeDetectorStatusKeeper.setDataTypeDetectionStatus(status); assertEquals(expectedDataTypeDetectorStatusKeeper, actualDataTypeDetectorStatusKeeper); } @Test public void testDetectDataTypeOfEachDatasetColumnWithMissingValues() { String[] columnNames = new String[]{"column_A", "column_B", "column_C"}; String[] rowValues1 = new String[]{"100A", "2020", "129.99"}; // Row 2 has two values instead of 3, so empty string will be padded at the end String[] rowValues2 = new String[]{"Happy", "17.99"}; DataTypeDetectorStatusKeeper actualDataTypeDetectorStatusKeeper = new DataTypeDetectorStatusKeeper(); DataTypeDetectorUtils.detectDataTypeOfRowValues(new HashMap<>(), actualDataTypeDetectorStatusKeeper, columnNames, rowValues1); DataTypeDetectorUtils.detectDataTypeOfRowValues(new HashMap<>(), actualDataTypeDetectorStatusKeeper, columnNames, rowValues2); actualDataTypeDetectorStatusKeeper.validateDataTypeDetector(); Map<String, Schema> override = new HashMap<>(); List<Schema> actualFields = DataTypeDetectorUtils .detectDataTypeOfEachDatasetColumn(override, columnNames, actualDataTypeDetectorStatusKeeper) .stream().map(Schema.Field::getSchema).collect(Collectors.toList()); List<Schema> expectedFields = new ArrayList<>(Arrays.asList( Schema.Field.of(columnNames[0], Schema.of(Schema.Type.STRING)), Schema.Field.of(columnNames[1], Schema.of(Schema.Type.DOUBLE)), Schema.Field.of(columnNames[2], Schema.nullableOf(Schema.of(Schema.Type.DOUBLE))) )).stream().map(Schema.Field::getSchema).collect(Collectors.toList()); assertEquals(expectedFields, actualFields); } }
asishgoudo/hydrator-plugins
<|start_filename|>src/__tests__/fixtures/component_38.js<|end_filename|> import {SuperCustomButton} from './component_37'; import PropTypes from 'prop-types'; export function SuperDuperCustomButton({color, ...otherProps}) { return <SuperCustomButton {...otherProps} style={{color}} />; } SuperDuperCustomButton.propTypes = SuperCustomButton.propTypes; <|start_filename|>src/__tests__/fixtures/component_35.js<|end_filename|> import {CustomButton, sharedProps} from './component_34'; import PropTypes from 'prop-types'; export function SuperCustomButton({color, ...otherProps}) { return <CustomButton {...otherProps} style={{color}} />; } SuperCustomButton.propTypes = sharedProps; export {sharedProps}; export * from './component_36'; <|start_filename|>src/__tests__/fixtures/component_36.js<|end_filename|> import {SuperCustomButton, sharedProps} from './component_35'; import PropTypes from 'prop-types'; export function SuperDuperCustomButton({color, ...otherProps}) { return <SuperCustomButton {...otherProps} style={{color}} />; } SuperDuperCustomButton.propTypes = sharedProps; export * from './component_35'; <|start_filename|>src/__tests__/fixtures/component_37.js<|end_filename|> import * as C36 from './component_36'; import PropTypes from 'prop-types'; export function SuperDuperCustomButton({color, ...otherProps}) { return <C36.SuperCustomButton {...otherProps} style={{color}} />; } SuperDuperCustomButton.propTypes = C36.sharedProps; export {SuperCustomButton} from './component_36';
bryceosterhaus/react-docgen
<|start_filename|>test/basic.js<|end_filename|> const common = require('./common') const Socket = require('../') const test = require('tape') test('detect WebSocket support', function (t) { t.equal(Socket.WEBSOCKET_SUPPORT, true, 'websocket support') t.end() }) test('create invalid socket', function (t) { t.plan(2) let socket t.doesNotThrow(function () { socket = new Socket('invalid://invalid-url') }) socket.on('error', function (err) { t.ok(err instanceof Error, 'got error') socket.destroy() }) }) test('echo string', function (t) { t.plan(4) const socket = new Socket(common.SERVER_URL) socket.on('connect', function () { t.pass('connect emitted') socket.send('sup!') socket.on('data', function (data) { t.ok(Buffer.isBuffer(data), 'data is Buffer') t.equal(data.toString(), 'sup!') socket.on('close', function () { t.pass('destroyed socket') }) socket.destroy() }) }) }) test('echo string (opts.url version)', function (t) { t.plan(4) const socket = new Socket({ url: common.SERVER_URL }) socket.on('connect', function () { t.pass('connect emitted') socket.send('sup!') socket.on('data', function (data) { t.ok(Buffer.isBuffer(data), 'data is Buffer') t.equal(data.toString(), 'sup!') socket.on('close', function () { t.pass('destroyed socket') }) socket.destroy() }) }) }) test('echo Buffer', function (t) { t.plan(4) const socket = new Socket(common.SERVER_URL) socket.on('connect', function () { t.pass('connect emitted') socket.send(Buffer.from([1, 2, 3])) socket.on('data', function (data) { t.ok(Buffer.isBuffer(data), 'data is Buffer') t.deepEqual(data, Buffer.from([1, 2, 3]), 'got correct data') socket.on('close', function () { t.pass('destroyed socket') }) socket.destroy() }) }) }) test('echo Uint8Array', function (t) { t.plan(4) const socket = new Socket(common.SERVER_URL) socket.on('connect', function () { t.pass('connect emitted') socket.send(new Uint8Array([1, 2, 3])) socket.on('data', function (data) { // binary types always get converted to Buffer // See: https://github.com/feross/simple-peer/issues/138#issuecomment-278240571 t.ok(Buffer.isBuffer(data), 'data is Buffer') t.deepEqual(data, Buffer.from([1, 2, 3]), 'got correct data') socket.on('close', function () { t.pass('destroyed socket') }) socket.destroy() }) }) }) test('echo ArrayBuffer', function (t) { t.plan(4) const socket = new Socket(common.SERVER_URL) socket.on('connect', function () { t.pass('connect emitted') socket.send(new Uint8Array([1, 2, 3]).buffer) socket.on('data', function (data) { t.ok(Buffer.isBuffer(data), 'data is Buffer') t.deepEqual(data, Buffer.from([1, 2, 3]), 'got correct data') socket.on('close', function () { t.pass('destroyed socket') }) socket.destroy() }) }) }) <|start_filename|>test/node/server.js<|end_filename|> // Test the Server class const Socket = require('../../') const Server = require('../../server') const test = require('tape') test('socket server', function (t) { t.plan(5) const port = 6789 const server = new Server({ port }) server.on('connection', function (socket) { t.equal(typeof socket.read, 'function') // stream function is present socket.on('data', function (data) { t.ok(Buffer.isBuffer(data), 'type is buffer') t.equal(data.toString(), 'ping') socket.write('pong') }) }) const client = new Socket('ws://localhost:' + port) client.on('data', function (data) { t.ok(Buffer.isBuffer(data), 'type is buffer') t.equal(data.toString(), 'pong') server.close() client.destroy() }) client.write('ping') }) test('socket server, with custom encoding', function (t) { t.plan(5) const port = 6789 const server = new Server({ port, encoding: 'utf8' }) server.on('connection', function (socket) { t.equal(typeof socket.read, 'function') // stream function is present socket.on('data', function (data) { t.equal(typeof data, 'string', 'type is string') t.equal(data, 'ping') socket.write('pong') }) }) const client = new Socket({ url: 'ws://localhost:' + port, encoding: 'utf8' }) client.on('data', function (data) { t.equal(typeof data, 'string', 'type is string') t.equal(data, 'pong') server.close() client.destroy() }) client.write('ping') }) <|start_filename|>perf/server.js<|end_filename|> // run in a terminal, look at Node.js console for speed const prettierBytes = require('prettier-bytes') const speedometer = require('speedometer') const ws = require('ws') const speed = speedometer() const server = new ws.Server({ perMessageDeflate: false, port: 8080 }) server.once('connection', function (socket) { socket.on('message', function (message) { speed(message.length) }) }) setInterval(function () { console.log(prettierBytes(speed())) }, 1000) <|start_filename|>server.js<|end_filename|> const events = require('events') const Socket = require('./') const WebSocketServer = require('ws').Server class SocketServer extends events.EventEmitter { constructor (opts) { super() this.opts = { clientTracking: false, perMessageDeflate: false, ...opts } this.destroyed = false this._server = new WebSocketServer(this.opts) this._server.on('listening', this._handleListening) this._server.on('connection', this._handleConnection) this._server.once('error', this._handleError) } address () { return this._server.address() } close (cb) { if (this.destroyed) { if (cb) cb(new Error('server is closed')) return } this.destroyed = true if (cb) this.once('close', cb) this._server.removeListener('listening', this._handleListening) this._server.removeListener('connection', this._handleConnection) this._server.removeListener('error', this._handleError) this._server.on('error', () => {}) // suppress future errors this._server.close(() => this.emit('close')) this._server = null } _handleListening = () => { this.emit('listening') } _handleConnection = (conn, req) => { const socket = new Socket({ ...this.opts, socket: conn }) this.emit('connection', socket, req) } _handleError = (err) => { this.emit('error', err) this.close() } } module.exports = SocketServer <|start_filename|>perf/send.js<|end_filename|> // run in a browser, with: // beefy perf/send.js // 6.7MB const Socket = require('../') const stream = require('readable-stream') const buf = Buffer.alloc(1000) const endless = new stream.Readable({ read: function () { this.push(buf) } }) const socket = new Socket('ws://localhost:8080') socket.on('connect', function () { endless.pipe(socket) })
Satellite-im/simple-websocket
<|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithPartialViewResultAsync.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithPartialViewResultAsync { [Fact(DisplayName = "no usings, 1 To, returns PartialViewResult async")] public void FluentControllerBuilder_FluentActionNoUsings1ToReturnsPartialViewAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(async () => { await Task.Delay(1); return "Hello World!"; }) .ToPartialView("~/Path/To/PartialViewWithStringModel.cshtml"), typeof(ControllerWithNoUsingsXToReturnsPartialViewAsync), null); } [Fact(DisplayName = "no usings, 3 To, returns PartialViewResult async")] public void FluentControllerBuilder_FluentActionNoUsings3ToReturnsPartialViewAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(async () => { await Task.Delay(1); return "Hello"; }) .UsingResult() .To(async text => { await Task.Delay(1); return $"{text} World"; }) .UsingResult() .To(async text => { await Task.Delay(1); return $"{text}!"; }) .ToPartialView("~/Path/To/PartialViewWithStringModel.cshtml"), typeof(ControllerWithNoUsingsXToReturnsPartialViewAsync), null); } [Fact(DisplayName = "no usings, 1 Do, returns PartialViewResult async")] public void FluentControllerBuilder_FluentActionNoUsings1DoReturnsPartialViewAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .DoAsync(async () => { await Task.Delay(1); }) .ToPartialView("~/Path/To/PartialViewWithoutModel.cshtml"), typeof(ControllerWithNoUsingsXDoReturnsPartialViewAsync), null); } [Fact(DisplayName = "no usings, 3 Do, returns PartialViewResult async")] public void FluentControllerBuilder_FluentActionNoUsings3DoReturnsPartialViewAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .DoAsync(async () => { await Task.Delay(1); }) .DoAsync(async () => { await Task.Delay(1); }) .DoAsync(async () => { await Task.Delay(1); }) .ToPartialView("~/Path/To/PartialViewWithoutModel.cshtml"), typeof(ControllerWithNoUsingsXDoReturnsPartialViewAsync), null); } [Fact(DisplayName = "no usings, 1 Do, 1 To, returns PartialViewResult async")] public void FluentControllerBuilder_FluentActionNoUsings1Do1ToReturnsPartialViewAsync() { var foo = "bar"; BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .DoAsync(async () => { await Task.Delay(1); foo = "baz"; }) .To(async () => { await Task.Delay(1); return foo; }) .ToPartialView("~/Path/To/PartialViewWithStringModel.cshtml"), typeof(ControllerWithNoUsings1Do1ToReturnsPartialViewAsync), null); } [Fact(DisplayName = "1 body (string), returns PartialViewResult async")] public void FluentControllerBuilder_FluentAction1BodyReturnsPartialViewAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingBody<string>() .To(async (name) => { await Task.Delay(1); return $"Hello {name}!"; }) .ToPartialView("~/Path/To/PartialViewWithStringModel.cshtml"), typeof(ControllerWith1BodyReturnsPartialViewAsync), new object[] { "Bob" }); } [Fact(DisplayName = "1 body (string), 1 Do, 1 To, returns PartialViewResult async")] public void FluentControllerBuilder_FluentAction1Body1DoReturnsPartialViewAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .DoAsync(async () => { await Task.Delay(1); }) .UsingBody<string>() .To(async (name) => { await Task.Delay(1); return $"Hello {name}!"; }) .ToPartialView("~/Path/To/PartialViewWithStringModel.cshtml"), typeof(ControllerWith1BodyReturnsPartialViewAsync), new object[] { "Bob" }); } [Fact(DisplayName = "1 body (string), 1 route param (string), returns PartialViewResult async")] public void FluentControllerBuilder_FluentAction1Body1RouteParamReturnsPartialViewAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/{lastName}", HttpMethod.Get) .UsingBody<string>() .UsingRouteParameter<string>("lastName") .To(async (firstName, lastName) => { await Task.Delay(1); return $"Hello {firstName} {lastName}!"; }) .ToPartialView("~/Path/To/PartialViewWithStringModel.cshtml"), typeof(ControllerWith1Body1RouteParamReturnsPartialViewAsync), new object[] { "Bob", "Bobsson" }); } [Fact(DisplayName = "1 body (string), 1 route param (string), 2 To, returns PartialViewResult async")] public void FluentControllerBuilder_FluentAction1Body1RouteParam2ToReturnsPartialViewAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/{lastName}", HttpMethod.Get) .UsingBody<string>() .To(async firstName => { await Task.Delay(1); return $"Hello {firstName}"; }) .UsingRouteParameter<string>("lastName") .To(async lastName => { await Task.Delay(1); return $"{lastName}!"; }) .ToPartialView("~/Path/To/PartialViewWithStringModel.cshtml"), typeof(ControllerWith1Body1RouteParam2ToReturnsPartialViewAsync), new object[] { "Bob", "Bobsson" }); } } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/StringExtensions.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using System; namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions { public static class StringExtensions { public static string WithoutTrailing(this string originalValue, string trailingValue, StringComparison stringComparison = StringComparison.CurrentCultureIgnoreCase) { if (originalValue.Length < trailingValue.Length) { throw new ArgumentException($"Trailing string {trailingValue} is longer than original string {originalValue}"); } if (originalValue.EndsWith(trailingValue, stringComparison)) { return originalValue.Substring(0, originalValue.Length - trailingValue.Length); } else { return originalValue; } } public static string WithoutLeading(this string originalValue, string leadingValue, StringComparison stringComparison = StringComparison.CurrentCultureIgnoreCase) { if (originalValue.Length < leadingValue.Length) { throw new ArgumentException($"Leading string {leadingValue} is longer than original string {originalValue}"); } if (originalValue.StartsWith(leadingValue, stringComparison)) { return originalValue.Substring(leadingValue.Length, originalValue.Length - leadingValue.Length); } else { return originalValue; } } public static string Without(this string text, string textToRemove) { return text.Replace(textToRemove, ""); } public static bool Contains(this string originalValue, string valueToCheck, StringComparison comparison) { return originalValue.IndexOf(valueToCheck, comparison) >= 0; } } } <|start_filename|>test/WebApps/SimpleMvc/Models/ModelStateFormModel.cs<|end_filename|> using System.ComponentModel.DataAnnotations; namespace SimpleMvc.Models { public class ModelStateFormModel { [Required] public string TextValue { get; set; } } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/IlHandle.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using System.Reflection.Emit; namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions { public class IlHandle { public ILGenerator Generator { get; internal set; } } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/FluentActionWithController.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using System; using System.Linq.Expressions; namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions { public class FluentActionWithMvcController<TU1> : FluentActionBase { public FluentActionWithMvcController(FluentActionDefinition fluentActionDefinition, FluentActionUsingDefinition usingDefinition) : base(fluentActionDefinition) { Definition.ExistingOrNewHandlerDraft.Usings.Add(usingDefinition); } public FluentActionWithControllerResult<TR> ToMvcAction<TR>(Expression<Func<TU1, TR>> actionExpression) { return new FluentActionWithControllerResult<TR>(Definition, actionExpression); } } public class FluentActionWithMvcController<TU1, TU2> : FluentActionBase { public FluentActionWithMvcController(FluentActionDefinition fluentActionDefinition, FluentActionUsingDefinition usingDefinition) : base(fluentActionDefinition) { Definition.ExistingOrNewHandlerDraft.Usings.Add(usingDefinition); } public FluentActionWithControllerResult<TR> ToMvcAction<TR>(Expression<Func<TU1, TU2, TR>> actionExpression) { return new FluentActionWithControllerResult<TR>(Definition, actionExpression); } } public class FluentActionWithMvcController<TU1, TU2, TU3> : FluentActionBase { public FluentActionWithMvcController(FluentActionDefinition fluentActionDefinition, FluentActionUsingDefinition usingDefinition) : base(fluentActionDefinition) { Definition.ExistingOrNewHandlerDraft.Usings.Add(usingDefinition); } public FluentActionWithControllerResult<TR> ToMvcAction<TR>(Expression<Func<TU1, TU2, TU3, TR>> actionExpression) { return new FluentActionWithControllerResult<TR>(Definition, actionExpression); } } public class FluentActionWithMvcController<TU1, TU2, TU3, TU4> : FluentActionBase { public FluentActionWithMvcController(FluentActionDefinition fluentActionDefinition, FluentActionUsingDefinition usingDefinition) : base(fluentActionDefinition) { Definition.ExistingOrNewHandlerDraft.Usings.Add(usingDefinition); } public FluentActionWithControllerResult<TR> ToMvcAction<TR>(Expression<Func<TU1, TU2, TU3, TU4, TR>> actionExpression) { return new FluentActionWithControllerResult<TR>(Definition, actionExpression); } } public class FluentActionWithMvcController<TU1, TU2, TU3, TU4, TU5> : FluentActionBase { public FluentActionWithMvcController(FluentActionDefinition fluentActionDefinition, FluentActionUsingDefinition usingDefinition) : base(fluentActionDefinition) { Definition.ExistingOrNewHandlerDraft.Usings.Add(usingDefinition); } public FluentActionWithControllerResult<TR> ToMvcAction<TR>(Expression<Func<TU1, TU2, TU3, TU4, TU5, TR>> actionExpression) { return new FluentActionWithControllerResult<TR>(Definition, actionExpression); } } public class FluentActionWithMvcController<TU1, TU2, TU3, TU4, TU5, TU6> : FluentActionBase { public FluentActionWithMvcController(FluentActionDefinition fluentActionDefinition, FluentActionUsingDefinition usingDefinition) : base(fluentActionDefinition) { Definition.ExistingOrNewHandlerDraft.Usings.Add(usingDefinition); } public FluentActionWithControllerResult<TR> ToMvcAction<TR>(Expression<Func<TU1, TU2, TU3, TU4, TU5, TU6, TR>> actionExpression) { return new FluentActionWithControllerResult<TR>(Definition, actionExpression); } } public class FluentActionWithMvcController<TU1, TU2, TU3, TU4, TU5, TU6, TU7> : FluentActionBase { public FluentActionWithMvcController(FluentActionDefinition fluentActionDefinition, FluentActionUsingDefinition usingDefinition) : base(fluentActionDefinition) { Definition.ExistingOrNewHandlerDraft.Usings.Add(usingDefinition); } public FluentActionWithControllerResult<TR> ToMvcAction<TR>(Expression<Func<TU1, TU2, TU3, TU4, TU5, TU6, TU7, TR>> actionExpression) { return new FluentActionWithControllerResult<TR>(Definition, actionExpression); } } public class FluentActionWithMvcController<TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8> : FluentActionBase { public FluentActionWithMvcController(FluentActionDefinition fluentActionDefinition, FluentActionUsingDefinition usingDefinition) : base(fluentActionDefinition) { Definition.ExistingOrNewHandlerDraft.Usings.Add(usingDefinition); } public FluentActionWithControllerResult<TR> ToMvcAction<TR>(Expression<Func<TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8, TR>> actionExpression) { return new FluentActionWithControllerResult<TR>(Definition, actionExpression); } } public class FluentActionWithMvcController<TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8, TU9> : FluentActionBase { public FluentActionWithMvcController(FluentActionDefinition fluentActionDefinition, FluentActionUsingDefinition usingDefinition) : base(fluentActionDefinition) { Definition.ExistingOrNewHandlerDraft.Usings.Add(usingDefinition); } public FluentActionWithControllerResult<TR> ToMvcAction<TR>(Expression<Func<TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8, TU9, TR>> actionExpression) { return new FluentActionWithControllerResult<TR>(Definition, actionExpression); } } public class FluentActionWithControllerResult<TR> : FluentActionBase { public FluentActionWithControllerResult(FluentActionDefinition fluentActionDefinition, LambdaExpression actionExpression) : base(fluentActionDefinition) { var returnType = typeof(TR); Definition.ExistingOrNewHandlerDraft.Type = FluentActionHandlerType.Controller; Definition.ExistingOrNewHandlerDraft.Expression = actionExpression; Definition.ExistingOrNewHandlerDraft.ReturnType = returnType.IsAnonymous() ? typeof(object) : returnType; Definition.CommitHandlerDraft(); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Services/UserService.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class UserItem { public int Id { get; set; } public string Name { get; set; } public override bool Equals(object obj) { return obj is UserItem && ((UserItem)obj).Id == Id && ((UserItem)obj).Name == Name; } public override int GetHashCode() { return $"{Id}-{Name}".GetHashCode(); } } public interface IUserService { IList<UserItem> ListUsers(); Task<IList<UserItem>> ListUsersAsync(); EntityAddResultItem AddUser(UserItem user); Task<EntityAddResultItem> AddUserAsync(UserItem user); UserItem GetUserById(int userId); Task<UserItem> GetUserByIdAsync(int userId); EntityUpdateResultItem UpdateUser(int userId, UserItem user); Task<EntityUpdateResultItem> UpdateUserAsync(int userId, UserItem user); EntityRemoveResultItem RemoveUser(int userId); Task<EntityRemoveResultItem> RemoveUserAsync(int userId); } public class UserService : IUserService { public IList<UserItem> ListUsers() { return new List<UserItem> { new UserItem { Id = 1, Name = "<NAME>" }, new UserItem { Id = 2, Name = "<NAME>" }, new UserItem { Id = 3, Name = "<NAME>" } }; } public async Task<IList<UserItem>> ListUsersAsync() { await Task.Delay(1); return ListUsers(); } public EntityAddResultItem AddUser(UserItem user) { return new EntityAddResultItem { Id = DateTimeOffset.Now.Millisecond, Timestamp = DateTimeOffset.Now }; } public async Task<EntityAddResultItem> AddUserAsync(UserItem user) { await Task.Delay(1); return AddUser(user); } public UserItem GetUserById(int userId) { return new UserItem { Id = 1, Name = "<NAME>" }; } public async Task<UserItem> GetUserByIdAsync(int userId) { await Task.Delay(1); return GetUserById(userId); } public EntityUpdateResultItem UpdateUser(int userId, UserItem user) { return new EntityUpdateResultItem { Id = userId, Timestamp = DateTimeOffset.Now }; } public async Task<EntityUpdateResultItem> UpdateUserAsync(int userId, UserItem user) { await Task.Delay(1); return UpdateUser(userId, user); } public EntityRemoveResultItem RemoveUser(int userId) { return new EntityRemoveResultItem { Id = userId, Timestamp = DateTimeOffset.Now }; } public async Task<EntityRemoveResultItem> RemoveUserAsync(int userId) { await Task.Delay(1); return RemoveUser(userId); } } public class EntityAddResultItem { public int Id { get; set; } public DateTimeOffset Timestamp { get; set; } } public class EntityRemoveResultItem { public int Id { get; set; } public DateTimeOffset Timestamp { get; set; } } public class EntityUpdateResultItem { public int Id { get; set; } public DateTimeOffset Timestamp { get; set; } } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/UsingDefinitions/UsingTempDataDefinition.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions { public class FluentActionUsingTempDataDefinition : FluentActionUsingDefinition { public override bool IsControllerProperty => true; public override string ControllerPropertyName => "TempData"; } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/FluentAction.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.ViewFeatures; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions { public class FluentAction : FluentAction<object, object> { public FluentAction(FluentActionDefinition fluentActionDefinition) : base(fluentActionDefinition) { } public FluentAction(string routeTemplate, HttpMethod httpMethod, string id = null) : base(routeTemplate, httpMethod, id) { } } public class FluentAction<TP, TR> : FluentActionBase { public FluentAction(FluentActionDefinition fluentActionDefinition) : base(fluentActionDefinition) { } public FluentAction(string routeTemplate, HttpMethod httpMethod, string id = null) : base(httpMethod, routeTemplate, id) { } public FluentAction(FluentActionDefinition fluentActionDefinition, Delegate handlerFunc, bool async = false) : base(fluentActionDefinition) { var returnType = typeof(TR); Definition.ExistingOrNewHandlerDraft.Type = FluentActionHandlerType.Func; Definition.ExistingOrNewHandlerDraft.Delegate = handlerFunc; Definition.ExistingOrNewHandlerDraft.ReturnType = returnType.IsAnonymous() ? typeof(object) : returnType; Definition.ExistingOrNewHandlerDraft.Async = async; Definition.CommitHandlerDraft(); } public virtual FluentAction<TP2, TR> InheritingFrom<TP2>() where TP2 : Controller { Definition.ParentType = typeof(TP2); return new FluentAction<TP2, TR>(Definition); } public virtual FluentAction<TP, TR> GroupBy(string groupName) { Definition.GroupName = groupName; return this; } public virtual FluentAction<TP, TR> IgnoreApi(bool ignore = true) { Definition.IgnoreApi = ignore; return this; } public virtual FluentAction<TP, TR> WithTitle(string title) { Definition.Title = title; return this; } public virtual FluentAction<TP, TR> WithDescription(string description) { Definition.Description = description; return this; } public virtual FluentAction<TP, TR> WithCustomAttribute<T>() { return WithCustomAttribute<T>(new Type[0], new object[0]); } public virtual FluentAction<TP, TR> WithCustomAttribute<T>(Type[] constructorArgTypes, object[] constructorArgs) { var attributeConstructorInfo = typeof(T).GetConstructor(constructorArgTypes); return WithCustomAttribute<T>(attributeConstructorInfo, constructorArgs); } public virtual FluentAction<TP, TR> WithCustomAttribute<T>(Type[] constructorArgTypes, object[] constructorArgs, string[] namedProperties, object[] propertyValues) { var attributeConstructorInfo = typeof(T).GetConstructor(constructorArgTypes); return WithCustomAttribute<T>( attributeConstructorInfo, constructorArgs, namedProperties.Select(propertyName => typeof(T).GetProperty(propertyName)).ToArray(), propertyValues); } public virtual FluentAction<TP, TR> WithCustomAttribute<T>(ConstructorInfo constructor, object[] constructorArgs) { return WithCustomAttribute<T>( constructor, constructorArgs, new PropertyInfo[0], new object[0], new FieldInfo[0], new object[0]); } public virtual FluentAction<TP, TR> WithCustomAttribute<T>(ConstructorInfo constructor, object[] constructorArgs, FieldInfo[] namedFields, object[] fieldValues) { return WithCustomAttribute<T>( constructor, constructorArgs, new PropertyInfo[0], new object[0], namedFields, fieldValues); } public virtual FluentAction<TP, TR> WithCustomAttribute<T>(ConstructorInfo constructor, object[] constructorArgs, PropertyInfo[] namedProperties, object[] propertyValues) { return WithCustomAttribute<T>( constructor, constructorArgs, namedProperties, propertyValues, new FieldInfo[0], new object[0]); } public virtual FluentAction<TP, TR> WithCustomAttribute<T>(ConstructorInfo constructor, object[] constructorArgs, PropertyInfo[] namedProperties, object[] propertyValues, FieldInfo[] namedFields, object[] fieldValues) { Definition.CustomAttributes.Add(new FluentActionCustomAttribute() { Type = typeof(T), Constructor = constructor, ConstructorArgs = constructorArgs, NamedProperties = namedProperties, PropertyValues = propertyValues, NamedFields = namedFields, FieldValues = fieldValues, }); return this; } public virtual FluentAction<TP, TR> WithCustomAttributeOnClass<T>() { return WithCustomAttributeOnClass<T>(new Type[0], new object[0]); } public virtual FluentAction<TP, TR> WithCustomAttributeOnClass<T>(Type[] constructorArgTypes, object[] constructorArgs) { var attributeConstructorInfo = typeof(T).GetConstructor(constructorArgTypes); return WithCustomAttributeOnClass<T>(attributeConstructorInfo, constructorArgs); } public virtual FluentAction<TP, TR> WithCustomAttributeOnClass<T>(Type[] constructorArgTypes, object[] constructorArgs, string[] namedProperties, object[] propertyValues) { var attributeConstructorInfo = typeof(T).GetConstructor(constructorArgTypes); return WithCustomAttributeOnClass<T>( attributeConstructorInfo, constructorArgs, namedProperties.Select(propertyName => typeof(T).GetProperty(propertyName)).ToArray(), propertyValues); } public virtual FluentAction<TP, TR> WithCustomAttributeOnClass<T>(ConstructorInfo constructor, object[] constructorArgs) { return WithCustomAttributeOnClass<T>( constructor, constructorArgs, new PropertyInfo[0], new object[0], new FieldInfo[0], new object[0]); } public virtual FluentAction<TP, TR> WithCustomAttributeOnClass<T>(ConstructorInfo constructor, object[] constructorArgs, FieldInfo[] namedFields, object[] fieldValues) { return WithCustomAttributeOnClass<T>( constructor, constructorArgs, new PropertyInfo[0], new object[0], namedFields, fieldValues); } public virtual FluentAction<TP, TR> WithCustomAttributeOnClass<T>(ConstructorInfo constructor, object[] constructorArgs, PropertyInfo[] namedProperties, object[] propertyValues) { return WithCustomAttributeOnClass<T>( constructor, constructorArgs, namedProperties, propertyValues, new FieldInfo[0], new object[0]); } public virtual FluentAction<TP, TR> WithCustomAttributeOnClass<T>(ConstructorInfo constructor, object[] constructorArgs, PropertyInfo[] namedProperties, object[] propertyValues, FieldInfo[] namedFields, object[] fieldValues) { Definition.CustomAttributesOnClass.Add(new FluentActionCustomAttribute() { Type = typeof(T), Constructor = constructor, ConstructorArgs = constructorArgs, NamedProperties = namedProperties, PropertyValues = propertyValues, NamedFields = namedFields, FieldValues = fieldValues, }); return this; } public virtual FluentAction<TP, TR> ValidateAntiForgeryToken() { return WithCustomAttribute<ValidateAntiForgeryTokenAttribute>(); } public virtual FluentAction<TP, TR> Authorize( string policy = null, string roles = null, string authenticationSchemes = null) { return WithCustomAttribute<AuthorizeAttribute>( new Type[] { typeof(string) }, new object[] { policy }, new string[] { "Roles", "AuthenticationSchemes" }, new object[] { roles, authenticationSchemes }); } public virtual FluentAction<TP, TR> AuthorizeClass( string policy = null, string roles = null, string authenticationSchemes = null) { return WithCustomAttributeOnClass<AuthorizeAttribute>( new Type[] { typeof(string) }, new object[] { policy }, new string[] { "Roles", "AuthenticationSchemes" }, new object[] { roles, authenticationSchemes }); } public virtual FluentAction<TP, TR> AllowAnonymous() { return WithCustomAttribute<AllowAnonymousAttribute>(); } /// <summary> /// Adds a ResponseCache attribute to the generated MVC action /// </summary> /// <param name="duration">Duration in seconds for which the response is cached. This sets "max-age" in "Cache-control" header.</param> /// <param name="location">The location where the data from a particular URL must be cached.</param> /// <param name="noStore">The value which determines whether the data should be stored or not. When set to true, it sets "Cache-control" header to "no-store". Ignores the "Location" parameter for values other than "None". Ignores the "duration" parameter.</param> /// <param name="varyByHeader">The value for the Vary response header.</param> /// <param name="varyByQueryKeys">The query keys to vary by.</param> /// <param name="cacheProfileName">The value of the cache profile name.</param> /// <param name="order"></param> /// <param name="isReusable"></param> /// <returns></returns> public virtual FluentAction<TP, TR> ResponseCache( int? duration = null, ResponseCacheLocation? location = null, bool? noStore = null, string varyByHeader = null, string[] varyByQueryKeys = null, string cacheProfileName = null, int? order = null, bool? isReusable = null ) { var nonNullableArguments = new Dictionary<string, object>() { { "Duration", duration }, { "Location", location }, { "NoStore", noStore }, { "VaryByHeader", varyByHeader }, { "VaryByQueryKeys", varyByQueryKeys }, { "CacheProfileName", cacheProfileName }, { "Order", order }, { "IsReusable", isReusable } } .Where(pair => pair.Value != null) .ToList(); return WithCustomAttribute<ResponseCacheAttribute>( new Type[0], new object[0], nonNullableArguments.Select(p => p.Key).ToArray(), nonNullableArguments.Select(p => p.Value).ToArray() ); } public virtual FluentAction<TP, TR, TU1> Using<TU1>(FluentActionUsingDefinition usingDefinition) { return new FluentAction<TP, TR, TU1>(Definition, usingDefinition); } public virtual FluentAction<TP, TR, TU1> UsingBody<TU1>() { return new FluentAction<TP, TR, TU1>(Definition, new FluentActionUsingBodyDefinition { Type = typeof(TU1) }); } public virtual FluentAction<TP, TR, TU1> UsingBody<TU1>(TU1 defaultValue) { return new FluentAction<TP, TR, TU1>(Definition, new FluentActionUsingBodyDefinition { Type = typeof(TU1), HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1> UsingForm<TU1>() { return new FluentAction<TP, TR, TU1>(Definition, new FluentActionUsingFormDefinition { Type = typeof(TU1) }); } public virtual FluentAction<TP, TR, TU1> UsingForm<TU1>(TU1 defaultValue) { return new FluentAction<TP, TR, TU1>(Definition, new FluentActionUsingFormDefinition { Type = typeof(TU1), HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, IFormFile> UsingFormFile(string name) { return new FluentAction<TP, TR, IFormFile>(Definition, new FluentActionUsingFormFileDefinition { Type = typeof(IFormFile), Name = name }); } public virtual FluentAction<TP, TR, IEnumerable<IFormFile>> UsingFormFiles(string name) { return new FluentAction<TP, TR, IEnumerable<IFormFile>>(Definition, new FluentActionUsingFormFilesDefinition { Type = typeof(IEnumerable<IFormFile>), Name = name }); } public virtual FluentAction<TP, TR, TU1> UsingFormValue<TU1>(string key) { return new FluentAction<TP, TR, TU1>(Definition, new FluentActionUsingFormValueDefinition { Type = typeof(TU1), Key = key }); } public virtual FluentAction<TP, TR, TU1> UsingFormValue<TU1>(string key, TU1 defaultValue) { return new FluentAction<TP, TR, TU1>(Definition, new FluentActionUsingFormValueDefinition { Type = typeof(TU1), Key = key, HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1> UsingHeader<TU1>(string name) { return new FluentAction<TP, TR, TU1>(Definition, new FluentActionUsingHeaderParameterDefinition { Type = typeof(TU1), Name = name }); } public virtual FluentAction<TP, TR, TU1> UsingHeader<TU1>(string name, TU1 defaultValue) { return new FluentAction<TP, TR, TU1>(Definition, new FluentActionUsingHeaderParameterDefinition { Type = typeof(TU1), Name = name, HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, HttpContext> UsingHttpContext() { return new FluentAction<TP, TR, HttpContext>(Definition, new FluentActionUsingHttpContextDefinition { Type = typeof(HttpContext) }); } public virtual FluentAction<TP, TR, TU1> UsingModelBinder<TU1>(Type modelBinderType, string parameterName = null) { return new FluentAction<TP, TR, TU1>(Definition, new FluentActionUsingModelBinderDefinition { Type = typeof(TU1), ModelBinderType = modelBinderType, ParameterName = parameterName }); } public virtual FluentAction<TP, TR, TU1> UsingModelBinder<TU1>(Type modelBinderType, string parameterName, TU1 defaultValue) { return new FluentAction<TP, TR, TU1>(Definition, new FluentActionUsingModelBinderDefinition { Type = typeof(TU1), ModelBinderType = modelBinderType, HasDefaultValue = true, DefaultValue = defaultValue, ParameterName = parameterName }); } public virtual FluentAction<TP, TR, ModelStateDictionary> UsingModelState() { return new FluentAction<TP, TR, ModelStateDictionary>(Definition, new FluentActionUsingModelStateDefinition { Type = typeof(ModelStateDictionary) }); } public virtual FluentAction<TP, TR, TP> UsingParent() { return new FluentAction<TP, TR, TP>(Definition, new FluentActionUsingParentDefinition { Type = typeof(TR) }); } public virtual FluentAction<TP, TR, TP2> UsingParent<TP2>() { return new FluentAction<TP, TR, TP2>(Definition, new FluentActionUsingParentDefinition { Type = typeof(TP2) }); } public virtual FluentAction<TP, TR, TPr> UsingProperty<TPr>(string name) { return new FluentAction<TP, TR, TPr>(Definition, new FluentActionUsingPropertyDefinition { Type = typeof(TPr), PropertyName = name }); } public virtual FluentAction<TP, TR, TU1> UsingQueryStringParameter<TU1>(string name) { return new FluentAction<TP, TR, TU1>(Definition, new FluentActionUsingQueryStringParameterDefinition { Type = typeof(TU1), Name = name }); } public virtual FluentAction<TP, TR, TU1> UsingQueryStringParameter<TU1>(string name, TU1 defaultValue) { return new FluentAction<TP, TR, TU1>(Definition, new FluentActionUsingQueryStringParameterDefinition { Type = typeof(TU1), Name = name, HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, HttpRequest> UsingRequest() { return new FluentAction<TP, TR, HttpRequest>(Definition, new FluentActionUsingRequestDefinition { Type = typeof(HttpRequest) }); } public virtual FluentAction<TP, TR, HttpResponse> UsingResponse() { return new FluentAction<TP, TR, HttpResponse>(Definition, new FluentActionUsingResponseDefinition { Type = typeof(HttpResponse) }); } public virtual FluentAction<TP, TR, TR> UsingResult() { return new FluentAction<TP, TR, TR>(Definition, new FluentActionUsingResultDefinition { Type = typeof(TR) }); } public virtual FluentAction<TP, TR, TU1> UsingRouteParameter<TU1>(string name) { return new FluentAction<TP, TR, TU1>(Definition, new FluentActionUsingRouteParameterDefinition { Type = typeof(TU1), Name = name }); } public virtual FluentAction<TP, TR, TU1> UsingRouteParameter<TU1>(string name, TU1 defaultValue) { return new FluentAction<TP, TR, TU1>(Definition, new FluentActionUsingRouteParameterDefinition { Type = typeof(TU1), Name = name, HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1> UsingService<TU1>() { return new FluentAction<TP, TR, TU1>(Definition, new FluentActionUsingServiceDefinition { Type = typeof(TU1) }); } public virtual FluentAction<TP, TR, TU1> UsingService<TU1>(TU1 defaultValue) { return new FluentAction<TP, TR, TU1>(Definition, new FluentActionUsingServiceDefinition { Type = typeof(TU1), HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, ITempDataDictionary> UsingTempData() { return new FluentAction<TP, TR, ITempDataDictionary>(Definition, new FluentActionUsingTempDataDefinition { Type = typeof(ITempDataDictionary) }); } public virtual FluentAction<TP, TR, dynamic> UsingViewBag() { return new FluentAction<TP, TR, dynamic>(Definition, new FluentActionUsingViewBagDefinition { Type = typeof(object) }); } public virtual FluentAction<TP, TR, ViewDataDictionary> UsingViewData() { return new FluentAction<TP, TR, ViewDataDictionary>(Definition, new FluentActionUsingViewDataDefinition { Type = typeof(ViewDataDictionary) }); } public FluentAction<TP, object> Do(Action handlerAction) { Definition.ExistingOrNewHandlerDraft.Type = FluentActionHandlerType.Action; Definition.ExistingOrNewHandlerDraft.Delegate = handlerAction; Definition.CommitHandlerDraft(); return new FluentAction<TP, object>(Definition); } public FluentAction<TP, object> DoAsync(Func<Task> asyncHandlerAction) { Definition.ExistingOrNewHandlerDraft.Type = FluentActionHandlerType.Action; Definition.ExistingOrNewHandlerDraft.Delegate = asyncHandlerAction; Definition.ExistingOrNewHandlerDraft.Async = true; Definition.CommitHandlerDraft(); return new FluentAction<TP, object>(Definition); } public virtual FluentActionWithMvcController<TC> ToMvcController<TC>() where TC : Controller { return new FluentActionWithMvcController<TC>(Definition, new FluentActionUsingMvcControllerDefinition { Type = typeof(TC) }); } public FluentAction<TP, TR2> To<TR2>(Func<TR2> handlerFunc) { return new FluentAction<TP, TR2>(Definition, handlerFunc); } public FluentAction<TP, TR2> To<TR2>(Func<Task<TR2>> asyncHandlerFunc) { return new FluentAction<TP, TR2>(Definition, asyncHandlerFunc, async: true); } public FluentActionWithView<TP> ToView(string pathToView) { return new FluentActionWithView<TP>(Definition, pathToView); } public FluentActionWithPartialView<TP> ToPartialView(string pathToView) { return new FluentActionWithPartialView<TP>(Definition, pathToView); } public FluentActionWithViewComponent<TP> ToViewComponent(Type viewComponentType) { return new FluentActionWithViewComponent<TP>(Definition, viewComponentType); } public FluentActionWithViewComponent<TP> ToViewComponent(string viewComponentName) { return new FluentActionWithViewComponent<TP>(Definition, viewComponentName); } } public class FluentAction<TP, TR, TU1> : FluentActionBase { public FluentAction(FluentActionDefinition fluentActionDefinition, FluentActionUsingDefinition usingDefinition) : base(fluentActionDefinition) { Definition.ExistingOrNewHandlerDraft.Usings.Add(usingDefinition); } public virtual FluentAction<TP, TR, TU1, TU2> Using<TU2>(FluentActionUsingDefinition usingDefinition) { return new FluentAction<TP, TR, TU1, TU2>(Definition, usingDefinition); } public FluentAction<TP, TR, TU1, TU2> UsingBody<TU2>() { return new FluentAction<TP, TR, TU1, TU2>(Definition, new FluentActionUsingBodyDefinition { Type = typeof(TU2) }); } public FluentAction<TP, TR, TU1, TU2> UsingBody<TU2>(TU2 defaultValue) { return new FluentAction<TP, TR, TU1, TU2>(Definition, new FluentActionUsingBodyDefinition { Type = typeof(TU2), HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2> UsingForm<TU2>() { return new FluentAction<TP, TR, TU1, TU2>(Definition, new FluentActionUsingFormDefinition { Type = typeof(TU2) }); } public virtual FluentAction<TP, TR, TU1, TU2> UsingForm<TU2>(TU2 defaultValue) { return new FluentAction<TP, TR, TU1, TU2>(Definition, new FluentActionUsingFormDefinition { Type = typeof(TU2), HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, IFormFile> UsingFormFile(string name) { return new FluentAction<TP, TR, TU1, IFormFile>(Definition, new FluentActionUsingFormFileDefinition { Type = typeof(IFormFile), Name = name }); } public virtual FluentAction<TP, TR, TU1, IEnumerable<IFormFile>> UsingFormFiles(string name) { return new FluentAction<TP, TR, TU1, IEnumerable<IFormFile>>(Definition, new FluentActionUsingFormFilesDefinition { Type = typeof(IEnumerable<IFormFile>), Name = name }); } public virtual FluentAction<TP, TR, TU1, TU2> UsingFormValue<TU2>(string key) { return new FluentAction<TP, TR, TU1, TU2>(Definition, new FluentActionUsingFormValueDefinition { Type = typeof(TU2), Key = key }); } public virtual FluentAction<TP, TR, TU1, TU2> UsingFormValue<TU2>(string key, TU2 defaultValue) { return new FluentAction<TP, TR, TU1, TU2>(Definition, new FluentActionUsingFormValueDefinition { Type = typeof(TU2), Key = key, HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2> UsingHeader<TU2>(string name) { return new FluentAction<TP, TR, TU1, TU2>(Definition, new FluentActionUsingHeaderParameterDefinition { Type = typeof(TU2), Name = name }); } public virtual FluentAction<TP, TR, TU1, TU2> UsingHeader<TU2>(string name, TU2 defaultValue) { return new FluentAction<TP, TR, TU1, TU2>(Definition, new FluentActionUsingHeaderParameterDefinition { Type = typeof(TU2), Name = name, HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, HttpContext> UsingHttpContext() { return new FluentAction<TP, TR, TU1, HttpContext>(Definition, new FluentActionUsingHttpContextDefinition { Type = typeof(HttpContext) }); } public virtual FluentAction<TP, TR, TU1, TU2> UsingModelBinder<TU2>(Type modelBinderType, string parameterName = null) { return new FluentAction<TP, TR, TU1, TU2>(Definition, new FluentActionUsingModelBinderDefinition { Type = typeof(TU2), ModelBinderType = modelBinderType, ParameterName = parameterName }); } public virtual FluentAction<TP, TR, TU1, TU2> UsingModelBinder<TU2>(Type modelBinderType, string parameterName, TU2 defaultValue) { return new FluentAction<TP, TR, TU1, TU2>(Definition, new FluentActionUsingModelBinderDefinition { Type = typeof(TU2), ModelBinderType = modelBinderType, HasDefaultValue = true, DefaultValue = defaultValue, ParameterName = parameterName }); } public virtual FluentAction<TP, TR, TU1, ModelStateDictionary> UsingModelState() { return new FluentAction<TP, TR, TU1, ModelStateDictionary>(Definition, new FluentActionUsingModelStateDefinition { Type = typeof(ModelStateDictionary) }); } public virtual FluentAction<TP, TR, TU1, TP> UsingParent() { return new FluentAction<TP, TR, TU1, TP>(Definition, new FluentActionUsingParentDefinition { Type = typeof(TR) }); } public virtual FluentAction<TP, TR, TU1, TP2> UsingParent<TP2>() { return new FluentAction<TP, TR, TU1, TP2>(Definition, new FluentActionUsingParentDefinition { Type = typeof(TP2) }); } public virtual FluentAction<TP, TR, TU1, TPr> UsingProperty<TPr>(string name) { return new FluentAction<TP, TR, TU1, TPr>(Definition, new FluentActionUsingPropertyDefinition { Type = typeof(TPr), PropertyName = name }); } public virtual FluentAction<TP, TR, TU1, TU2> UsingQueryStringParameter<TU2>(string name) { return new FluentAction<TP, TR, TU1, TU2>(Definition, new FluentActionUsingQueryStringParameterDefinition { Type = typeof(TU2), Name = name }); } public virtual FluentAction<TP, TR, TU1, TU2> UsingQueryStringParameter<TU2>(string name, TU2 defaultValue) { return new FluentAction<TP, TR, TU1, TU2>(Definition, new FluentActionUsingQueryStringParameterDefinition { Type = typeof(TU2), Name = name, HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, HttpRequest> UsingRequest() { return new FluentAction<TP, TR, TU1, HttpRequest>(Definition, new FluentActionUsingRequestDefinition { Type = typeof(HttpRequest) }); } public virtual FluentAction<TP, TR, TU1, HttpResponse> UsingResponse() { return new FluentAction<TP, TR, TU1, HttpResponse>(Definition, new FluentActionUsingResponseDefinition { Type = typeof(HttpResponse) }); } public virtual FluentAction<TP, TR, TU1, TR> UsingResult() { return new FluentAction<TP, TR, TU1, TR>(Definition, new FluentActionUsingResultDefinition { Type = typeof(TR) }); } public FluentAction<TP, TR, TU1, TU2> UsingRouteParameter<TU2>(string name) { return new FluentAction<TP, TR, TU1, TU2>(Definition, new FluentActionUsingRouteParameterDefinition { Type = typeof(TU2), Name = name }); } public FluentAction<TP, TR, TU1, TU2> UsingRouteParameter<TU2>(string name, TU2 defaultValue) { return new FluentAction<TP, TR, TU1, TU2>(Definition, new FluentActionUsingRouteParameterDefinition { Type = typeof(TU2), Name = name, HasDefaultValue = true, DefaultValue = defaultValue }); } public FluentAction<TP, TR, TU1, TU2> UsingService<TU2>() { return new FluentAction<TP, TR, TU1, TU2>(Definition, new FluentActionUsingServiceDefinition { Type = typeof(TU2) }); } public FluentAction<TP, TR, TU1, TU2> UsingService<TU2>(TU2 defaultValue) { return new FluentAction<TP, TR, TU1, TU2>(Definition, new FluentActionUsingServiceDefinition { Type = typeof(TU2), HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, ITempDataDictionary> UsingTempData() { return new FluentAction<TP, TR, TU1, ITempDataDictionary>(Definition, new FluentActionUsingTempDataDefinition { Type = typeof(ITempDataDictionary) }); } public virtual FluentAction<TP, TR, TU1, dynamic> UsingViewBag() { return new FluentAction<TP, TR, TU1, dynamic>(Definition, new FluentActionUsingViewBagDefinition { Type = typeof(object) }); } public virtual FluentAction<TP, TR, TU1, ViewDataDictionary> UsingViewData() { return new FluentAction<TP, TR, TU1, ViewDataDictionary>(Definition, new FluentActionUsingViewDataDefinition { Type = typeof(ViewDataDictionary) }); } public FluentAction<TP, object> Do(Action<TU1> handlerAction) { Definition.ExistingOrNewHandlerDraft.Type = FluentActionHandlerType.Action; Definition.ExistingOrNewHandlerDraft.Delegate = handlerAction; Definition.CommitHandlerDraft(); return new FluentAction<TP, object>(Definition); } public FluentAction<TP, object> DoAsync(Func<TU1, Task> asyncHandlerAction) { Definition.ExistingOrNewHandlerDraft.Type = FluentActionHandlerType.Action; Definition.ExistingOrNewHandlerDraft.Delegate = asyncHandlerAction; Definition.ExistingOrNewHandlerDraft.Async = true; Definition.CommitHandlerDraft(); return new FluentAction<TP, object>(Definition); } public virtual FluentActionWithMvcController<TU1, TC> ToMvcController<TC>() where TC : Controller { return new FluentActionWithMvcController<TU1, TC>(Definition, new FluentActionUsingMvcControllerDefinition { Type = typeof(TC) }); } public FluentAction<TP, TR2> To<TR2>(Func<TU1, TR2> handlerFunc) { return new FluentAction<TP, TR2>(Definition, handlerFunc); } public FluentAction<TP, TR2> To<TR2>(Func<TU1, Task<TR2>> asyncHandlerFunc) { return new FluentAction<TP, TR2>(Definition, asyncHandlerFunc, async: true); } public FluentActionWithView<TP> ToView(string pathToView) { return new FluentActionWithView<TP>(Definition, pathToView); } public FluentActionWithPartialView<TP> ToPartialView(string pathToView) { return new FluentActionWithPartialView<TP>(Definition, pathToView); } public FluentActionWithViewComponent<TP> ToViewComponent(Type viewComponentType) { return new FluentActionWithViewComponent<TP>(Definition, viewComponentType); } public FluentActionWithViewComponent<TP> ToViewComponent(string viewComponentName) { return new FluentActionWithViewComponent<TP>(Definition, viewComponentName); } } public class FluentAction<TP, TR, TU1, TU2> : FluentActionBase { public FluentAction(FluentActionDefinition fluentActionDefinition, FluentActionUsingDefinition usingDefinition) : base(fluentActionDefinition) { Definition.ExistingOrNewHandlerDraft.Usings.Add(usingDefinition); } public virtual FluentAction<TP, TR, TU1, TU2, TU3> Using<TU3>(FluentActionUsingDefinition usingDefinition) { return new FluentAction<TP, TR, TU1, TU2, TU3>(Definition, usingDefinition); } public FluentAction<TP, TR, TU1, TU2, TU3> UsingBody<TU3>() { return new FluentAction<TP, TR, TU1, TU2, TU3>(Definition, new FluentActionUsingBodyDefinition { Type = typeof(TU3) }); } public FluentAction<TP, TR, TU1, TU2, TU3> UsingBody<TU3>(TU3 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3>(Definition, new FluentActionUsingBodyDefinition { Type = typeof(TU3), HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3> UsingForm<TU3>() { return new FluentAction<TP, TR, TU1, TU2, TU3>(Definition, new FluentActionUsingFormDefinition { Type = typeof(TU3) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3> UsingForm<TU3>(TU3 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3>(Definition, new FluentActionUsingFormDefinition { Type = typeof(TU3), HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, IFormFile> UsingFormFile(string name) { return new FluentAction<TP, TR, TU1, TU2, IFormFile>(Definition, new FluentActionUsingFormFileDefinition { Type = typeof(IFormFile), Name = name }); } public virtual FluentAction<TP, TR, TU1, TU2, IEnumerable<IFormFile>> UsingFormFiles(string name) { return new FluentAction<TP, TR, TU1, TU2, IEnumerable<IFormFile>>(Definition, new FluentActionUsingFormFilesDefinition { Type = typeof(IEnumerable<IFormFile>), Name = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3> UsingFormValue<TU3>(string key) { return new FluentAction<TP, TR, TU1, TU2, TU3>(Definition, new FluentActionUsingFormValueDefinition { Type = typeof(TU3), Key = key }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3> UsingFormValue<TU3>(string key, TU3 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3>(Definition, new FluentActionUsingFormValueDefinition { Type = typeof(TU3), Key = key, HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3> UsingHeader<TU3>(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3>(Definition, new FluentActionUsingHeaderParameterDefinition { Type = typeof(TU3), Name = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3> UsingHeader<TU3>(string name, TU3 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3>(Definition, new FluentActionUsingHeaderParameterDefinition { Type = typeof(TU3), Name = name, HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, HttpContext> UsingHttpContext() { return new FluentAction<TP, TR, TU1, TU2, HttpContext>(Definition, new FluentActionUsingHttpContextDefinition { Type = typeof(HttpContext) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3> UsingModelBinder<TU3>(Type modelBinderType, string parameterName = null) { return new FluentAction<TP, TR, TU1, TU2, TU3>(Definition, new FluentActionUsingModelBinderDefinition { Type = typeof(TU3), ModelBinderType = modelBinderType, ParameterName = parameterName }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3> UsingModelBinder<TU3>(Type modelBinderType, string parameterName, TU3 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3>(Definition, new FluentActionUsingModelBinderDefinition { Type = typeof(TU3), ModelBinderType = modelBinderType, HasDefaultValue = true, DefaultValue = defaultValue, ParameterName = parameterName }); } public virtual FluentAction<TP, TR, TU1, TU2, ModelStateDictionary> UsingModelState() { return new FluentAction<TP, TR, TU1, TU2, ModelStateDictionary>(Definition, new FluentActionUsingModelStateDefinition { Type = typeof(ModelStateDictionary) }); } public virtual FluentAction<TP, TR, TU1, TU2, TP> UsingParent() { return new FluentAction<TP, TR, TU1, TU2, TP>(Definition, new FluentActionUsingParentDefinition { Type = typeof(TR) }); } public virtual FluentAction<TP, TR, TU1, TU2, TP2> UsingParent<TP2>() { return new FluentAction<TP, TR, TU1, TU2, TP2>(Definition, new FluentActionUsingParentDefinition { Type = typeof(TP2) }); } public virtual FluentAction<TP, TR, TU1, TU2, TPr> UsingProperty<TPr>(string name) { return new FluentAction<TP, TR, TU1, TU2, TPr>(Definition, new FluentActionUsingPropertyDefinition { Type = typeof(TPr), PropertyName = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3> UsingQueryStringParameter<TU3>(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3>(Definition, new FluentActionUsingQueryStringParameterDefinition { Type = typeof(TU3), Name = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3> UsingQueryStringParameter<TU3>(string name, TU3 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3>(Definition, new FluentActionUsingQueryStringParameterDefinition { Type = typeof(TU3), Name = name, HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, HttpRequest> UsingRequest() { return new FluentAction<TP, TR, TU1, TU2, HttpRequest>(Definition, new FluentActionUsingRequestDefinition { Type = typeof(HttpRequest) }); } public virtual FluentAction<TP, TR, TU1, TU2, HttpResponse> UsingResponse() { return new FluentAction<TP, TR, TU1, TU2, HttpResponse>(Definition, new FluentActionUsingResponseDefinition { Type = typeof(HttpResponse) }); } public virtual FluentAction<TP, TR, TU1, TU2, TR> UsingResult() { return new FluentAction<TP, TR, TU1, TU2, TR>(Definition, new FluentActionUsingResultDefinition { Type = typeof(TR) }); } public FluentAction<TP, TR, TU1, TU2, TU3> UsingRouteParameter<TU3>(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3>(Definition, new FluentActionUsingRouteParameterDefinition { Type = typeof(TU3), Name = name }); } public FluentAction<TP, TR, TU1, TU2, TU3> UsingRouteParameter<TU3>(string name, TU3 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3>(Definition, new FluentActionUsingRouteParameterDefinition { Type = typeof(TU3), Name = name, HasDefaultValue = true, DefaultValue = defaultValue }); } public FluentAction<TP, TR, TU1, TU2, TU3> UsingService<TU3>() { return new FluentAction<TP, TR, TU1, TU2, TU3>(Definition, new FluentActionUsingServiceDefinition { Type = typeof(TU3) }); } public FluentAction<TP, TR, TU1, TU2, TU3> UsingService<TU3>(TU3 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3>(Definition, new FluentActionUsingServiceDefinition { Type = typeof(TU3), HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, ITempDataDictionary> UsingTempData() { return new FluentAction<TP, TR, TU1, TU2, ITempDataDictionary>(Definition, new FluentActionUsingTempDataDefinition { Type = typeof(ITempDataDictionary) }); } public virtual FluentAction<TP, TR, TU1, TU2, dynamic> UsingViewBag() { return new FluentAction<TP, TR, TU1, TU2, dynamic>(Definition, new FluentActionUsingViewBagDefinition { Type = typeof(object) }); } public virtual FluentAction<TP, TR, TU1, TU2, ViewDataDictionary> UsingViewData() { return new FluentAction<TP, TR, TU1, TU2, ViewDataDictionary>(Definition, new FluentActionUsingViewDataDefinition { Type = typeof(ViewDataDictionary) }); } public FluentAction<TP, object> Do(Action<TU1, TU2> handlerAction) { Definition.ExistingOrNewHandlerDraft.Type = FluentActionHandlerType.Action; Definition.ExistingOrNewHandlerDraft.Delegate = handlerAction; Definition.CommitHandlerDraft(); return new FluentAction<TP, object>(Definition); } public FluentAction<TP, object> DoAsync(Func<TU1, TU2, Task> asyncHandlerAction) { Definition.ExistingOrNewHandlerDraft.Type = FluentActionHandlerType.Action; Definition.ExistingOrNewHandlerDraft.Delegate = asyncHandlerAction; Definition.ExistingOrNewHandlerDraft.Async = true; Definition.CommitHandlerDraft(); return new FluentAction<TP, object>(Definition); } public virtual FluentActionWithMvcController<TU1, TU2, TC> ToMvcController<TC>() where TC : Controller { return new FluentActionWithMvcController<TU1, TU2, TC>(Definition, new FluentActionUsingMvcControllerDefinition { Type = typeof(TC) }); } public FluentAction<TP, TR2> To<TR2>(Func<TU1, TU2, TR2> handlerFunc) { return new FluentAction<TP, TR2>(Definition, handlerFunc); } public FluentAction<TP, TR2> To<TR2>(Func<TU1, TU2, Task<TR2>> asyncHandlerFunc) { return new FluentAction<TP, TR2>(Definition, asyncHandlerFunc, async: true); } public FluentActionWithView<TP> ToView(string pathToView) { return new FluentActionWithView<TP>(Definition, pathToView); } public FluentActionWithPartialView<TP> ToPartialView(string pathToView) { return new FluentActionWithPartialView<TP>(Definition, pathToView); } public FluentActionWithViewComponent<TP> ToViewComponent(Type viewComponentType) { return new FluentActionWithViewComponent<TP>(Definition, viewComponentType); } public FluentActionWithViewComponent<TP> ToViewComponent(string viewComponentName) { return new FluentActionWithViewComponent<TP>(Definition, viewComponentName); } } public class FluentAction<TP, TR, TU1, TU2, TU3> : FluentActionBase { public FluentAction(FluentActionDefinition fluentActionDefinition, FluentActionUsingDefinition usingDefinition) : base(fluentActionDefinition) { Definition.ExistingOrNewHandlerDraft.Usings.Add(usingDefinition); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4> Using<TU4>(FluentActionUsingDefinition usingDefinition) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4>(Definition, usingDefinition); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4> UsingBody<TU4>() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4>(Definition, new FluentActionUsingBodyDefinition { Type = typeof(TU4) }); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4> UsingBody<TU4>(TU4 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4>(Definition, new FluentActionUsingBodyDefinition { Type = typeof(TU4), HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4> UsingForm<TU4>() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4>(Definition, new FluentActionUsingFormDefinition { Type = typeof(TU4) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4> UsingForm<TU4>(TU4 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4>(Definition, new FluentActionUsingFormDefinition { Type = typeof(TU4), HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, IFormFile> UsingFormFile(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, IFormFile>(Definition, new FluentActionUsingFormFileDefinition { Type = typeof(IFormFile), Name = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, IEnumerable<IFormFile>> UsingFormFiles(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, IEnumerable<IFormFile>>(Definition, new FluentActionUsingFormFilesDefinition { Type = typeof(IEnumerable<IFormFile>), Name = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4> UsingFormValue<TU4>(string key) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4>(Definition, new FluentActionUsingFormValueDefinition { Type = typeof(TU4), Key = key }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4> UsingFormValue<TU4>(string key, TU4 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4>(Definition, new FluentActionUsingFormValueDefinition { Type = typeof(TU4), Key = key, HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4> UsingHeader<TU4>(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4>(Definition, new FluentActionUsingHeaderParameterDefinition { Type = typeof(TU4), Name = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4> UsingHeader<TU4>(string name, TU4 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4>(Definition, new FluentActionUsingHeaderParameterDefinition { Type = typeof(TU4), Name = name, HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, HttpContext> UsingHttpContext() { return new FluentAction<TP, TR, TU1, TU2, TU3, HttpContext>(Definition, new FluentActionUsingHttpContextDefinition { Type = typeof(HttpContext) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4> UsingModelBinder<TU4>(Type modelBinderType, string parameterName = null) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4>(Definition, new FluentActionUsingModelBinderDefinition { Type = typeof(TU4), ModelBinderType = modelBinderType, ParameterName = parameterName }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4> UsingModelBinder<TU4>(Type modelBinderType, string parameterName, TU4 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4>(Definition, new FluentActionUsingModelBinderDefinition { Type = typeof(TU4), ModelBinderType = modelBinderType, HasDefaultValue = true, DefaultValue = defaultValue, ParameterName = parameterName }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, ModelStateDictionary> UsingModelState() { return new FluentAction<TP, TR, TU1, TU2, TU3, ModelStateDictionary>(Definition, new FluentActionUsingModelStateDefinition { Type = typeof(ModelStateDictionary) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TP> UsingParent() { return new FluentAction<TP, TR, TU1, TU2, TU3, TP>(Definition, new FluentActionUsingParentDefinition { Type = typeof(TR) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TP2> UsingParent<TP2>() { return new FluentAction<TP, TR, TU1, TU2, TU3, TP2>(Definition, new FluentActionUsingParentDefinition { Type = typeof(TP2) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TPr> UsingProperty<TPr>(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TPr>(Definition, new FluentActionUsingPropertyDefinition { Type = typeof(TPr), PropertyName = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4> UsingQueryStringParameter<TU4>(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4>(Definition, new FluentActionUsingQueryStringParameterDefinition { Type = typeof(TU4), Name = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4> UsingQueryStringParameter<TU4>(string name, TU4 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4>(Definition, new FluentActionUsingQueryStringParameterDefinition { Type = typeof(TU4), Name = name, HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, HttpRequest> UsingRequest() { return new FluentAction<TP, TR, TU1, TU2, TU3, HttpRequest>(Definition, new FluentActionUsingRequestDefinition { Type = typeof(HttpRequest) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, HttpResponse> UsingResponse() { return new FluentAction<TP, TR, TU1, TU2, TU3, HttpResponse>(Definition, new FluentActionUsingResponseDefinition { Type = typeof(HttpResponse) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TR> UsingResult() { return new FluentAction<TP, TR, TU1, TU2, TU3, TR>(Definition, new FluentActionUsingResultDefinition { Type = typeof(TR) }); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4> UsingRouteParameter<TU4>(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4>(Definition, new FluentActionUsingRouteParameterDefinition { Type = typeof(TU4), Name = name }); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4> UsingRouteParameter<TU4>(string name, TU4 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4>(Definition, new FluentActionUsingRouteParameterDefinition { Type = typeof(TU4), Name = name, HasDefaultValue = true, DefaultValue = defaultValue }); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4> UsingService<TU4>() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4>(Definition, new FluentActionUsingServiceDefinition { Type = typeof(TU4) }); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4> UsingService<TU4>(TU4 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4>(Definition, new FluentActionUsingServiceDefinition { Type = typeof(TU4), HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, ITempDataDictionary> UsingTempData() { return new FluentAction<TP, TR, TU1, TU2, TU3, ITempDataDictionary>(Definition, new FluentActionUsingTempDataDefinition { Type = typeof(ITempDataDictionary) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, dynamic> UsingViewBag() { return new FluentAction<TP, TR, TU1, TU2, TU3, dynamic>(Definition, new FluentActionUsingViewBagDefinition { Type = typeof(object) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, ViewDataDictionary> UsingViewData() { return new FluentAction<TP, TR, TU1, TU2, TU3, ViewDataDictionary>(Definition, new FluentActionUsingViewDataDefinition { Type = typeof(ViewDataDictionary) }); } public FluentAction<TP, object> Do(Action<TU1, TU2, TU3> handlerAction) { Definition.ExistingOrNewHandlerDraft.Type = FluentActionHandlerType.Action; Definition.ExistingOrNewHandlerDraft.Delegate = handlerAction; Definition.CommitHandlerDraft(); return new FluentAction<TP, object>(Definition); } public FluentAction<TP, object> DoAsync(Func<TU1, TU2, TU3, Task> asyncHandlerAction) { Definition.ExistingOrNewHandlerDraft.Type = FluentActionHandlerType.Action; Definition.ExistingOrNewHandlerDraft.Delegate = asyncHandlerAction; Definition.ExistingOrNewHandlerDraft.Async = true; Definition.CommitHandlerDraft(); return new FluentAction<TP, object>(Definition); } public virtual FluentActionWithMvcController<TU1, TU2, TU3, TC> ToMvcController<TC>() where TC : Controller { return new FluentActionWithMvcController<TU1, TU2, TU3, TC>(Definition, new FluentActionUsingMvcControllerDefinition { Type = typeof(TC) }); } public FluentAction<TP, TR2> To<TR2>(Func<TU1, TU2, TU3, TR2> handlerFunc) { return new FluentAction<TP, TR2>(Definition, handlerFunc); } public FluentAction<TP, TR2> To<TR2>(Func<TU1, TU2, TU3, Task<TR2>> asyncHandlerFunc) { return new FluentAction<TP, TR2>(Definition, asyncHandlerFunc, async: true); } public FluentActionWithView<TP> ToView(string pathToView) { return new FluentActionWithView<TP>(Definition, pathToView); } public FluentActionWithPartialView<TP> ToPartialView(string pathToView) { return new FluentActionWithPartialView<TP>(Definition, pathToView); } public FluentActionWithViewComponent<TP> ToViewComponent(Type viewComponentType) { return new FluentActionWithViewComponent<TP>(Definition, viewComponentType); } public FluentActionWithViewComponent<TP> ToViewComponent(string viewComponentName) { return new FluentActionWithViewComponent<TP>(Definition, viewComponentName); } } public class FluentAction<TP, TR, TU1, TU2, TU3, TU4> : FluentActionBase { public FluentAction(FluentActionDefinition fluentActionDefinition, FluentActionUsingDefinition usingDefinition) : base(fluentActionDefinition) { Definition.ExistingOrNewHandlerDraft.Usings.Add(usingDefinition); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5> Using<TU5>(FluentActionUsingDefinition usingDefinition) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5>(Definition, usingDefinition); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5> UsingBody<TU5>() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5>(Definition, new FluentActionUsingBodyDefinition { Type = typeof(TU5) }); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5> UsingBody<TU5>(TU5 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5>(Definition, new FluentActionUsingBodyDefinition { Type = typeof(TU5), HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5> UsingForm<TU5>() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5>(Definition, new FluentActionUsingFormDefinition { Type = typeof(TU5) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5> UsingForm<TU5>(TU5 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5>(Definition, new FluentActionUsingFormDefinition { Type = typeof(TU5), HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, IFormFile> UsingFormFile(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, IFormFile>(Definition, new FluentActionUsingFormFileDefinition { Type = typeof(IFormFile), Name = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, IEnumerable<IFormFile>> UsingFormFiles(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, IEnumerable<IFormFile>>(Definition, new FluentActionUsingFormFilesDefinition { Type = typeof(IEnumerable<IFormFile>), Name = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5> UsingFormValue<TU5>(string key) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5>(Definition, new FluentActionUsingFormValueDefinition { Type = typeof(TU5), Key = key }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5> UsingFormValue<TU5>(string key, TU5 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5>(Definition, new FluentActionUsingFormValueDefinition { Type = typeof(TU5), Key = key, HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5> UsingHeader<TU5>(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5>(Definition, new FluentActionUsingHeaderParameterDefinition { Type = typeof(TU5), Name = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5> UsingHeader<TU5>(string name, TU5 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5>(Definition, new FluentActionUsingHeaderParameterDefinition { Type = typeof(TU5), Name = name, HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, HttpContext> UsingHttpContext() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, HttpContext>(Definition, new FluentActionUsingHttpContextDefinition { Type = typeof(HttpContext) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5> UsingModelBinder<TU5>(Type modelBinderType, string parameterName = null) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5>(Definition, new FluentActionUsingModelBinderDefinition { Type = typeof(TU5), ModelBinderType = modelBinderType, ParameterName = parameterName }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5> UsingModelBinder<TU5>(Type modelBinderType, string parameterName, TU5 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5>(Definition, new FluentActionUsingModelBinderDefinition { Type = typeof(TU5), ModelBinderType = modelBinderType, HasDefaultValue = true, DefaultValue = defaultValue, ParameterName = parameterName }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, ModelStateDictionary> UsingModelState() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, ModelStateDictionary>(Definition, new FluentActionUsingModelStateDefinition { Type = typeof(ModelStateDictionary) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TP> UsingParent() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TP>(Definition, new FluentActionUsingParentDefinition { Type = typeof(TR) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TP2> UsingParent<TP2>() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TP2>(Definition, new FluentActionUsingParentDefinition { Type = typeof(TP2) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TPr> UsingProperty<TPr>(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TPr>(Definition, new FluentActionUsingPropertyDefinition { Type = typeof(TPr), PropertyName = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5> UsingQueryStringParameter<TU5>(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5>(Definition, new FluentActionUsingQueryStringParameterDefinition { Type = typeof(TU5), Name = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5> UsingQueryStringParameter<TU5>(string name, TU5 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5>(Definition, new FluentActionUsingQueryStringParameterDefinition { Type = typeof(TU5), Name = name, HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, HttpRequest> UsingRequest() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, HttpRequest>(Definition, new FluentActionUsingRequestDefinition { Type = typeof(HttpRequest) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, HttpResponse> UsingResponse() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, HttpResponse>(Definition, new FluentActionUsingResponseDefinition { Type = typeof(HttpResponse) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TR> UsingResult() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TR>(Definition, new FluentActionUsingResultDefinition { Type = typeof(TR) }); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5> UsingRouteParameter<TU5>(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5>(Definition, new FluentActionUsingRouteParameterDefinition { Type = typeof(TU5), Name = name }); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5> UsingRouteParameter<TU5>(string name, TU5 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5>(Definition, new FluentActionUsingRouteParameterDefinition { Type = typeof(TU5), Name = name, HasDefaultValue = true, DefaultValue = defaultValue }); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5> UsingService<TU5>() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5>(Definition, new FluentActionUsingServiceDefinition { Type = typeof(TU5) }); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5> UsingService<TU5>(TU5 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5>(Definition, new FluentActionUsingServiceDefinition { Type = typeof(TU5), HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, ITempDataDictionary> UsingTempData() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, ITempDataDictionary>(Definition, new FluentActionUsingTempDataDefinition { Type = typeof(ITempDataDictionary) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, dynamic> UsingViewBag() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, dynamic>(Definition, new FluentActionUsingViewBagDefinition { Type = typeof(object) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, ViewDataDictionary> UsingViewData() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, ViewDataDictionary>(Definition, new FluentActionUsingViewDataDefinition { Type = typeof(ViewDataDictionary) }); } public FluentAction<TP, object> Do(Action<TU1, TU2, TU3, TU4> handlerAction) { Definition.ExistingOrNewHandlerDraft.Type = FluentActionHandlerType.Action; Definition.ExistingOrNewHandlerDraft.Delegate = handlerAction; Definition.CommitHandlerDraft(); return new FluentAction<TP, object>(Definition); } public FluentAction<TP, object> DoAsync(Func<TU1, TU2, TU3, TU4, Task> asyncHandlerAction) { Definition.ExistingOrNewHandlerDraft.Type = FluentActionHandlerType.Action; Definition.ExistingOrNewHandlerDraft.Delegate = asyncHandlerAction; Definition.ExistingOrNewHandlerDraft.Async = true; Definition.CommitHandlerDraft(); return new FluentAction<TP, object>(Definition); } public virtual FluentActionWithMvcController<TU1, TU2, TU3, TU4, TC> ToMvcController<TC>() where TC : Controller { return new FluentActionWithMvcController<TU1, TU2, TU3, TU4, TC>(Definition, new FluentActionUsingMvcControllerDefinition { Type = typeof(TC) }); } public FluentAction<TP, TR2> To<TR2>(Func<TU1, TU2, TU3, TU4, TR2> handlerFunc) { return new FluentAction<TP, TR2>(Definition, handlerFunc); } public FluentAction<TP, TR2> To<TR2>(Func<TU1, TU2, TU3, TU4, Task<TR2>> asyncHandlerFunc) { return new FluentAction<TP, TR2>(Definition, asyncHandlerFunc, async: true); } public FluentActionWithView<TP> ToView(string pathToView) { return new FluentActionWithView<TP>(Definition, pathToView); } public FluentActionWithPartialView<TP> ToPartialView(string pathToView) { return new FluentActionWithPartialView<TP>(Definition, pathToView); } public FluentActionWithViewComponent<TP> ToViewComponent(Type viewComponentType) { return new FluentActionWithViewComponent<TP>(Definition, viewComponentType); } public FluentActionWithViewComponent<TP> ToViewComponent(string viewComponentName) { return new FluentActionWithViewComponent<TP>(Definition, viewComponentName); } } public class FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5> : FluentActionBase { public FluentAction(FluentActionDefinition fluentActionDefinition, FluentActionUsingDefinition usingDefinition) : base(fluentActionDefinition) { Definition.ExistingOrNewHandlerDraft.Usings.Add(usingDefinition); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6> Using<TU6>(FluentActionUsingDefinition usingDefinition) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6>(Definition, usingDefinition); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6> UsingBody<TU6>() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6>(Definition, new FluentActionUsingBodyDefinition { Type = typeof(TU6) }); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6> UsingBody<TU6>(TU6 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6>(Definition, new FluentActionUsingBodyDefinition { Type = typeof(TU6), HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6> UsingForm<TU6>() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6>(Definition, new FluentActionUsingFormDefinition { Type = typeof(TU6) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6> UsingForm<TU6>(TU6 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6>(Definition, new FluentActionUsingFormDefinition { Type = typeof(TU6), HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, IFormFile> UsingFormFile(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, IFormFile>(Definition, new FluentActionUsingFormFileDefinition { Type = typeof(IFormFile), Name = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, IEnumerable<IFormFile>> UsingFormFiles(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, IEnumerable<IFormFile>>(Definition, new FluentActionUsingFormFilesDefinition { Type = typeof(IEnumerable<IFormFile>), Name = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6> UsingFormValue<TU6>(string key) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6>(Definition, new FluentActionUsingFormValueDefinition { Type = typeof(TU6), Key = key }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6> UsingFormValue<TU6>(string key, TU6 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6>(Definition, new FluentActionUsingFormValueDefinition { Type = typeof(TU6), Key = key, HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6> UsingHeader<TU6>(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6>(Definition, new FluentActionUsingHeaderParameterDefinition { Type = typeof(TU6), Name = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6> UsingHeader<TU6>(string name, TU6 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6>(Definition, new FluentActionUsingHeaderParameterDefinition { Type = typeof(TU6), Name = name, HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, HttpContext> UsingHttpContext() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, HttpContext>(Definition, new FluentActionUsingHttpContextDefinition { Type = typeof(HttpContext) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6> UsingModelBinder<TU6>(Type modelBinderType, string parameterName = null) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6>(Definition, new FluentActionUsingModelBinderDefinition { Type = typeof(TU6), ModelBinderType = modelBinderType, ParameterName = parameterName }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6> UsingModelBinder<TU6>(Type modelBinderType, string parameterName, TU6 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6>(Definition, new FluentActionUsingModelBinderDefinition { Type = typeof(TU6), ModelBinderType = modelBinderType, HasDefaultValue = true, DefaultValue = defaultValue, ParameterName = parameterName }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, ModelStateDictionary> UsingModelState() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, ModelStateDictionary>(Definition, new FluentActionUsingModelStateDefinition { Type = typeof(ModelStateDictionary) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TP> UsingParent() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TP>(Definition, new FluentActionUsingParentDefinition { Type = typeof(TR) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TP2> UsingParent<TP2>() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TP2>(Definition, new FluentActionUsingParentDefinition { Type = typeof(TP2) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TPr> UsingProperty<TPr>(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TPr>(Definition, new FluentActionUsingPropertyDefinition { Type = typeof(TPr), PropertyName = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6> UsingQueryStringParameter<TU6>(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6>(Definition, new FluentActionUsingQueryStringParameterDefinition { Type = typeof(TU6), Name = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6> UsingQueryStringParameter<TU6>(string name, TU6 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6>(Definition, new FluentActionUsingQueryStringParameterDefinition { Type = typeof(TU6), Name = name, HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, HttpRequest> UsingRequest() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, HttpRequest>(Definition, new FluentActionUsingRequestDefinition { Type = typeof(HttpRequest) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, HttpResponse> UsingResponse() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, HttpResponse>(Definition, new FluentActionUsingResponseDefinition { Type = typeof(HttpResponse) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TR> UsingResult() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TR>(Definition, new FluentActionUsingResultDefinition { Type = typeof(TR) }); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6> UsingRouteParameter<TU6>(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6>(Definition, new FluentActionUsingRouteParameterDefinition { Type = typeof(TU6), Name = name }); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6> UsingRouteParameter<TU6>(string name, TU6 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6>(Definition, new FluentActionUsingRouteParameterDefinition { Type = typeof(TU6), Name = name, HasDefaultValue = true, DefaultValue = defaultValue }); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6> UsingService<TU6>() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6>(Definition, new FluentActionUsingServiceDefinition { Type = typeof(TU6) }); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6> UsingService<TU6>(TU6 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6>(Definition, new FluentActionUsingServiceDefinition { Type = typeof(TU6), HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, ITempDataDictionary> UsingTempData() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, ITempDataDictionary>(Definition, new FluentActionUsingTempDataDefinition { Type = typeof(ITempDataDictionary) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, dynamic> UsingViewBag() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, dynamic>(Definition, new FluentActionUsingViewBagDefinition { Type = typeof(object) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, ViewDataDictionary> UsingViewData() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, ViewDataDictionary>(Definition, new FluentActionUsingViewDataDefinition { Type = typeof(ViewDataDictionary) }); } public FluentAction<TP, object> Do(Action<TU1, TU2, TU3, TU4, TU5> handlerAction) { Definition.ExistingOrNewHandlerDraft.Type = FluentActionHandlerType.Action; Definition.ExistingOrNewHandlerDraft.Delegate = handlerAction; Definition.CommitHandlerDraft(); return new FluentAction<TP, object>(Definition); } public FluentAction<TP, object> DoAsync(Func<TU1, TU2, TU3, TU4, TU5, Task> asyncHandlerAction) { Definition.ExistingOrNewHandlerDraft.Type = FluentActionHandlerType.Action; Definition.ExistingOrNewHandlerDraft.Delegate = asyncHandlerAction; Definition.ExistingOrNewHandlerDraft.Async = true; Definition.CommitHandlerDraft(); return new FluentAction<TP, object>(Definition); } public virtual FluentActionWithMvcController<TU1, TU2, TU3, TU4, TU5, TC> ToMvcController<TC>() where TC : Controller { return new FluentActionWithMvcController<TU1, TU2, TU3, TU4, TU5, TC>(Definition, new FluentActionUsingMvcControllerDefinition { Type = typeof(TC) }); } public FluentAction<TP, TR2> To<TR2>(Func<TU1, TU2, TU3, TU4, TU5, TR2> handlerFunc) { return new FluentAction<TP, TR2>(Definition, handlerFunc); } public FluentAction<TP, TR2> To<TR2>(Func<TU1, TU2, TU3, TU4, TU5, Task<TR2>> asyncHandlerFunc) { return new FluentAction<TP, TR2>(Definition, asyncHandlerFunc, async: true); } public FluentActionWithView<TP> ToView(string pathToView) { return new FluentActionWithView<TP>(Definition, pathToView); } public FluentActionWithPartialView<TP> ToPartialView(string pathToView) { return new FluentActionWithPartialView<TP>(Definition, pathToView); } public FluentActionWithViewComponent<TP> ToViewComponent(Type viewComponentType) { return new FluentActionWithViewComponent<TP>(Definition, viewComponentType); } public FluentActionWithViewComponent<TP> ToViewComponent(string viewComponentName) { return new FluentActionWithViewComponent<TP>(Definition, viewComponentName); } } public class FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6> : FluentActionBase { public FluentAction(FluentActionDefinition fluentActionDefinition, FluentActionUsingDefinition usingDefinition) : base(fluentActionDefinition) { Definition.ExistingOrNewHandlerDraft.Usings.Add(usingDefinition); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7> Using<TU7>(FluentActionUsingDefinition usingDefinition) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7>(Definition, usingDefinition); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7> UsingBody<TU7>() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7>(Definition, new FluentActionUsingBodyDefinition { Type = typeof(TU7) }); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7> UsingBody<TU7>(TU7 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7>(Definition, new FluentActionUsingBodyDefinition { Type = typeof(TU7), HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7> UsingForm<TU7>() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7>(Definition, new FluentActionUsingFormDefinition { Type = typeof(TU7) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7> UsingForm<TU7>(TU7 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7>(Definition, new FluentActionUsingFormDefinition { Type = typeof(TU7), HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, IFormFile> UsingFormFile(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, IFormFile>(Definition, new FluentActionUsingFormFileDefinition { Type = typeof(IFormFile), Name = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, IEnumerable<IFormFile>> UsingFormFiles(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, IEnumerable<IFormFile>>(Definition, new FluentActionUsingFormFilesDefinition { Type = typeof(IEnumerable<IFormFile>), Name = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7> UsingFormValue<TU7>(string key) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7>(Definition, new FluentActionUsingFormValueDefinition { Type = typeof(TU7), Key = key }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7> UsingFormValue<TU7>(string key, TU7 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7>(Definition, new FluentActionUsingFormValueDefinition { Type = typeof(TU7), Key = key, HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7> UsingHeader<TU7>(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7>(Definition, new FluentActionUsingHeaderParameterDefinition { Type = typeof(TU7), Name = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7> UsingHeader<TU7>(string name, TU7 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7>(Definition, new FluentActionUsingHeaderParameterDefinition { Type = typeof(TU7), Name = name, HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, HttpContext> UsingHttpContext() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, HttpContext>(Definition, new FluentActionUsingHttpContextDefinition { Type = typeof(HttpContext) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7> UsingModelBinder<TU7>(Type modelBinderType, string parameterName = null) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7>(Definition, new FluentActionUsingModelBinderDefinition { Type = typeof(TU7), ModelBinderType = modelBinderType, ParameterName = parameterName }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7> UsingModelBinder<TU7>(Type modelBinderType, string parameterName, TU7 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7>(Definition, new FluentActionUsingModelBinderDefinition { Type = typeof(TU7), ModelBinderType = modelBinderType, HasDefaultValue = true, DefaultValue = defaultValue, ParameterName = parameterName }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, ModelStateDictionary> UsingModelState() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, ModelStateDictionary>(Definition, new FluentActionUsingModelStateDefinition { Type = typeof(ModelStateDictionary) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TP> UsingParent() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TP>(Definition, new FluentActionUsingParentDefinition { Type = typeof(TR) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TP2> UsingParent<TP2>() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TP2>(Definition, new FluentActionUsingParentDefinition { Type = typeof(TP2) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TPr> UsingProperty<TPr>(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TPr>(Definition, new FluentActionUsingPropertyDefinition { Type = typeof(TPr), PropertyName = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7> UsingQueryStringParameter<TU7>(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7>(Definition, new FluentActionUsingQueryStringParameterDefinition { Type = typeof(TU7), Name = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7> UsingQueryStringParameter<TU7>(string name, TU7 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7>(Definition, new FluentActionUsingQueryStringParameterDefinition { Type = typeof(TU7), Name = name, HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, HttpRequest> UsingRequest() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, HttpRequest>(Definition, new FluentActionUsingRequestDefinition { Type = typeof(HttpRequest) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, HttpResponse> UsingResponse() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, HttpResponse>(Definition, new FluentActionUsingResponseDefinition { Type = typeof(HttpResponse) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TR> UsingResult() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TR>(Definition, new FluentActionUsingResultDefinition { Type = typeof(TR) }); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7> UsingRouteParameter<TU7>(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7>(Definition, new FluentActionUsingRouteParameterDefinition { Type = typeof(TU7), Name = name }); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7> UsingRouteParameter<TU7>(string name, TU7 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7>(Definition, new FluentActionUsingRouteParameterDefinition { Type = typeof(TU7), Name = name, HasDefaultValue = true, DefaultValue = defaultValue }); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7> UsingService<TU7>() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7>(Definition, new FluentActionUsingServiceDefinition { Type = typeof(TU7) }); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7> UsingService<TU7>(TU7 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7>(Definition, new FluentActionUsingServiceDefinition { Type = typeof(TU7), HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, ITempDataDictionary> UsingTempData() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, ITempDataDictionary>(Definition, new FluentActionUsingTempDataDefinition { Type = typeof(ITempDataDictionary) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, dynamic> UsingViewBag() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, dynamic>(Definition, new FluentActionUsingViewBagDefinition { Type = typeof(object) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, ViewDataDictionary> UsingViewData() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, ViewDataDictionary>(Definition, new FluentActionUsingViewDataDefinition { Type = typeof(ViewDataDictionary) }); } public FluentAction<TP, object> Do(Action<TU1, TU2, TU3, TU4, TU5, TU6> handlerAction) { Definition.ExistingOrNewHandlerDraft.Type = FluentActionHandlerType.Action; Definition.ExistingOrNewHandlerDraft.Delegate = handlerAction; Definition.CommitHandlerDraft(); return new FluentAction<TP, object>(Definition); } public FluentAction<TP, object> DoAsync(Func<TU1, TU2, TU3, TU4, TU5, TU6, Task> asyncHandlerAction) { Definition.ExistingOrNewHandlerDraft.Type = FluentActionHandlerType.Action; Definition.ExistingOrNewHandlerDraft.Delegate = asyncHandlerAction; Definition.ExistingOrNewHandlerDraft.Async = true; Definition.CommitHandlerDraft(); return new FluentAction<TP, object>(Definition); } public virtual FluentActionWithMvcController<TU1, TU2, TU3, TU4, TU5, TU6, TC> ToMvcController<TC>() where TC : Controller { return new FluentActionWithMvcController<TU1, TU2, TU3, TU4, TU5, TU6, TC>(Definition, new FluentActionUsingMvcControllerDefinition { Type = typeof(TC) }); } public FluentAction<TP, TR2> To<TR2>(Func<TU1, TU2, TU3, TU4, TU5, TU6, TR2> handlerFunc) { return new FluentAction<TP, TR2>(Definition, handlerFunc); } public FluentAction<TP, TR2> To<TR2>(Func<TU1, TU2, TU3, TU4, TU5, TU6, Task<TR2>> asyncHandlerFunc) { return new FluentAction<TP, TR2>(Definition, asyncHandlerFunc, async: true); } public FluentActionWithView<TP> ToView(string pathToView) { return new FluentActionWithView<TP>(Definition, pathToView); } public FluentActionWithPartialView<TP> ToPartialView(string pathToView) { return new FluentActionWithPartialView<TP>(Definition, pathToView); } public FluentActionWithViewComponent<TP> ToViewComponent(Type viewComponentType) { return new FluentActionWithViewComponent<TP>(Definition, viewComponentType); } public FluentActionWithViewComponent<TP> ToViewComponent(string viewComponentName) { return new FluentActionWithViewComponent<TP>(Definition, viewComponentName); } } public class FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7> : FluentActionBase { public FluentAction(FluentActionDefinition fluentActionDefinition, FluentActionUsingDefinition usingDefinition) : base(fluentActionDefinition) { Definition.ExistingOrNewHandlerDraft.Usings.Add(usingDefinition); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8> Using<TU8>(FluentActionUsingDefinition usingDefinition) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8>(Definition, usingDefinition); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8> UsingBody<TU8>() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8>(Definition, new FluentActionUsingBodyDefinition { Type = typeof(TU8) }); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8> UsingBody<TU8>(TU8 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8>(Definition, new FluentActionUsingBodyDefinition { Type = typeof(TU8), HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8> UsingForm<TU8>() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8>(Definition, new FluentActionUsingFormDefinition { Type = typeof(TU8) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8> UsingForm<TU8>(TU8 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8>(Definition, new FluentActionUsingFormDefinition { Type = typeof(TU8), HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, IFormFile> UsingFormFile(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, IFormFile>(Definition, new FluentActionUsingFormFileDefinition { Type = typeof(IFormFile), Name = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, IEnumerable<IFormFile>> UsingFormFiles(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, IEnumerable<IFormFile>>(Definition, new FluentActionUsingFormFilesDefinition { Type = typeof(IEnumerable<IFormFile>), Name = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8> UsingFormValue<TU8>(string key) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8>(Definition, new FluentActionUsingFormValueDefinition { Type = typeof(TU8), Key = key }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8> UsingFormValue<TU8>(string key, TU8 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8>(Definition, new FluentActionUsingFormValueDefinition { Type = typeof(TU8), Key = key, HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8> UsingHeader<TU8>(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8>(Definition, new FluentActionUsingHeaderParameterDefinition { Type = typeof(TU8), Name = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8> UsingHeader<TU8>(string name, TU8 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8>(Definition, new FluentActionUsingHeaderParameterDefinition { Type = typeof(TU8), Name = name, HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, HttpContext> UsingHttpContext() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, HttpContext>(Definition, new FluentActionUsingHttpContextDefinition { Type = typeof(HttpContext) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8> UsingModelBinder<TU8>(Type modelBinderType, string parameterName = null) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8>(Definition, new FluentActionUsingModelBinderDefinition { Type = typeof(TU8), ModelBinderType = modelBinderType, ParameterName = parameterName }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8> UsingModelBinder<TU8>(Type modelBinderType, string parameterName, TU8 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8>(Definition, new FluentActionUsingModelBinderDefinition { Type = typeof(TU8), ModelBinderType = modelBinderType, HasDefaultValue = true, DefaultValue = defaultValue, ParameterName = parameterName }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, ModelStateDictionary> UsingModelState() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, ModelStateDictionary>(Definition, new FluentActionUsingModelStateDefinition { Type = typeof(ModelStateDictionary) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TP> UsingParent() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TP>(Definition, new FluentActionUsingParentDefinition { Type = typeof(TR) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TP2> UsingParent<TP2>() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TP2>(Definition, new FluentActionUsingParentDefinition { Type = typeof(TP2) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TPr> UsingProperty<TPr>(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TPr>(Definition, new FluentActionUsingPropertyDefinition { Type = typeof(TPr), PropertyName = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8> UsingQueryStringParameter<TU8>(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8>(Definition, new FluentActionUsingQueryStringParameterDefinition { Type = typeof(TU8), Name = name }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8> UsingQueryStringParameter<TU8>(string name, TU8 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8>(Definition, new FluentActionUsingQueryStringParameterDefinition { Type = typeof(TU8), Name = name, HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, HttpRequest> UsingRequest() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, HttpRequest>(Definition, new FluentActionUsingRequestDefinition { Type = typeof(HttpRequest) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, HttpResponse> UsingResponse() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, HttpResponse>(Definition, new FluentActionUsingResponseDefinition { Type = typeof(HttpResponse) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TR> UsingResult() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TR>(Definition, new FluentActionUsingResultDefinition { Type = typeof(TR) }); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8> UsingRouteParameter<TU8>(string name) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8>(Definition, new FluentActionUsingRouteParameterDefinition { Type = typeof(TU8), Name = name }); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8> UsingRouteParameter<TU8>(string name, TU8 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8>(Definition, new FluentActionUsingRouteParameterDefinition { Type = typeof(TU8), Name = name, HasDefaultValue = true, DefaultValue = defaultValue }); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8> UsingService<TU8>() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8>(Definition, new FluentActionUsingServiceDefinition { Type = typeof(TU8) }); } public FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8> UsingService<TU8>(TU8 defaultValue) { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8>(Definition, new FluentActionUsingServiceDefinition { Type = typeof(TU8), HasDefaultValue = true, DefaultValue = defaultValue }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, ITempDataDictionary> UsingTempData() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, ITempDataDictionary>(Definition, new FluentActionUsingTempDataDefinition { Type = typeof(ITempDataDictionary) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, dynamic> UsingViewBag() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, dynamic>(Definition, new FluentActionUsingViewBagDefinition { Type = typeof(object) }); } public virtual FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, ViewDataDictionary> UsingViewData() { return new FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, ViewDataDictionary>(Definition, new FluentActionUsingViewDataDefinition { Type = typeof(ViewDataDictionary) }); } public FluentAction<TP, object> Do(Action<TU1, TU2, TU3, TU4, TU5, TU6, TU7> handlerAction) { Definition.ExistingOrNewHandlerDraft.Type = FluentActionHandlerType.Action; Definition.ExistingOrNewHandlerDraft.Delegate = handlerAction; Definition.CommitHandlerDraft(); return new FluentAction<TP, object>(Definition); } public FluentAction<TP, object> DoAsync(Func<TU1, TU2, TU3, TU4, TU5, TU6, TU7, Task> asyncHandlerAction) { Definition.ExistingOrNewHandlerDraft.Type = FluentActionHandlerType.Action; Definition.ExistingOrNewHandlerDraft.Delegate = asyncHandlerAction; Definition.ExistingOrNewHandlerDraft.Async = true; Definition.CommitHandlerDraft(); return new FluentAction<TP, object>(Definition); } public virtual FluentActionWithMvcController<TU1, TU2, TU3, TU4, TU5, TU6, TU7, TC> ToMvcController<TC>() where TC : Controller { return new FluentActionWithMvcController<TU1, TU2, TU3, TU4, TU5, TU6, TU7, TC>(Definition, new FluentActionUsingMvcControllerDefinition { Type = typeof(TC) }); } public FluentAction<TP, TR2> To<TR2>(Func<TU1, TU2, TU3, TU4, TU5, TU6, TU7, TR2> handlerFunc) { return new FluentAction<TP, TR2>(Definition, handlerFunc); } public FluentAction<TP, TR2> To<TR2>(Func<TU1, TU2, TU3, TU4, TU5, TU6, TU7, Task<TR2>> asyncHandlerFunc) { return new FluentAction<TP, TR2>(Definition, asyncHandlerFunc, async: true); } public FluentActionWithView<TP> ToView(string pathToView) { return new FluentActionWithView<TP>(Definition, pathToView); } public FluentActionWithPartialView<TP> ToPartialView(string pathToView) { return new FluentActionWithPartialView<TP>(Definition, pathToView); } public FluentActionWithViewComponent<TP> ToViewComponent(Type viewComponentType) { return new FluentActionWithViewComponent<TP>(Definition, viewComponentType); } public FluentActionWithViewComponent<TP> ToViewComponent(string viewComponentName) { return new FluentActionWithViewComponent<TP>(Definition, viewComponentName); } } public class FluentAction<TP, TR, TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8> : FluentActionBase { public FluentAction(FluentActionDefinition fluentActionDefinition, FluentActionUsingDefinition usingDefinition) : base(fluentActionDefinition) { Definition.ExistingOrNewHandlerDraft.Usings.Add(usingDefinition); } public FluentAction<TP, object> Do(Action<TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8> handlerAction) { Definition.ExistingOrNewHandlerDraft.Type = FluentActionHandlerType.Action; Definition.ExistingOrNewHandlerDraft.Delegate = handlerAction; Definition.CommitHandlerDraft(); return new FluentAction<TP, object>(Definition); } public FluentAction<TP, object> DoAsync(Func<TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8, Task> asyncHandlerAction) { Definition.ExistingOrNewHandlerDraft.Type = FluentActionHandlerType.Action; Definition.ExistingOrNewHandlerDraft.Delegate = asyncHandlerAction; Definition.ExistingOrNewHandlerDraft.Async = true; Definition.CommitHandlerDraft(); return new FluentAction<TP, object>(Definition); } public virtual FluentActionWithMvcController<TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8, TC> ToMvcController<TC>() where TC : Controller { return new FluentActionWithMvcController<TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8, TC>(Definition, new FluentActionUsingMvcControllerDefinition { Type = typeof(TC) }); } public FluentAction<TP, TR2> To<TR2>(Func<TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8, TR2> handlerFunc) { return new FluentAction<TP, TR2>(Definition, handlerFunc); } public FluentAction<TP, TR2> To<TR2>(Func<TU1, TU2, TU3, TU4, TU5, TU6, TU7, TU8, Task<TR2>> asyncHandlerFunc) { return new FluentAction<TP, TR2>(Definition, asyncHandlerFunc, async: true); } public FluentActionWithView<TP> ToView(string pathToView) { return new FluentActionWithView<TP>(Definition, pathToView); } public FluentActionWithPartialView<TP> ToPartialView(string pathToView) { return new FluentActionWithPartialView<TP>(Definition, pathToView); } public FluentActionWithViewComponent<TP> ToViewComponent(Type viewComponentType) { return new FluentActionWithViewComponent<TP>(Definition, viewComponentType); } public FluentActionWithViewComponent<TP> ToViewComponent(string viewComponentName) { return new FluentActionWithViewComponent<TP>(Definition, viewComponentName); } } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/FluentActionCustomAttribute.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using System; using System.Reflection; namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions { public class FluentActionCustomAttribute { public Type Type { get; internal set; } public ConstructorInfo Constructor { get; internal set; } public object[] ConstructorArgs { get; internal set; } public PropertyInfo[] NamedProperties { get; internal set; } public object[] PropertyValues { get; internal set; } public FieldInfo[] NamedFields { get; internal set; } public object[] FieldValues { get; internal set; } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/ParameterlessControllers.cs<|end_filename|> using Microsoft.AspNetCore.Mvc; using System; using System.Threading.Tasks; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { public class ParameterlessControllerReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction() { return "Hello"; } } public class ParameterlessControllerReturnsStringAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<string> HandlerAction() { await Task.Delay(1); return "Hello"; } } public class ParameterlessControllerReturnsInt : Controller { [HttpGet] [Route("/route/url")] public int HandlerAction() { return 13; } } public class ParameterlessControllerReturnsIntAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<int> HandlerAction() { await Task.Delay(1); return 13; } } public class ParameterlessControllerReturnsGuid : Controller { [HttpGet] [Route("/route/url")] public Guid HandlerAction() { return new Guid("2a6d4959-817c-4514-90f3-52b518e9ddb0"); } } public class ParameterlessControllerReturnsGuidAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<Guid> HandlerAction() { await Task.Delay(1); return new Guid("2a6d4959-817c-4514-90f3-52b518e9ddb0"); } } public enum ExampleEnumWithoutUsings { ExampleEnumValue1, ExampleEnumValue2, ExampleEnumValue3 } public class ParameterlessControllerReturnsEnum : Controller { [HttpGet] [Route("/route/url")] public ExampleEnumWithoutUsings HandlerAction() { return ExampleEnumWithoutUsings.ExampleEnumValue2; } } public class ParameterlessControllerReturnsEnumAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<ExampleEnumWithoutUsings> HandlerAction() { await Task.Delay(1); return ExampleEnumWithoutUsings.ExampleEnumValue2; } } public class ExampleClassWithoutUsings { public string StringField; public int IntField; public string StringProperty { get; set; } public override bool Equals(object obj) { return obj is ExampleClassWithoutUsings && ((ExampleClassWithoutUsings)obj).StringField == StringField && ((ExampleClassWithoutUsings)obj).IntField == IntField && ((ExampleClassWithoutUsings)obj).StringProperty == StringProperty; } public override int GetHashCode() { return $"{StringField}-{IntField}-{StringProperty}".GetHashCode(); } } public class ParameterlessControllerReturnsObject : Controller { [HttpGet] [Route("/route/url")] public ExampleClassWithoutUsings HandlerAction() { return new ExampleClassWithoutUsings { StringField = "Hello", IntField = 14, StringProperty = "World!" }; } } public class ParameterlessControllerReturnsObjectAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<ExampleClassWithoutUsings> HandlerAction() { await Task.Delay(1); return new ExampleClassWithoutUsings { StringField = "Hello", IntField = 14, StringProperty = "World!" }; } } } <|start_filename|>test/WebApps/MvcWithSwagger/Views/_ViewImports.cshtml<|end_filename|> @using MvcWithSwagger @using MvcWithSwagger.Models @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithModelState.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithModelState { [Fact(DisplayName = "1 model state, returns string")] public void FluentControllerBuilder_FluentActionWithModelStateReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticAction( new FluentAction("/route/url", HttpMethod.Post) .UsingModelState() .To(modelState => $"Hello World!"), typeof(ControllerWithModelStateReturnsString)); } [Fact(DisplayName = "1 model state, returns string async")] public void FluentControllerBuilder_FluentActionWithModelStateReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticAction( new FluentAction("/route/url", HttpMethod.Post) .UsingModelState() .To(async modelState => { await Task.Delay(1); return $"Hello World!"; }), typeof(ControllerWithModelStateReturnsStringAsync)); } } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/UsingDefinitions/FluentActionUsingDefinition.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using System; using System.Reflection; using System.Reflection.Emit; namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions { public abstract class FluentActionUsingDefinition { public Type Type { get; set; } public bool HasDefaultValue { get; set; } public object DefaultValue { get; set; } public virtual bool IsMethodParameter => false; public virtual string MethodParameterName => null; public virtual bool IsControllerProperty => false; public virtual string ControllerPropertyName => null; public override bool Equals(object other) { return other is FluentActionUsingDefinition && other.GetHashCode() == GetHashCode(); } public virtual ParameterBuilder DefineMethodParameter(MethodBuilder methodBuilder, FluentActionDefinition actionDefinition, FluentActionUsingDefinition usingDefinition, int parameterIndex) { var parameterBuilder = methodBuilder.DefineParameter( parameterIndex, usingDefinition.HasDefaultValue ? ParameterAttributes.HasDefault : ParameterAttributes.None, usingDefinition.MethodParameterName ?? $"parameter{parameterIndex}"); if (usingDefinition.HasDefaultValue) { parameterBuilder.SetConstant(usingDefinition.DefaultValue); } return parameterBuilder; } public override int GetHashCode() { return Tuple.Create(GetType(), Type).GetHashCode(); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithHeaders.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithHeaders { [Fact(DisplayName = "1 header (string), returns string")] public void FluentControllerBuilder_FluentActionUsingHeaderReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingHeader<string>("name") .To(name => $"Hello {name}!"), typeof(ControllerWithHeaderReturnsString), new object[] { "Charlie" }); } [Fact(DisplayName = "1 header (string), returns string async")] public void FluentControllerBuilder_FluentActionUsingHeaderReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingHeader<string>("name") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }), typeof(ControllerWithHeaderReturnsStringAsync), new object[] { "Charlie" }); } [Fact(DisplayName = "1 header (string) with used default value, returns string")] public void FluentControllerBuilder_FluentActionUsingHeaderWithUsedDefaultValueReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingHeader<string>("name", "Hanzel") .To(name => $"Hello {name}!"), typeof(ControllerWithHeaderAndDefaultValueReturnsString), new object[] { Type.Missing }); } [Fact(DisplayName = "1 header (string) with used default value, returns string async")] public void FluentControllerBuilder_FluentActionUsingHeaderWithUsedDefaultValueReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingHeader<string>("name", "Hanzel") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }), typeof(ControllerWithHeaderAndDefaultValueReturnsStringAsync), new object[] { Type.Missing }); } [Fact(DisplayName = "1 header (string) with unused default value, returns string")] public void FluentControllerBuilder_FluentActionUsingHeaderWithUnusedDefaultValueReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingHeader<string>("name", "Hanzel") .To(name => $"Hello {name}!"), typeof(ControllerWithHeaderAndDefaultValueReturnsString), new object[] { "Charlie" }); } [Fact(DisplayName = "1 header (string) with unused default value, returns string async")] public void FluentControllerBuilder_FluentActionUsingHeaderWithUnusedDefaultValueReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingHeader<string>("name", "Hanzel") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }), typeof(ControllerWithHeaderAndDefaultValueReturnsStringAsync), new object[] { "Charlie" }); } [Fact(DisplayName = "2 headers (string, identical), returns string")] public void FluentControllerBuilder_FluentActionUsingTwoIdenticalHeadersReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingHeader<string>("name") .UsingHeader<string>("name") .To((name1, name2) => $"Hello {name1}! I said hello {name2}!"), typeof(ControllerWithTwoIdenticalHeadersReturnsString), new object[] { "Charlie" }); } [Fact(DisplayName = "2 headers (string, identical), returns string async")] public void FluentControllerBuilder_FluentActionUsingTwoIdenticalHeadersReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingHeader<string>("name") .UsingHeader<string>("name") .To(async (name1, name2) => { await Task.Delay(1); return $"Hello {name1}! I said hello {name2}!"; }), typeof(ControllerWithTwoIdenticalHeadersReturnsStringAsync), new object[] { "Charlie" }); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithResponse.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithResponse { [Fact(DisplayName = "1 Response, returns string")] public void FluentControllerBuilder_FluentActionWithResponseReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingResponse() .To(response => { if (response == null) { throw new Exception("Response is null inside fluent action delegate."); } return "Hello"; }), typeof(ControllerWithResponseReturnsString), null); } [Fact(DisplayName = "1 Response, returns string async")] public void FluentControllerBuilder_FluentActionWithResponseReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .DoAsync(async () => { await Task.Delay(1); }) .UsingResponse() .To(async response => { await Task.Delay(1); if (response == null) { throw new Exception("Response is null inside fluent action delegate."); } return "Hello"; }), typeof(ControllerWithResponseReturnsStringAsync), null); } } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/FluentActionWithView.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using Microsoft.AspNetCore.Mvc; using System; namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions { public class FluentActionWithView<TP> : FluentAction<TP, ViewResult> { public FluentActionWithView(FluentActionDefinition fluentActionDefinition, string pathToView) : base(fluentActionDefinition) { Definition.ExistingOrNewHandlerDraft.Type = FluentActionHandlerType.View; Definition.ExistingOrNewHandlerDraft.ViewTarget = pathToView; Definition.ExistingOrNewHandlerDraft.ReturnType = typeof(ViewResult); Definition.ExistingOrNewHandlerDraft.Async = false; Definition.CommitHandlerDraft(); } } public class FluentActionWithPartialView<TP> : FluentAction<TP, ViewResult> { public FluentActionWithPartialView(FluentActionDefinition fluentActionDefinition, string pathToView) : base(fluentActionDefinition) { Definition.ExistingOrNewHandlerDraft.Type = FluentActionHandlerType.PartialView; Definition.ExistingOrNewHandlerDraft.ViewTarget = pathToView; Definition.ExistingOrNewHandlerDraft.ReturnType = typeof(PartialViewResult); Definition.ExistingOrNewHandlerDraft.Async = false; Definition.CommitHandlerDraft(); } } public class FluentActionWithViewComponent<TP> : FluentAction<TP, ViewResult> { public FluentActionWithViewComponent(FluentActionDefinition fluentActionDefinition, string viewComponentName) : base(fluentActionDefinition) { Definition.ExistingOrNewHandlerDraft.Type = FluentActionHandlerType.ViewComponent; Definition.ExistingOrNewHandlerDraft.ViewTarget = viewComponentName; Definition.ExistingOrNewHandlerDraft.ReturnType = typeof(ViewComponentResult); Definition.ExistingOrNewHandlerDraft.Async = false; Definition.CommitHandlerDraft(); } public FluentActionWithViewComponent(FluentActionDefinition fluentActionDefinition, Type viewComponentType) : base(fluentActionDefinition) { Definition.ExistingOrNewHandlerDraft.Type = FluentActionHandlerType.ViewComponent; Definition.ExistingOrNewHandlerDraft.ViewComponentType = viewComponentType; Definition.ExistingOrNewHandlerDraft.ReturnType = typeof(ViewComponentResult); Definition.ExistingOrNewHandlerDraft.Async = false; Definition.CommitHandlerDraft(); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithCustomAttributes.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System; using System.Reflection; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithCustomAttributes { [Fact(DisplayName = "1 custom attribute (empty), returns string")] public void FluentControllerBuilder_FluentActionWith1EmptyCustomAttributeReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .WithCustomAttribute<MyCustomAttribute>() .To(() => "hello"), typeof(ControllerWith1EmptyCustomAttributeReturnsString), null); } [Fact(DisplayName = "1 custom attribute (const), returns string")] public void FluentControllerBuilder_FluentActionWith1ConstructorCustomAttributeReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .WithCustomAttribute<MyCustomAttribute>(new Type[] { typeof(int) }, new object[] { 10 }) .To(() => "hello"), typeof(ControllerWith1ConstructorCustomAttributeReturnsString), null); } [Fact(DisplayName = "1 custom attribute (const with Type[]), returns string")] public void FluentControllerBuilder_FluentActionWith1ConstructorWithInfoCustomAttributeReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .WithCustomAttribute<MyCustomAttribute>( typeof(MyCustomAttribute).GetConstructor(new Type[] { typeof(int) }), new object[] { 10 }) .To(() => "hello"), typeof(ControllerWith1ConstructorCustomAttributeReturnsString), null); } [Fact(DisplayName = "1 custom attribute (prop with Type[]), returns string")] public void FluentControllerBuilder_FluentActionWith1PropertyCustomAttributeReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .WithCustomAttribute<MyCustomAttribute>(new Type[0], new object[0], new string[] { "Property" }, new object[] { "prop" }) .To(() => "hello"), typeof(ControllerWith1PropertyCustomAttributeReturnsString), null); } [Fact(DisplayName = "1 custom attribute (prop), returns string")] public void FluentControllerBuilder_FluentActionWith1PropertyWithInfoCustomAttributeReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .WithCustomAttribute<MyCustomAttribute>( typeof(MyCustomAttribute).GetConstructor(new Type[0]), new object[0], new PropertyInfo[] { typeof(MyCustomAttribute).GetProperty("Property") }, new object[] { "prop" }) .To(() => "hello"), typeof(ControllerWith1PropertyCustomAttributeReturnsString), null); } [Fact(DisplayName = "1 custom attribute (field), returns string")] public void FluentControllerBuilder_FluentActionWith1FieldCustomAttributeReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .WithCustomAttribute<MyCustomAttribute>( typeof(MyCustomAttribute).GetConstructor(new Type[0]), new object[0], new FieldInfo[] { typeof(MyCustomAttribute).GetField("Field") }, new object[] { "field" }) .To(() => "hello"), typeof(ControllerWith1FieldCustomAttributeReturnsString), null); } [Fact(DisplayName = "1 custom attribute (const - prop), returns string")] public void FluentControllerBuilder_FluentActionWith1ConstructorPropertyWithInfoCustomAttributeReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .WithCustomAttribute<MyCustomAttribute>( typeof(MyCustomAttribute).GetConstructor(new Type[] { typeof(int) }), new object[] { 10 }, new PropertyInfo[] { typeof(MyCustomAttribute).GetProperty("Property") }, new object[] { "prop" }) .To(() => "hello"), typeof(ControllerWith1ConstructorPropertyCustomAttributeReturnsString), null); } [Fact(DisplayName = "1 custom attribute (const - field), returns string")] public void FluentControllerBuilder_FluentActionWith1ConstructorFieldWithInfoCustomAttributeReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .WithCustomAttribute<MyCustomAttribute>( typeof(MyCustomAttribute).GetConstructor(new Type[] { typeof(int) }), new object[] { 10 }, new FieldInfo[] { typeof(MyCustomAttribute).GetField("Field") }, new object[] { "field" }) .To(() => "hello"), typeof(ControllerWith1ConstructorFieldCustomAttributeReturnsString), null); } [Fact(DisplayName = "1 custom attribute (field - prop), returns string")] public void FluentControllerBuilder_FluentActionWith1FieldPropertyWithInfoCustomAttributeReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .WithCustomAttribute<MyCustomAttribute>( typeof(MyCustomAttribute).GetConstructor(new Type[0]), new object[0], new PropertyInfo[] { typeof(MyCustomAttribute).GetProperty("Property") }, new object[] { "prop" }, new FieldInfo[] { typeof(MyCustomAttribute).GetField("Field") }, new object[] { "field" }) .To(() => "hello"), typeof(ControllerWith1FieldPropertyCustomAttributeReturnsString), null); } [Fact(DisplayName = "1 custom attribute (const - field - prop), returns string")] public void FluentControllerBuilder_FluentActionWith1ConstructorFieldPropertyWithInfoCustomAttributeReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .WithCustomAttribute<MyCustomAttribute>( typeof(MyCustomAttribute).GetConstructor(new Type[] { typeof(int) }), new object[] { 10 }, new PropertyInfo[] { typeof(MyCustomAttribute).GetProperty("Property") }, new object[] { "prop" }, new FieldInfo[] { typeof(MyCustomAttribute).GetField("Field") }, new object[] { "field" }) .To(() => "hello"), typeof(ControllerWith1ConstructorFieldPropertyCustomAttributeReturnsString), null); } [Fact(DisplayName = "2 custom attributes (empty, empty), returns string")] public void FluentControllerBuilder_FluentActionWith2EmptyCustomAttributesReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .WithCustomAttribute<MyCustomAttribute>() .WithCustomAttribute<MySecondCustomAttribute>() .To(() => "hello"), typeof(ControllerWith2EmptyCustomAttributesReturnsString), null); } [Fact(DisplayName = "1 custom attribute (empty), returns ViewResult async")] public void FluentControllerBuilder_FluentActionWith1EmptyCustomAttributeReturnsViewResultAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .WithCustomAttribute<MyCustomAttribute>() .To(async () => { await Task.Delay(1); return "hello"; }) .ToView("~/Path/To/ViewWithStringModel.cshtml"), typeof(ControllerWith1EmptyCustomAttributeReturnsViewResultAsync), null); } [Fact(DisplayName = "2 custom attributes (empty, empty), returns ViewResult async")] public void FluentControllerBuilder_FluentActionWith2EmptyCustomAttributesReturnsViewResultAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .WithCustomAttribute<MyCustomAttribute>() .WithCustomAttribute<MySecondCustomAttribute>() .To(async () => { await Task.Delay(1); return "hello"; }) .ToView("~/Path/To/ViewWithStringModel.cshtml"), typeof(ControllerWith2EmptyCustomAttributesReturnsViewResultAsync), null); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/ControllersWithParentType.cs<|end_filename|> using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { public class ControllerWithParentTypeReturnsString : BaseController { [HttpGet] [Route("/route/url")] public string HandlerAction() { return "hello"; } } } <|start_filename|>test/WebApps/MvcWithSwagger/Localization/Actions.Designer.cs<|end_filename|> //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace MvcWithSwagger.Localization { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Actions { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Actions() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MvcWithSwagger.Localization.Actions", typeof(Actions).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to AddUser-&gt;Description. /// </summary> internal static string AddUser_Description { get { return ResourceManager.GetString("AddUser_Description", resourceCulture); } } /// <summary> /// Looks up a localized string similar to AddUser-&gt;Title. /// </summary> internal static string AddUser_Title { get { return ResourceManager.GetString("AddUser_Title", resourceCulture); } } /// <summary> /// Looks up a localized string similar to GetUser-&gt;Description. /// </summary> internal static string GetUser_Description { get { return ResourceManager.GetString("GetUser_Description", resourceCulture); } } /// <summary> /// Looks up a localized string similar to GetUser-&gt;Title. /// </summary> internal static string GetUser_Title { get { return ResourceManager.GetString("GetUser_Title", resourceCulture); } } /// <summary> /// Looks up a localized string similar to ListUsers-&gt;Description. /// </summary> internal static string ListUsers_Description { get { return ResourceManager.GetString("ListUsers_Description", resourceCulture); } } /// <summary> /// Looks up a localized string similar to ListUsers-&gt;Title. /// </summary> internal static string ListUsers_Title { get { return ResourceManager.GetString("ListUsers_Title", resourceCulture); } } /// <summary> /// Looks up a localized string similar to RemoveUser-&gt;Description. /// </summary> internal static string RemoveUser_Description { get { return ResourceManager.GetString("RemoveUser_Description", resourceCulture); } } /// <summary> /// Looks up a localized string similar to RemoveUser-&gt;Title. /// </summary> internal static string RemoveUser_Title { get { return ResourceManager.GetString("RemoveUser_Title", resourceCulture); } } /// <summary> /// Looks up a localized string similar to UpdateUser-&gt;Description. /// </summary> internal static string UpdateUser_Description { get { return ResourceManager.GetString("UpdateUser_Description", resourceCulture); } } /// <summary> /// Looks up a localized string similar to UpdateUser-&gt;Title. /// </summary> internal static string UpdateUser_Title { get { return ResourceManager.GetString("UpdateUser_Title", resourceCulture); } } } } <|start_filename|>test/WebApps/MvcWithSwagger/Actions/NoteActions.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using NSwag.Annotations; using System; namespace MvcWithSwagger { public static class NoteActions { public static FluentActionCollection All => FluentActionCollection.DefineActions( actions => { actions.Configure(config => { config.GroupBy("Notes"); config.WithCustomAttribute<OpenApiTagsAttribute>( new Type[] { typeof(string[]) }, new object[] { new string[] { "Notes" } } ); }); actions .Route("/notes", HttpMethod.Get) .UsingService<INoteService>() .To(noteService => noteService.List()); actions .Route("/notes", HttpMethod.Post) .UsingService<INoteService>() .UsingBody<NoteItem>() .To((noteService, note) => noteService.Add(note)); actions .Route("/notes/{noteId}", HttpMethod.Get) .UsingService<INoteService>() .UsingRouteParameter<int>("noteId") .To((noteService, noteId) => noteService.Get(noteId)); actions .Route("/notes/{noteId}", HttpMethod.Put) .UsingService<INoteService>() .UsingRouteParameter<int>("noteId") .UsingBody<NoteItem>() .To((noteService, noteId, note) => noteService.Update(noteId, note)); actions .Route("/notes/{noteId}", HttpMethod.Delete) .UsingService<INoteService>() .UsingRouteParameter<int>("noteId") .To((noteService, noteId) => noteService.Remove(noteId)); } ); } } <|start_filename|>samples/MvcTemplate/Views/_ViewImports.cshtml<|end_filename|> @using MvcTemplate @using MvcTemplate.Models @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Config/Append/AppendReturnsStringContainer.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using Microsoft.AspNetCore.Mvc; using System; using System.Linq; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class AppendReturnsStringContainer { [Fact(DisplayName = "1 Append in collection config returns string container")] public void FluentActionCollection_DefineActions_Config_Append_ReturnsStringContainer() { var actionCollection = FluentActionCollection.DefineActions( actions => { actions.Configure(config => { config.Append(action => action .UsingResult() .To(result => new StringContainer { Value = result.ToString() }) ); }); actions .RouteGet("/hello") .UsingQueryStringParameter<string>("name") .To(name => $"Hello {name}!"); actions .RouteGet("/helloAsync") .UsingQueryStringParameter<string>("name") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }); actions .RouteGet("/helloAsyncWithDo") .Do(() => { /* Doing nothing */ }) .UsingQueryStringParameter<string>("name") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }); actions .RouteGet("/helloAsyncWithAsyncDo") .Do(async () => { await Task.Delay(1); }) .UsingQueryStringParameter<string>("name") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }); actions .RouteGet("/hi/{name}") .UsingRouteParameter<string>("name") .To(name => $"Hi {name}!") .UsingResult() .To(greeting => $"{greeting} How are you?"); actions .RouteGet("/userCount") .UsingService<IUserService>() .To(userService => userService.ListUsers().Count()); actions .RouteGet("/toView") .ToView("~/path/to/view"); } ); foreach (var action in actionCollection) { switch (action.RouteTemplate) { case "/hello": BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( action, typeof(Append_HelloController), new object[] { "Bob" }); break; case "/helloAsync": BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( action, typeof(Append_HelloAsyncController), new object[] { "Bob" }); break; case "/helloAsyncWithDo": BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( action, typeof(Append_HelloAsyncWithDoController), new object[] { "Bob" }); break; case "/helloAsyncWithAsyncDo": BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( action, typeof(Append_HelloAsyncWithAsyncDoController), new object[] { "Bob" }); break; case "/hi/{name}": BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( action, typeof(Append_HiController), new object[] { "Bob" }); break; case "/userCount": BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( action, typeof(Append_UserCountController), new object[] { new UserService() }); break; case "/toView": BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( action, typeof(Append_ToViewController), new object[0]); break; default: throw new Exception($"Could not find controller type to compare with for action {action}"); } } } } public class StringContainer { public string Value { get; set; } public override bool Equals(object obj) { return obj is StringContainer && obj != null && ((StringContainer) obj).Value == Value; } public override int GetHashCode() { return (Value ?? "").GetHashCode(); } public override string ToString() { return Value.ToString(); } } public class Append_HelloController : Controller { [HttpGet] [Route("/hello")] public StringContainer HandlerAction([FromQuery]string name) { return new StringContainer { Value = $"Hello {name}!" }; } } public class Append_HelloAsyncController : Controller { [HttpGet] [Route("/helloAsync")] public async Task<StringContainer> HandlerAction([FromQuery]string name) { await Task.Delay(1); return new StringContainer { Value = $"Hello {name}!" }; } } public class Append_HelloAsyncWithDoController : Controller { [HttpGet] [Route("/helloAsyncWithDo")] public async Task<StringContainer> HandlerAction([FromQuery]string name) { await Task.Delay(1); return new StringContainer { Value = $"Hello {name}!" }; } } public class Append_HelloAsyncWithAsyncDoController : Controller { [HttpGet] [Route("/helloAsyncWithAsyncDo")] public async Task<StringContainer> HandlerAction([FromQuery]string name) { await Task.Delay(1); return new StringContainer { Value = $"Hello {name}!" }; } } public class Append_HiController : Controller { [HttpGet] [Route("/hi/{name}")] public StringContainer HandlerAction([FromRoute]string name) { return new StringContainer { Value = $"Hi {name}! How are you?" }; } } public class Append_UserCountController : Controller { [HttpGet] [Route("/userCount")] public StringContainer HandlerAction([FromServices]IUserService userService) { var userCount = userService.ListUsers().Count; return new StringContainer { Value = userCount.ToString() }; } } public class Append_ToViewController : Controller { [HttpGet] [Route("/toView")] public StringContainer HandlerAction() { var view = View("~/path/to/view"); return new StringContainer { Value = view.ToString() }; } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsForReadMeExamples.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsForReadMeExamples { [Fact(DisplayName = "README example 1: HelloWorld")] public void FluentControllerBuilder_FluentActionForReadMeExample1() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/", HttpMethod.Get) .To(() => "Hello World!"), typeof(ControllerForReadMeExample1), null); } [Fact(DisplayName = "README example 2: Another example")] public void FluentControllerBuilder_FluentActionForReadMeExample2() { BuilderTestUtils.BuildActionAndCompareToStaticAction( new FluentAction("/users/{userId}", HttpMethod.Get) .UsingService<IUserService>() .UsingRouteParameter<int>("userId") .To((userService, userId) => userService.GetUserById(userId)) .ToView("~/Views/Users/DisplayUser.cshtml"), typeof(ControllerForReadMeExample2)); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithDo.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System; using System.Threading.Tasks; using Xunit; using static ExplicitlyImpl.AspNetCore.Mvc.FluentActions.FluentActionControllerDefinitionBuilder; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithDo { [Fact(DisplayName = "1 Do, no return, throws")] public void FluentControllerBuilder_FluentActionWithDoAndNoReturnThrows() { Assert.Throws<FluentActionValidationException>(() => BuilderTestUtils.BuildAction( new FluentAction("/route/url", HttpMethod.Get) .Do(() => Console.WriteLine("foo")))); } [Fact(DisplayName = "1 Do, returns string")] public void FluentControllerBuilder_FluentActionWithDoReturnsString() { var foo = "bar"; BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .Do(() => { foo = "baz"; }) .To(() => foo), typeof(ControllerWithDoReturnsString), null); } [Fact(DisplayName = "1 Do, returns string async")] public void FluentControllerBuilder_FluentActionWithDoReturnsStringAsync() { var foo = "bar"; BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .DoAsync(async () => { await Task.Delay(1); foo = "baz"; }) .To(() => foo), typeof(ControllerWithDoReturnsStringAsync), null); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Config/Append/AppendAsyncReturnsStringContainer.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using Microsoft.AspNetCore.Mvc; using System; using System.Linq; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class AppendAsyncReturnsStringContainer { [Fact(DisplayName = "1 Append (async) in collection config returns string container")] public void FluentActionCollection_DefineActions_Config_AppendAsync_ReturnsStringContainer() { var actionCollection = FluentActionCollection.DefineActions( actions => { actions.Configure(config => { config.Append(action => action .UsingResult() .To(async result => { await Task.Delay(1); return new StringContainer { Value = result.ToString() }; }) ); }); actions .RouteGet("/hello") .UsingQueryStringParameter<string>("name") .To(name => $"Hello {name}!"); actions .RouteGet("/helloAsync") .UsingQueryStringParameter<string>("name") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }); actions .RouteGet("/helloAsyncWithDo") .Do(() => { /* Doing nothing */ }) .UsingQueryStringParameter<string>("name") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }); actions .RouteGet("/helloAsyncWithAsyncDo") .Do(async () => { await Task.Delay(1); }) .UsingQueryStringParameter<string>("name") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }); actions .RouteGet("/hi/{name}") .UsingRouteParameter<string>("name") .To(name => $"Hi {name}!") .UsingResult() .To(greeting => $"{greeting} How are you?"); actions .RouteGet("/userCount") .UsingService<IUserService>() .To(userService => userService.ListUsers().Count()); actions .RouteGet("/toView") .ToView("~/path/to/view"); } ); foreach (var action in actionCollection) { switch (action.RouteTemplate) { case "/hello": BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( action, typeof(AppendAsync_HelloController), new object[] { "Bob" }); break; case "/helloAsync": BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( action, typeof(AppendAsync_HelloAsyncController), new object[] { "Bob" }); break; case "/helloAsyncWithDo": BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( action, typeof(AppendAsync_HelloAsyncWithDoController), new object[] { "Bob" }); break; case "/helloAsyncWithAsyncDo": BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( action, typeof(AppendAsync_HelloAsyncWithAsyncDoController), new object[] { "Bob" }); break; case "/hi/{name}": BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( action, typeof(AppendAsync_HiController), new object[] { "Bob" }); break; case "/userCount": BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( action, typeof(AppendAsync_UserCountController), new object[] { new UserService() }); break; case "/toView": BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( action, typeof(AppendAsync_ToViewController), new object[0]); break; default: throw new Exception($"Could not find controller type to compare with for action {action}"); } } } } public class AppendAsync_HelloController : Controller { [HttpGet] [Route("/hello")] public async Task<StringContainer> HandlerAction([FromQuery]string name) { await Task.Delay(1); return new StringContainer { Value = $"Hello {name}!" }; } } public class AppendAsync_HelloAsyncController : Controller { [HttpGet] [Route("/helloAsync")] public async Task<StringContainer> HandlerAction([FromQuery]string name) { await Task.Delay(1); return new StringContainer { Value = $"Hello {name}!" }; } } public class AppendAsync_HelloAsyncWithDoController : Controller { [HttpGet] [Route("/helloAsyncWithDo")] public async Task<StringContainer> HandlerAction([FromQuery]string name) { await Task.Delay(1); return new StringContainer { Value = $"Hello {name}!" }; } } public class AppendAsync_HelloAsyncWithAsyncDoController : Controller { [HttpGet] [Route("/helloAsyncWithAsyncDo")] public async Task<StringContainer> HandlerAction([FromQuery]string name) { await Task.Delay(1); return new StringContainer { Value = $"Hello {name}!" }; } } public class AppendAsync_HiController : Controller { [HttpGet] [Route("/hi/{name}")] public async Task<StringContainer> HandlerAction([FromRoute]string name) { await Task.Delay(1); return new StringContainer { Value = $"Hi {name}! How are you?" }; } } public class AppendAsync_UserCountController : Controller { [HttpGet] [Route("/userCount")] public async Task<StringContainer> HandlerAction([FromServices]IUserService userService) { await Task.Delay(1); var userCount = userService.ListUsers().Count; return new StringContainer { Value = userCount.ToString() }; } } public class AppendAsync_ToViewController : Controller { [HttpGet] [Route("/toView")] public async Task<StringContainer> HandlerAction() { await Task.Delay(1); var view = View("~/path/to/view"); return new StringContainer { Value = view.ToString() }; } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/ControllersWithViewResultAsync.cs<|end_filename|> using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { public class ControllerWithNoUsingsXToReturnsViewAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<ViewResult> HandlerAction() { await Task.Delay(1); return View("~/Path/To/ViewWithStringModel.cshtml", "Hello World!"); } } public class ControllerWithNoUsingsXDoReturnsViewAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<ViewResult> HandlerAction() { await Task.Delay(1); return View("~/Path/To/ViewWithoutModel.cshtml"); } } public class ControllerWithNoUsings1Do1ToReturnsViewAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<ViewResult> HandlerAction() { await Task.Delay(1); return View("~/Path/To/ViewWithStringModel.cshtml", "baz"); } } public class ControllerWith1BodyReturnsViewAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<ViewResult> HandlerAction([FromBody]string name) { await Task.Delay(1); return View("~/Path/To/ViewWithStringModel.cshtml", $"Hello {name}!"); } } public class ControllerWith1Body1RouteParamReturnsViewAsync : Controller { [HttpGet] [Route("/route/{lastName}")] public async Task<ViewResult> HandlerAction([FromBody]string firstName, [FromRoute]string lastName) { await Task.Delay(1); return View("~/Path/To/ViewWithStringModel.cshtml", $"Hello {firstName} {lastName}!"); } } public class ControllerWith1Body1RouteParam2ToReturnsViewAsync : Controller { [HttpGet] [Route("/route/{lastName}")] public async Task<ViewResult> HandlerAction([FromBody]string firstName, [FromRoute]string lastName) { await Task.Delay(1); return View("~/Path/To/ViewWithStringModel.cshtml", $"Hello {firstName} {lastName}!"); } } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/Builder/AsyncStateMachineTypeBuilder.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Threading.Tasks; using System.Collections.Generic; namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core.Builder { public class AsyncStateMachineTypeBuilder { public TypeBuilder ParentType { get; set; } public TypeBuilder Type { get; set; } public FluentActionDefinition FluentActionDefinition { get; set; } public ConstructorBuilder Constructor { get; set; } public FieldBuilder ParentField { get; set; } public FieldBuilder AsyncTaskMethodBuilderField { get; set; } public FieldBuilder TaskDelayAwaiterField { get; set; } public FieldBuilder StateField { get; set; } public FieldBuilder[] MethodParameterFields { get; set; } public StateMachineState[] States { get; set; } public Type ReturnType { get; set; } public ILogger Logger { get; set; } public string LoggerKey { get; set; } public static AsyncStateMachineTypeBuilder Create( TypeBuilder parentTypeBuilder, FluentActionDefinition fluentActionDefinition, ILogger logger = null) { var builder = new AsyncStateMachineTypeBuilder { ParentType = parentTypeBuilder, ReturnType = fluentActionDefinition.Handlers.Last().ReturnType, Logger = logger }; if (logger != null) { builder.LoggerKey = FluentActionLoggers.Add(logger); } builder.DefineTypeAndDefaultConstructor(parentTypeBuilder); builder.DefineFields(fluentActionDefinition); builder.DefineMoveNextMethod(fluentActionDefinition); builder.DefineSetStateMachineMethod(); return builder; } private void DefineTypeAndDefaultConstructor(TypeBuilder parentTypeBuilder) { Type = parentTypeBuilder.DefineNestedType( $"{parentTypeBuilder.Name}_AsyncStateMachine", TypeAttributes.Class | TypeAttributes.NestedPrivate | TypeAttributes.Sealed | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit); Type.AddInterfaceImplementation(typeof(IAsyncStateMachine)); Constructor = Type.DefineDefaultConstructor(MethodAttributes.Public); } private void DefineFields(FluentActionDefinition fluentActionDefinition) { var asyncTaskMethodBuilderType = typeof(AsyncTaskMethodBuilder<>).MakeGenericType(ReturnType); ParentField = Type.DefineField("Parent", ParentType, FieldAttributes.Public); AsyncTaskMethodBuilderField = Type.DefineField("AsyncTaskMethodBuilder", asyncTaskMethodBuilderType, FieldAttributes.Public); StateField = Type.DefineField("State", typeof(int), FieldAttributes.Public); DefineMethodParameterFields(fluentActionDefinition); DefineStates(fluentActionDefinition); } private void DefineMethodParameterFields(FluentActionDefinition fluentActionDefinition) { var usingsForMethodParameters = fluentActionDefinition.Handlers .SelectMany(handler => handler.Usings) .Where(@using => @using.IsMethodParameter) .Distinct() .ToArray(); var methodParameterIndices = usingsForMethodParameters .Select((@using, index) => new { Using = @using, Index = index }) .ToDictionary( indexedUsing => indexedUsing.Using.GetHashCode(), indexedUsing => indexedUsing.Index + 1 // 1-based index ); MethodParameterFields = new FieldBuilder[usingsForMethodParameters.Length]; foreach (var usingDefinition in usingsForMethodParameters) { var methodParameterIndex = methodParameterIndices[usingDefinition.GetHashCode()]; MethodParameterFields[methodParameterIndex - 1] = Type.DefineField( $"parameter{methodParameterIndex}", usingDefinition.Type, FieldAttributes.Public); } } private void DefineStates(FluentActionDefinition fluentActionDefinition) { var handlersPerState = fluentActionDefinition.Handlers .Divide(handler => handler.Async) .Select(handlers => handlers.ToArray()) .ToArray(); States = new StateMachineState[handlersPerState.Length]; for (var stateIndex = 0; stateIndex < handlersPerState.Length; stateIndex++) { var handlersInState = handlersPerState[stateIndex]; var state = new StateMachineState { Handlers = new StateMachineStateHandler[handlersInState.Length] }; for (var handlerIndex = 0; handlerIndex < handlersInState.Length; handlerIndex++) { var handlerDefinition = handlersInState[handlerIndex]; state.Handlers[handlerIndex] = new StateMachineStateHandler { Definition = handlerDefinition }; if (handlerDefinition.Type == FluentActionHandlerType.Func) { state.Handlers[handlerIndex].DelegateField = Type.DefineField( $"State{stateIndex}Handler{handlerIndex}Delegate", BuilderHelper.GetDelegateType(handlerDefinition), FieldAttributes.Public); state.Handlers[handlerIndex].ResultField = Type.DefineField( $"State{stateIndex}Handler{handlerIndex}Result", handlerDefinition.ReturnType, FieldAttributes.Public); } else if (handlerDefinition.Type == FluentActionHandlerType.Action) { state.Handlers[handlerIndex].DelegateField = Type.DefineField( $"State{stateIndex}Handler{handlerIndex}Delegate", BuilderHelper.GetDelegateType(handlerDefinition), FieldAttributes.Public); } else if ( handlerDefinition.Type == FluentActionHandlerType.View || handlerDefinition.Type == FluentActionHandlerType.PartialView || handlerDefinition.Type == FluentActionHandlerType.ViewComponent) { state.Handlers[handlerIndex].ResultField = Type.DefineField( $"State{stateIndex}Handler{handlerIndex}Result", handlerDefinition.ReturnType, FieldAttributes.Public); } } var lastHandlerInState = handlersInState.Last(); if (lastHandlerInState.Type == FluentActionHandlerType.Func) { state.ResultType = lastHandlerInState.ReturnType; state.ResultField = Type.DefineField( $"State{stateIndex}ReturnType", state.ResultType, FieldAttributes.Public); state.TaskAwaiterType = typeof(TaskAwaiter<>) .MakeGenericType(lastHandlerInState.ReturnType); state.TaskAwaiterField = Type.DefineField( $"State{stateIndex}Awaiter", state.TaskAwaiterType, FieldAttributes.Public); state.WaitingField = Type.DefineField( $"State{stateIndex}WaitingFlag", typeof(bool), FieldAttributes.Public); } else if (lastHandlerInState.Type == FluentActionHandlerType.Action) { state.ResultType = lastHandlerInState.ReturnType; // state.ResultField is not used since an Action returns void state.TaskAwaiterType = typeof(TaskAwaiter); state.TaskAwaiterField = Type.DefineField( $"State{stateIndex}Awaiter", state.TaskAwaiterType, FieldAttributes.Public); state.WaitingField = Type.DefineField( $"State{stateIndex}WaitingFlag", typeof(bool), FieldAttributes.Public); } else if (lastHandlerInState.Type == FluentActionHandlerType.View || lastHandlerInState.Type == FluentActionHandlerType.PartialView || lastHandlerInState.Type == FluentActionHandlerType.ViewComponent) { state.ResultType = lastHandlerInState.ReturnType; state.ResultField = Type.DefineField( $"State{stateIndex}ReturnType", state.ResultType, FieldAttributes.Public); } States[stateIndex] = state; } } private void DefineMoveNextMethod(FluentActionDefinition fluentActionDefinition) { var usingsForMethodParameters = fluentActionDefinition.Handlers .SelectMany(handler => handler.Usings) .Where(@using => @using.IsMethodParameter) .Distinct() .ToArray(); var methodParameterIndices = usingsForMethodParameters .Select((@using, index) => new { Using = @using, Index = index }) .ToDictionary( indexedUsing => indexedUsing.Using.GetHashCode(), indexedUsing => indexedUsing.Index + 1 // 1-based index ); var asyncTaskMethodBuilderType = typeof(AsyncTaskMethodBuilder<>).MakeGenericType(ReturnType); var handlersForEachState = fluentActionDefinition.Handlers .Divide(handler => handler.Async) .Select(handlers => handlers.ToArray()) .ToArray(); var moveNextBuilder = Type.DefineMethod("MoveNext", MethodAttributes.Public | MethodAttributes.Virtual); Type.DefineMethodOverride(moveNextBuilder, typeof(IAsyncStateMachine).GetMethod("MoveNext")); moveNextBuilder.SetImplementationFlags(MethodImplAttributes.Managed); var ilGenerator = moveNextBuilder.GetILGenerator(); EmitDebugLog(ilGenerator, "Starting up..."); for (var i = 0; i < handlersForEachState.Length; i++) { States[i].StartLabel = ilGenerator.DefineLabel(); States[i].WaitLabel = ilGenerator.DefineLabel(); States[i].FinishLabel = ilGenerator.DefineLabel(); } var statesStartLabels = States.Select(state => state.StartLabel).ToArray(); var leaveLabel = ilGenerator.DefineLabel(); var localVariableForThis = ilGenerator.DeclareLocal(Type); var exceptionLocalVariable = ilGenerator.DeclareLocal(typeof(Exception)); var exceptionBlock = ilGenerator.BeginExceptionBlock(); EmitDebugLog(ilGenerator, "Checking State < 0"); // If State < 0 it means we've got an exception and should leave ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldfld, StateField); ilGenerator.Emit(OpCodes.Ldc_I4_0); ilGenerator.Emit(OpCodes.Blt, leaveLabel); EmitDebugLog(ilGenerator, "Checking State >= handlersForEachState.Length"); // If State >= handlersForEachState.Length it means we've got a result and should leave ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldfld, StateField); ilGenerator.Emit(OpCodes.Ldc_I4, handlersForEachState.Length); ilGenerator.Emit(OpCodes.Bge, leaveLabel); EmitDebugLog(ilGenerator, "Switching on State"); // Jump to state (as long as 0 <= State && State < asyncHandlers.Length) ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldfld, StateField); ilGenerator.Emit(OpCodes.Switch, statesStartLabels); // ====== Leave-block ====== (With label so you can jump to it) ilGenerator.MarkLabel(leaveLabel); ilGenerator.Emit(OpCodes.Leave, exceptionBlock); // Define each state-block var stateIndex = 0; var lastStateIndex = States.Length - 1; foreach (var state in States) { // ====== State-block ====== (Run all handlers in state and, potentially, wait for result of last async handler) ilGenerator.MarkLabel(state.StartLabel); EmitDebugLog(ilGenerator, $"State{stateIndex}::Start"); var taskAwaiterType = state.ResultType != null ? typeof(TaskAwaiter<>).MakeGenericType(state.ResultType) : typeof(TaskAwaiter); var taskAwaiterIsCompletedGetMethod = taskAwaiterType.GetProperty("IsCompleted").GetGetMethod(); var taskAwaiterGetResultMethod = taskAwaiterType.GetMethod("GetResult"); EmitDebugLog(ilGenerator, $"State{stateIndex}::Checking wait-flag"); if (state.Async) { // If [Waiting]: jump to wait-block ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldfld, state.WaitingField); ilGenerator.Emit(OpCodes.Brtrue, state.WaitLabel); } EmitDebugLog(ilGenerator, $"State{stateIndex}::Not waiting, running handlers"); // Else: Run all handlers in state for (var handlerInStateIndex = 0; handlerInStateIndex < state.Handlers.Length; handlerInStateIndex++) { var handlerInState = state.Handlers[handlerInStateIndex]; var handler = handlerInState.Definition; EmitDebugLog(ilGenerator, $"State{stateIndex}::Handler::Start"); if (handler.Type == FluentActionHandlerType.Func) { EmitDebugLog(ilGenerator, $"State{stateIndex}::Handler::Beginning Func.Invoke"); var resultType = BuilderHelper.GetReturnTypeOrTaskType(handler); var localVariableForResult = ilGenerator.DeclareLocal(resultType); var funcType = BuilderHelper.GetFuncType(handler); EmitDebugLog(ilGenerator, $"State{stateIndex}::Handler::Pushing Delegate"); // Push Delegate ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldfld, handlerInState.DelegateField); EmitDebugLog(ilGenerator, $"State{stateIndex}::Handler::Pushing arguments for Delegate"); // Push arguments for Delegate foreach (var usingDefinition in handler.Usings) { EmitUsingDefinitionValue(ilGenerator, fluentActionDefinition, usingDefinition, methodParameterIndices, state, stateIndex, handlerInStateIndex); } EmitDebugLog(ilGenerator, $"State{stateIndex}::Handler::Invoking Delegate"); // Push Func.Invoke ilGenerator.Emit(OpCodes.Callvirt, funcType.GetMethod("Invoke")); EmitDebugLog(ilGenerator, $"State{stateIndex}::Handler::Result in local variable"); // Push result in local variable ilGenerator.Emit(OpCodes.Stloc, localVariableForResult); if (handler.Async) { EmitDebugLog(ilGenerator, $"State{stateIndex}::Handler::State.Awaiter = result.GetAwaiter();"); // State.Awaiter = result.GetAwaiter(); ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldloc, localVariableForResult); ilGenerator.Emit(OpCodes.Call, resultType.GetMethod("GetAwaiter")); ilGenerator.Emit(OpCodes.Stfld, state.TaskAwaiterField); EmitDebugLog(ilGenerator, $"State{stateIndex}::Handler::State.Waiting = true;"); // State.Waiting = true; ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldc_I4_1); ilGenerator.Emit(OpCodes.Stfld, state.WaitingField); EmitDebugLog(ilGenerator, $"State{stateIndex}::Handler::If [result.IsCompleted]: Goto finish;"); // If [result.IsCompleted]: Goto finish ilGenerator.Emit(OpCodes.Ldloc, localVariableForResult); ilGenerator.Emit(OpCodes.Call, resultType.GetProperty("IsCompleted").GetGetMethod()); ilGenerator.Emit(OpCodes.Brtrue, state.FinishLabel); // Else: AwaitUnsafeOnCompleted(ref Awaiter, ref self) EmitDebugLog(ilGenerator, $"State{stateIndex}::Handler::Else: AwaitUnsafeOnCompleted(ref Awaiter, ref self)"); // Store executing instance ("this") in a local variable ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Stloc, localVariableForThis); ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldflda, AsyncTaskMethodBuilderField); ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldflda, state.TaskAwaiterField); ilGenerator.Emit(OpCodes.Ldloca, localVariableForThis); ilGenerator.Emit(OpCodes.Call, asyncTaskMethodBuilderType .GetMethod("AwaitUnsafeOnCompleted") .MakeGenericMethod(state.TaskAwaiterType, Type)); EmitDebugLog(ilGenerator, $"State{stateIndex}::Handler::Called AwaitUnsafeOnCompleted."); } else if (handlerInStateIndex == state.Handlers.Length - 1) { ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldloc, localVariableForResult); ilGenerator.Emit(OpCodes.Stfld, state.ResultField); ilGenerator.Emit(OpCodes.Br, state.FinishLabel); } else { ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldloc, localVariableForResult); ilGenerator.Emit(OpCodes.Stfld, handlerInState.ResultField); } } else if (handler.Type == FluentActionHandlerType.Action) { EmitDebugLog(ilGenerator, $"State{stateIndex}::Handler::Beginning Action.Invoke"); var resultType = typeof(Task); var localVariableForResult = ilGenerator.DeclareLocal(resultType); var funcType = BuilderHelper.GetDelegateType(handler); EmitDebugLog(ilGenerator, $"State{stateIndex}::Handler::Pushing Delegate"); // Push Delegate ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldfld, handlerInState.DelegateField); EmitDebugLog(ilGenerator, $"State{stateIndex}::Handler::Pushing arguments for Delegate"); // Push arguments for Delegate foreach (var usingDefinition in handler.Usings) { EmitUsingDefinitionValue(ilGenerator, fluentActionDefinition, usingDefinition, methodParameterIndices, state, stateIndex, handlerInStateIndex); } EmitDebugLog(ilGenerator, $"State{stateIndex}::Handler::Invoking Delegate"); // Push Func.Invoke ilGenerator.Emit(OpCodes.Callvirt, funcType.GetMethod("Invoke")); if (handler.Async) { EmitDebugLog(ilGenerator, $"State{stateIndex}::Handler::Result in local variable"); // Push result in local variable ilGenerator.Emit(OpCodes.Stloc, localVariableForResult); EmitDebugLog(ilGenerator, $"State{stateIndex}::Handler::State.Awaiter = result.GetAwaiter();"); // State.Awaiter = result.GetAwaiter(); ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldloc, localVariableForResult); ilGenerator.Emit(OpCodes.Call, resultType.GetMethod("GetAwaiter")); ilGenerator.Emit(OpCodes.Stfld, state.TaskAwaiterField); EmitDebugLog(ilGenerator, $"State{stateIndex}::Handler::State.Waiting = true;"); // State.Waiting = true; ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldc_I4_1); ilGenerator.Emit(OpCodes.Stfld, state.WaitingField); EmitDebugLog(ilGenerator, $"State{stateIndex}::Handler::If [result.IsCompleted]: Goto finish;"); // If [result.IsCompleted]: Goto finish ilGenerator.Emit(OpCodes.Ldloc, localVariableForResult); ilGenerator.Emit(OpCodes.Call, resultType.GetProperty("IsCompleted").GetGetMethod()); ilGenerator.Emit(OpCodes.Brtrue, state.FinishLabel); // Else: AwaitUnsafeOnCompleted(ref Awaiter, ref self) EmitDebugLog(ilGenerator, $"State{stateIndex}::Handler::Else: AwaitUnsafeOnCompleted(ref Awaiter, ref self)"); // Store executing instance ("this") in a local variable ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Stloc, localVariableForThis); ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldflda, AsyncTaskMethodBuilderField); ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldflda, state.TaskAwaiterField); ilGenerator.Emit(OpCodes.Ldloca, localVariableForThis); ilGenerator.Emit(OpCodes.Call, asyncTaskMethodBuilderType .GetMethod("AwaitUnsafeOnCompleted") .MakeGenericMethod(state.TaskAwaiterType, Type)); EmitDebugLog(ilGenerator, $"State{stateIndex}::Handler::Called AwaitUnsafeOnCompleted."); } else if (handlerInStateIndex == state.Handlers.Length - 1) { ilGenerator.Emit(OpCodes.Br, state.FinishLabel); } } else if (handler.Type == FluentActionHandlerType.View || handler.Type == FluentActionHandlerType.PartialView || handler.Type == FluentActionHandlerType.ViewComponent) { EmitDebugLog(ilGenerator, $"State{stateIndex}::Handler::Beginning View call"); if (handler.ViewTarget == null) { throw new Exception("Must specify a view target."); } // Call one of the following controller methods: // Controller.View(string pathName, object model) // Controller.PartialView(string pathName, object model) // Controller.ViewComponent(string componentName, object arguments) ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldfld, ParentField); ilGenerator.Emit(OpCodes.Ldstr, handler.ViewTarget); Type[] viewMethodParameterTypes = null; if (handler.Usings.Any()) { EmitUsingDefinitionValue(ilGenerator, fluentActionDefinition, handler.Usings.Last(), methodParameterIndices, state, stateIndex, handlerInStateIndex); viewMethodParameterTypes = new[] { typeof(string), typeof(object) }; } else if (handlerInStateIndex > 0 && state.Handlers[handlerInStateIndex - 1].ResultField != null) { ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldfld, state.Handlers[handlerInStateIndex - 1].ResultField); viewMethodParameterTypes = new[] { typeof(string), typeof(object) }; } else if (handlerInStateIndex == 0 && stateIndex > 0 && States[stateIndex - 1].ResultField != null) { ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldfld, States[stateIndex - 1].ResultField); viewMethodParameterTypes = new[] { typeof(string), typeof(object) }; } else { viewMethodParameterTypes = new[] { typeof(string) }; } MethodInfo viewMethod = null; if (handler.Type == FluentActionHandlerType.View) { viewMethod = typeof(Controller).GetMethod("View", viewMethodParameterTypes); } else if (handler.Type == FluentActionHandlerType.PartialView) { viewMethod = typeof(Controller).GetMethod("PartialView", viewMethodParameterTypes); } else if (handler.Type == FluentActionHandlerType.ViewComponent) { viewMethod = typeof(Controller).GetMethod("ViewComponent", viewMethodParameterTypes); } ilGenerator.Emit(OpCodes.Callvirt, viewMethod); if (handlerInStateIndex == state.Handlers.Length - 1) { ilGenerator.Emit(OpCodes.Stfld, state.ResultField); ilGenerator.Emit(OpCodes.Br, state.FinishLabel); } else { ilGenerator.Emit(OpCodes.Stfld, handlerInState.ResultField); } } } EmitDebugLog(ilGenerator, $"State{stateIndex}::Leaving exception-block."); ilGenerator.Emit(OpCodes.Leave, exceptionBlock); if (state.Async) { // ====== Wait-block ====== (Check Awaiter if it is done and then save result) ilGenerator.MarkLabel(state.WaitLabel); EmitDebugLog(ilGenerator, $"State{stateIndex}::Wait-block"); // If [!State.Awaiter.IsComplete]: leave ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldflda, state.TaskAwaiterField); ilGenerator.Emit(OpCodes.Call, taskAwaiterIsCompletedGetMethod); ilGenerator.Emit(OpCodes.Brfalse, leaveLabel); } // ====== Finish-block ====== (Save result, update state and, potentially, set final result) ilGenerator.MarkLabel(state.FinishLabel); EmitDebugLog(ilGenerator, $"State{stateIndex}::Finish-block"); if (state.Async && state.ResultType != null) { // State.Result = State.Awaiter.GetResult() ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldflda, state.TaskAwaiterField); ilGenerator.Emit(OpCodes.Call, taskAwaiterGetResultMethod); ilGenerator.Emit(OpCodes.Stfld, state.ResultField); } // State + 1 ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldc_I4, stateIndex + 1); ilGenerator.Emit(OpCodes.Stfld, StateField); if (stateIndex == lastStateIndex) { // MethodSetResult(StateResult) ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldflda, AsyncTaskMethodBuilderField); ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldfld, state.ResultField); ilGenerator.Emit(OpCodes.Call, asyncTaskMethodBuilderType.GetMethod("SetResult")); } else { ilGenerator.Emit(OpCodes.Br, statesStartLabels[stateIndex + 1]); } ilGenerator.Emit(OpCodes.Leave, exceptionBlock); stateIndex++; } ilGenerator.BeginCatchBlock(typeof(Exception)); EmitDebugLog(ilGenerator, $"Catch-block."); // Store exception locally ilGenerator.Emit(OpCodes.Stloc, exceptionLocalVariable); // State = -1 ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldc_I4_M1); ilGenerator.Emit(OpCodes.Stfld, StateField); // StateMachine.SetException(exception) ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldflda, AsyncTaskMethodBuilderField); ilGenerator.Emit(OpCodes.Ldloc, exceptionLocalVariable); ilGenerator.Emit(OpCodes.Call, asyncTaskMethodBuilderType.GetMethod("SetException")); EmitDebugLog(ilGenerator, $"Got exception."); ilGenerator.Emit(OpCodes.Leave, exceptionBlock); EmitDebugLog(ilGenerator, $"Ending exception block..."); ilGenerator.EndExceptionBlock(); EmitDebugLog(ilGenerator, $"Ended exception block."); EmitDebugLog(ilGenerator, $"Returning..."); ilGenerator.Emit(OpCodes.Ret); } private void EmitUsingDefinitionValue(ILGenerator ilGenerator, FluentActionDefinition fluentActionDefinition, FluentActionUsingDefinition usingDefinition, Dictionary<int, int> methodParameterIndices, StateMachineState state, int stateIndex, int handlerInStateIndex) { if (usingDefinition.IsMethodParameter) { var usingDefinitionHash = usingDefinition.GetHashCode(); var methodParameterIndex = methodParameterIndices[usingDefinitionHash]; ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldfld, MethodParameterFields[methodParameterIndex - 1]); } else if (usingDefinition.IsControllerProperty) { ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldfld, ParentField); ilGenerator.Emit(OpCodes.Callvirt, typeof(Controller).GetProperty(usingDefinition.ControllerPropertyName).GetGetMethod()); } else if (usingDefinition is FluentActionUsingPropertyDefinition) { var propertyName = ((FluentActionUsingPropertyDefinition)usingDefinition).PropertyName; var parentType = fluentActionDefinition.ParentType ?? typeof(Controller); var property = parentType.GetProperty(propertyName); if (property == null) { throw new Exception($"Could not find property {propertyName} on type {parentType.FullName}."); } var propertyGetMethod = property.GetGetMethod(); if (propertyGetMethod == null) { throw new Exception($"Missing public get method on property {propertyName} on type {parentType.FullName}."); } ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldfld, ParentField); ilGenerator.Emit(OpCodes.Callvirt, propertyGetMethod); } else if (usingDefinition is FluentActionUsingParentDefinition) { ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldfld, ParentField); } else if (usingDefinition is FluentActionUsingResultDefinition) { FieldBuilder resultFieldToLoad; if (handlerInStateIndex > 0) { resultFieldToLoad = state.Handlers[handlerInStateIndex - 1].ResultField; } else { resultFieldToLoad = States[stateIndex - 1].ResultField; } ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldfld, resultFieldToLoad); if (resultFieldToLoad.FieldType.IsValueType) { ilGenerator.Emit(OpCodes.Box, resultFieldToLoad.FieldType); } } else { throw new Exception($"Got unknown using definition: {usingDefinition.GetType()}"); } } private void DefineSetStateMachineMethod() { var setStateMachineMethodBuilder = Type.DefineMethod("SetStateMachine", MethodAttributes.Public | MethodAttributes.Virtual); setStateMachineMethodBuilder.SetParameters(new[] { typeof(IAsyncStateMachine) }); setStateMachineMethodBuilder.GetILGenerator().Emit(OpCodes.Ret); Type.DefineMethodOverride(setStateMachineMethodBuilder, typeof(IAsyncStateMachine).GetMethod("SetStateMachine")); } private void EmitDebugLog(ILGenerator ilGenerator, string message) { if (LoggerKey != null) { FluentActionLoggers.PushDebugLogOntoStack(ilGenerator, LoggerKey, $"[MoveNext] {message}"); } } } public class StateMachineState { public bool Async => Handlers?.LastOrDefault()?.Definition.Async ?? false; public Type ResultType { get; set; } public Label StartLabel { get; set; } public Label WaitLabel { get; set; } public Label FinishLabel { get; set; } public FieldBuilder ResultField { get; set; } public Type TaskAwaiterType { get; set; } public FieldBuilder TaskAwaiterField { get; set; } public FieldBuilder WaitingField { get; set; } public StateMachineStateHandler[] Handlers { get; set; } } public class StateMachineStateHandler { public FluentActionHandlerDefinition Definition { get; set; } public FieldBuilder DelegateField { get; set; } public FieldBuilder ResultField { get; set; } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithAntiForgeryTokens.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithAntiForgeryTokens { [Fact(DisplayName = "1 anti forgery token, returns string")] public void FluentControllerBuilder_FluentActionWithAntiForgeryTokenReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticAction( new FluentAction("/route/url", HttpMethod.Post) .ValidateAntiForgeryToken() .To(() => $"Hello World!"), typeof(ControllerWithAntiForgeryTokenReturnsString)); } [Fact(DisplayName = "1 anti forgery token, returns string async")] public void FluentControllerBuilder_FluentActionWithAntiForgeryTokenReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticAction( new FluentAction("/route/url", HttpMethod.Post) .ValidateAntiForgeryToken() .To(async () => { await Task.Delay(1); return $"Hello World!"; }), typeof(ControllerWithAntiForgeryTokenReturnsStringAsync)); } } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/FluentActionCollection.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Resources; namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions { public class FluentActionCollection : IEnumerable<FluentActionBase> { public List<FluentActionBase> FluentActions { get; internal set; } public FluentActionCollectionConfig Config { get; internal set; } internal FluentActionCollection(FluentActionCollectionConfig config) { FluentActions = new List<FluentActionBase>(); Config = config ?? new FluentActionCollectionConfig(); } /// <summary> /// Defines settings that will be applied to all subsequently defined fluent actions. /// Calling this method a second time will overwrite the current config but will not overwrite previously /// defined fluent actions. /// </summary> /// <param name="configureFluentActions">Action that will define the config of future fluent actions</param> public void Configure(Action<FluentActionCollectionConfigurator> configureFluentActions) { var configurator = new FluentActionCollectionConfigurator(new FluentActionCollectionConfig()); configureFluentActions(configurator); Config = configurator.Config; } /// <summary> /// Creates and adds a fluent action to this collection. /// </summary> /// <param name="id">Optional unique Id (between all fluent actions) for better debuggability and/or meta /// programming (such as generating docs or APIs).</param> public FluentAction Route(string routeTemplate, HttpMethod httpMethod, string id = null) { var fluentAction = new FluentAction(routeTemplate, httpMethod, id); PreConfigureAction(fluentAction); FluentActions.Add(fluentAction); return fluentAction; } /// <summary> /// Creates and adds a fluent action with a DELETE route to this collection. /// </summary> /// <param name="id">Optional unique Id (between all fluent actions) for better debuggability and/or meta /// programming (such as generating docs or APIs).</param> public FluentAction RouteDelete(string routeTemplate, string id = null) { return Route(routeTemplate, HttpMethod.Delete, id); } /// <summary> /// Creates and adds a fluent action with a GET route to this collection. /// </summary> /// <param name="id">Optional unique Id (between all fluent actions) for better debuggability and/or meta /// programming (such as generating docs or APIs).</param> public FluentAction RouteGet(string routeTemplate, string id = null) { return Route(routeTemplate, HttpMethod.Get, id); } /// <summary> /// Creates and adds a fluent action with a HEAD route to this collection. /// </summary> /// <param name="id">Optional unique Id (between all fluent actions) for better debuggability and/or meta /// programming (such as generating docs or APIs).</param> public FluentAction RouteHead(string routeTemplate, string id = null) { return Route(routeTemplate, HttpMethod.Head, id); } /// <summary> /// Creates and adds a fluent action with a OPTIONS route to this collection. /// </summary> /// <param name="id">Optional unique Id (between all fluent actions) for better debuggability and/or meta /// programming (such as generating docs or APIs).</param> public FluentAction RouteOptions(string routeTemplate, string id = null) { return Route(routeTemplate, HttpMethod.Options, id); } /// <summary> /// Creates and adds a fluent action with a PATCH route to this collection. /// </summary> /// <param name="id">Optional unique Id (between all fluent actions) for better debuggability and/or meta /// programming (such as generating docs or APIs).</param> public FluentAction RoutePatch(string routeTemplate, string id = null) { return Route(routeTemplate, HttpMethod.Patch, id); } /// <summary> /// Creates and adds a fluent action with a POST route to this collection. /// </summary> /// <param name="id">Optional unique Id (between all fluent actions) for better debuggability and/or meta /// programming (such as generating docs or APIs).</param> public FluentAction RoutePost(string routeTemplate, string id = null) { return Route(routeTemplate, HttpMethod.Post, id); } /// <summary> /// Creates and adds a fluent action with a PUT route to this collection. /// </summary> /// <param name="id">Optional unique Id (between all fluent actions) for better debuggability and/or meta /// programming (such as generating docs or APIs).</param> public FluentAction RoutePut(string routeTemplate, string id = null) { return Route(routeTemplate, HttpMethod.Put, id); } public void Add(FluentActionBase fluentAction) { PreConfigureAction(fluentAction); FluentActions.Add(fluentAction); } public void Add(FluentActionCollection fluentActions) { foreach (var fluentAction in fluentActions) { PreConfigureAction(fluentAction); FluentActions.Add(fluentAction); } } public IEnumerator<FluentActionBase> GetEnumerator() { return FluentActions.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private void PreConfigureAction(FluentActionBase fluentAction) { if (Config.GroupName != null && fluentAction.Definition.GroupName == null) { fluentAction.Definition.GroupName = Config.GroupName; } if (Config.IgnoreApi.HasValue && !fluentAction.Definition.IgnoreApi.HasValue) { fluentAction.Definition.IgnoreApi = Config.IgnoreApi; } if (Config.ParentType != null && fluentAction.Definition.ParentType == null) { fluentAction.Definition.ParentType = Config.ParentType; } if (Config.GetTitleFunc != null && fluentAction.Definition.Title == null) { fluentAction.Definition.Title = Config.GetTitleFunc(fluentAction.Definition); } if (Config.GetDescriptionFunc != null && fluentAction.Definition.Description == null) { fluentAction.Definition.Description = Config.GetDescriptionFunc(fluentAction.Definition); } foreach (var customAttribute in Config.CustomAttributes) { fluentAction.Definition.CustomAttributes.Add(customAttribute); } foreach (var customAttributeOnClass in Config.CustomAttributesOnClass) { fluentAction.Definition.CustomAttributesOnClass.Add(customAttributeOnClass); } } internal void PostConfigureActions() { FluentActions = FluentActions .Select(PostConfigureAction) .ToList(); } private FluentActionBase PostConfigureAction(FluentActionBase fluentAction) { if (fluentAction.Definition.IsMapRoute) { return fluentAction; } return Config.Appenders.Aggregate( fluentAction, (result, appender) => appender(new FluentAction(result.Definition)) ); } public static FluentActionCollection DefineActions(Action<FluentActionCollection> addFluentActions) { var actionCollection = new FluentActionCollection(new FluentActionCollectionConfig()); addFluentActions(actionCollection); actionCollection.PostConfigureActions(); return actionCollection; } } public class FluentActionCollectionConfigurator { internal FluentActionCollectionConfig Config { get; set; } public FluentActionCollectionConfigurator(FluentActionCollectionConfig config) { Config = config; } public void Append(Func<FluentAction<object, object>, FluentActionBase> appender) { Config.Appenders.Add(appender); } public void GroupBy(string groupName) { Config.GroupName = groupName; } public void IgnoreApi(bool ignore = true) { Config.IgnoreApi = ignore; } public void InheritingFrom(Type parentType) { if (parentType != typeof(Controller) && !parentType.GetTypeInfo().IsSubclassOf(typeof(Controller))) { throw new Exception($"Cannot make fluent action controller inherit from a class that is not derived from the Controller class (${parentType.FullName})."); } Config.ParentType = parentType; } public void InheritingFrom<T>() where T : Controller { Config.ParentType = typeof(T); } public void SetTitle(Func<FluentActionDefinition, string> getTitleFunc) { Config.GetTitleFunc = getTitleFunc; } public void SetTitleFromResource( Type resourceType, Func<FluentActionDefinition, string> getResourceNameFunc, bool ignoreMissingValues = false) { SetTitleFromResource(resourceType, getResourceNameFunc, CultureInfo.CurrentUICulture, ignoreMissingValues); } public void SetTitleFromResource( Type resourceType, Func<FluentActionDefinition, string> getResourceNameFunc, CultureInfo culture, bool ignoreMissingValues = false) { SetTitle(action => { try { return GetResourceValue(resourceType, getResourceNameFunc(action), culture, ignoreMissingValues); } catch (Exception exception) { throw new Exception($"Could not get title from resource {resourceType} for action {action}: {exception.Message ?? ""}", exception); } }); } public void SetDescription(Func<FluentActionDefinition, string> getDescriptionFunc) { Config.GetDescriptionFunc = getDescriptionFunc; } public void SetDescriptionFromResource( Type resourceType, Func<FluentActionDefinition, string> getResourceNameFunc, bool ignoreMissingValues = false) { SetDescriptionFromResource(resourceType, getResourceNameFunc, CultureInfo.CurrentUICulture, ignoreMissingValues); } public void SetDescriptionFromResource( Type resourceType, Func<FluentActionDefinition, string> getResourceNameFunc, CultureInfo culture, bool ignoreMissingValues = false) { SetDescription(action => { try { return GetResourceValue(resourceType, getResourceNameFunc(action), culture, ignoreMissingValues); } catch (Exception exception) { throw new Exception($"Could not get description from resource {resourceType} for action {action}: {exception.Message ?? ""}", exception); } }); } public void WithCustomAttribute<T>() { WithCustomAttribute<T>(new Type[0], new object[0]); } public void WithCustomAttribute<T>(Type[] constructorArgTypes, object[] constructorArgs) { var attributeConstructorInfo = typeof(T).GetConstructor(constructorArgTypes); WithCustomAttribute<T>(attributeConstructorInfo, constructorArgs); } public void WithCustomAttribute<T>(Type[] constructorArgTypes, object[] constructorArgs, string[] namedProperties, object[] propertyValues) { var attributeConstructorInfo = typeof(T).GetConstructor(constructorArgTypes); WithCustomAttribute<T>( attributeConstructorInfo, constructorArgs, namedProperties.Select(propertyName => typeof(T).GetProperty(propertyName)).ToArray(), propertyValues); } public void WithCustomAttribute<T>(ConstructorInfo constructor, object[] constructorArgs) { WithCustomAttribute<T>( constructor, constructorArgs, new PropertyInfo[0], new object[0], new FieldInfo[0], new object[0]); } public void WithCustomAttribute<T>(ConstructorInfo constructor, object[] constructorArgs, FieldInfo[] namedFields, object[] fieldValues) { WithCustomAttribute<T>( constructor, constructorArgs, new PropertyInfo[0], new object[0], namedFields, fieldValues); } public void WithCustomAttribute<T>(ConstructorInfo constructor, object[] constructorArgs, PropertyInfo[] namedProperties, object[] propertyValues) { WithCustomAttribute<T>( constructor, constructorArgs, namedProperties, propertyValues, new FieldInfo[0], new object[0]); } public void WithCustomAttribute<T>(ConstructorInfo constructor, object[] constructorArgs, PropertyInfo[] namedProperties, object[] propertyValues, FieldInfo[] namedFields, object[] fieldValues) { Config.CustomAttributes.Add(new FluentActionCustomAttribute() { Type = typeof(T), Constructor = constructor, ConstructorArgs = constructorArgs, NamedProperties = namedProperties, PropertyValues = propertyValues, NamedFields = namedFields, FieldValues = fieldValues, }); } public void WithCustomAttributeOnClass<T>() { WithCustomAttributeOnClass<T>(new Type[0], new object[0]); } public void WithCustomAttributeOnClass<T>(Type[] constructorArgTypes, object[] constructorArgs) { var attributeConstructorInfo = typeof(T).GetConstructor(constructorArgTypes); WithCustomAttributeOnClass<T>(attributeConstructorInfo, constructorArgs); } public void WithCustomAttributeOnClass<T>( Type[] constructorArgTypes, object[] constructorArgs, string[] namedProperties, object[] propertyValues) { var attributeConstructorInfo = typeof(T).GetConstructor(constructorArgTypes); WithCustomAttributeOnClass<T>( attributeConstructorInfo, constructorArgs, namedProperties.Select(propertyName => typeof(T).GetProperty(propertyName)).ToArray(), propertyValues); } public void WithCustomAttributeOnClass<T>(ConstructorInfo constructor, object[] constructorArgs) { WithCustomAttributeOnClass<T>( constructor, constructorArgs, new PropertyInfo[0], new object[0], new FieldInfo[0], new object[0]); } public void WithCustomAttributeOnClass<T>( ConstructorInfo constructor, object[] constructorArgs, FieldInfo[] namedFields, object[] fieldValues) { WithCustomAttributeOnClass<T>( constructor, constructorArgs, new PropertyInfo[0], new object[0], namedFields, fieldValues); } public void WithCustomAttributeOnClass<T>(ConstructorInfo constructor, object[] constructorArgs, PropertyInfo[] namedProperties, object[] propertyValues) { WithCustomAttributeOnClass<T>( constructor, constructorArgs, namedProperties, propertyValues, new FieldInfo[0], new object[0]); } public void WithCustomAttributeOnClass<T>(ConstructorInfo constructor, object[] constructorArgs, PropertyInfo[] namedProperties, object[] propertyValues, FieldInfo[] namedFields, object[] fieldValues) { Config.CustomAttributesOnClass.Add(new FluentActionCustomAttribute() { Type = typeof(T), Constructor = constructor, ConstructorArgs = constructorArgs, NamedProperties = namedProperties, PropertyValues = propertyValues, NamedFields = namedFields, FieldValues = fieldValues, }); } public void Authorize( string policy = null, string roles = null, string authenticationSchemes = null) { WithCustomAttribute<AuthorizeAttribute>( new Type[] { typeof(string) }, new object[] { policy }, new string[] { "Roles", "AuthenticationSchemes" }, new object[] { roles, authenticationSchemes }); } public void AuthorizeClass( string policy = null, string roles = null, string authenticationSchemes = null) { WithCustomAttributeOnClass<AuthorizeAttribute>( new Type[] { typeof(string) }, new object[] { policy }, new string[] { "Roles", "AuthenticationSchemes" }, new object[] { roles, authenticationSchemes }); } private static string GetResourceValue(Type resourceSourceType, string resourceName, CultureInfo culture, bool ignoreMissingValues = false) { var resourceValue = new ResourceManager(resourceSourceType).GetString(resourceName, culture); if (resourceValue == null && !ignoreMissingValues) { throw new Exception($"Resource is missing value for name {resourceName}."); } return resourceValue; } } public class FluentActionCollectionConfig { public string GroupName { get; internal set; } public bool? IgnoreApi { get; internal set; } public Type ParentType { get; internal set; } public Func<FluentActionDefinition, string> GetTitleFunc { get; internal set; } public Func<FluentActionDefinition, string> GetDescriptionFunc { get; internal set; } public IList<FluentActionCustomAttribute> CustomAttributes { get; internal set; } public IList<FluentActionCustomAttribute> CustomAttributesOnClass { get; internal set; } public IList<Func<FluentAction<object, object>, FluentActionBase>> Appenders { get; internal set; } public FluentActionCollectionConfig() { CustomAttributes = new List<FluentActionCustomAttribute>(); CustomAttributesOnClass = new List<FluentActionCustomAttribute>(); Appenders = new List<Func<FluentAction<object, object>, FluentActionBase>>(); } internal FluentActionCollectionConfig Clone() { return new FluentActionCollectionConfig { GroupName = GroupName, IgnoreApi = IgnoreApi, ParentType = ParentType, GetTitleFunc = GetTitleFunc, GetDescriptionFunc = GetDescriptionFunc, CustomAttributes = new List<FluentActionCustomAttribute>(CustomAttributes), CustomAttributesOnClass = new List<FluentActionCustomAttribute>(CustomAttributesOnClass), Appenders = new List<Func<FluentAction<object, object>, FluentActionBase>>(Appenders), }; } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithParent.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithParent { [Fact(DisplayName = "1 parent (from action), returns string")] public void FluentControllerBuilder_FluentActionUsingParentFromActionReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .InheritingFrom<BaseController>() .UsingParent() .To(parent => parent.Hello()), typeof(ControllerWithParentReturnsString), null); } [Fact(DisplayName = "1 parent (from config), returns string")] public void FluentControllerBuilder_FluentActionUsingParentFromConfigReturnsString() { var collection = FluentActionCollection.DefineActions(actions => { actions.Configure(config => { config.InheritingFrom<BaseController>(); }); actions.RouteGet("/route/url") .UsingParent<BaseController>() .To(parent => parent.Hello()); }); BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( collection.FluentActions[0], typeof(ControllerWithParentReturnsString), null); } [Fact(DisplayName = "1 parent (from action), 1 query string parameter (string), returns string")] public void FluentControllerBuilder_FluentActionUsingParentUsingQueryStringParameterFromActionReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .InheritingFrom<BaseController>() .UsingQueryStringParameter<string>("name") .UsingParent() .To((name, parent) => parent.Hello(name)), typeof(ControllerWithParentAndBodyReturnsString), new object[] { "Oscar" }); } [Fact(DisplayName = "1 parent (from action), returns string async")] public void FluentControllerBuilder_FluentActionUsingParentFromActionReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .InheritingFrom<BaseController>() .UsingParent() .To(async parent => { await Task.Delay(1); return parent.Hello(); }), typeof(ControllerWithParentReturnsStringAsync), null); } [Fact(DisplayName = "1 parent (from action), 1 query string parameter (string), returns string async")] public void FluentControllerBuilder_FluentActionUsingParentUsingQueryStringParameterFromActionReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .InheritingFrom<BaseController>() .UsingQueryStringParameter<string>("name") .UsingParent() .To(async (name, parent) => { await Task.Delay(1); return parent.Hello(name); }), typeof(ControllerWithParentAndBodyReturnsStringAsync), new object[] { "Oscar" }); } } } <|start_filename|>test/WebApps/SimpleMvc/Views/Plain/HelloWorld.cshtml<|end_filename|>  <h2>Hello World!</h2> @if (ViewBag.ViewBagMessage != null) { <h4>@ViewBag.ViewBagMessage</h4> } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.Utils/TypeComparisonFeature.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace ExplicitlyImpl.FluentActions.Test.Utils { public enum TypeComparisonFeature { Name, ParentType, HandlerActionMethod } public interface TypeFeatureComparer { IEnumerable<TypeFeatureComparisonResult> Compare(Type Type1, Type Type2, TypeComparerOptions options); } public class TypeNameComparer : TypeFeatureComparer { public IEnumerable<TypeFeatureComparisonResult> Compare(Type type1, Type type2, TypeComparerOptions options) { var namesMatch = type1.Name == type2.Name; return new[] { new TypeFeatureComparisonResult( TypeComparisonFeature.Name, namesMatch, namesMatch ? "Names match." : "Names do not match.") }; } } public class ParentTypeComparer : TypeFeatureComparer { public IEnumerable<TypeFeatureComparisonResult> Compare(Type type1, Type type2, TypeComparerOptions options) { var comparisonResults = new List<TypeFeatureComparisonResult>(); var parentTypesMatch = type1.GetTypeInfo().BaseType == type2.GetTypeInfo().BaseType; comparisonResults.Add(new TypeFeatureComparisonResult( TypeComparisonFeature.ParentType, parentTypesMatch, parentTypesMatch ? "Parent types match." : "Parent types do not match." )); var attributesForType1 = type1.GetTypeInfo().GetCustomAttributes() .ToArray(); var attributesForType2 = type2.GetTypeInfo().GetCustomAttributes() .ToArray(); for (var attributeIndex = 0; attributeIndex < attributesForType1.Length; attributeIndex++) { if (attributesForType1[attributeIndex].GetType() != attributesForType2[attributeIndex].GetType()) { comparisonResults.Add(new TypeFeatureComparisonResult( TypeComparisonFeature.HandlerActionMethod, false, $"Attribute types do not match between action methods (attribute index: {attributeIndex}).")); } } return comparisonResults; } } public class HandlerActionMethodComparer : TypeFeatureComparer { public IEnumerable<TypeFeatureComparisonResult> Compare(Type type1, Type type2, TypeComparerOptions options) { var comparisonResults = new List<TypeFeatureComparisonResult>(); var typeInfo1 = type1.GetTypeInfo(); var typeInfo2 = type2.GetTypeInfo(); var actionMethodForType1 = type1.GetTypeInfo().GetDeclaredMethods("HandlerAction").First(); if (actionMethodForType1 == null) { comparisonResults.Add(new TypeFeatureComparisonResult( TypeComparisonFeature.HandlerActionMethod, false, $"Type {type1.Name} is missing a handler action method.")); } var actionMethodForType2 = type2.GetTypeInfo().GetDeclaredMethods("HandlerAction").First(); if (actionMethodForType2 == null) { comparisonResults.Add(new TypeFeatureComparisonResult( TypeComparisonFeature.HandlerActionMethod, false, $"Type {type2.Name} is missing a handler action method.")); } if (actionMethodForType1 == null || actionMethodForType2 == null) { return comparisonResults; } var parametersForType1 = actionMethodForType1.GetParameters(); var parametersForType2 = actionMethodForType2.GetParameters(); if (parametersForType1.Length != parametersForType2.Length) { comparisonResults.Add(new TypeFeatureComparisonResult( TypeComparisonFeature.HandlerActionMethod, false, $"Parameter count does not match between action methods ({parametersForType1.Length} vs {parametersForType2.Length}).")); } else { for(var parameterIndex = 0; parameterIndex < parametersForType1.Length; parameterIndex++) { if (parametersForType1[parameterIndex].ParameterType != parametersForType2[parameterIndex].ParameterType) { comparisonResults.Add(new TypeFeatureComparisonResult( TypeComparisonFeature.HandlerActionMethod, false, $"Parameter types do not match between action methods (parameter index: {parameterIndex}).")); } else { var parameterAttributes1 = parametersForType1[parameterIndex].CustomAttributes .Where(attribute => attribute.AttributeType != typeof(OptionalAttribute)) .ToArray(); var parameterAttributes2 = parametersForType2[parameterIndex].CustomAttributes .Where(attribute => attribute.AttributeType != typeof(OptionalAttribute)) .ToArray(); if (parameterAttributes1.Length != parameterAttributes2.Length) { comparisonResults.Add(new TypeFeatureComparisonResult( TypeComparisonFeature.HandlerActionMethod, false, $"Parameter attribute count does not match between action methods for parameter at index {parameterIndex} ({parameterAttributes1.Length} vs {parameterAttributes2.Length}).")); } else { for (var parameterAttributeIndex = 0; parameterAttributeIndex < parameterAttributes1.Length; parameterAttributeIndex++) { if (parameterAttributes1[parameterAttributeIndex].AttributeType != parameterAttributes2[parameterAttributeIndex].AttributeType) { comparisonResults.Add(new TypeFeatureComparisonResult( TypeComparisonFeature.HandlerActionMethod, false, $"Parameter attribute types do not match between action methods for parameter at index {parameterIndex} ({parameterAttributes1[parameterAttributeIndex].AttributeType} vs {parameterAttributes2[parameterAttributeIndex].AttributeType}).")); } else if (parameterAttributes1[parameterAttributeIndex].AttributeType == typeof(ModelBinderAttribute)) { var parameterAttribute1 = parameterAttributes1[parameterAttributeIndex]; var parameterAttribute2 = parameterAttributes2[parameterAttributeIndex]; if (parameterAttribute1.NamedArguments.Count != parameterAttribute2.NamedArguments.Count) { comparisonResults.Add(new TypeFeatureComparisonResult( TypeComparisonFeature.HandlerActionMethod, false, $"Named argument count for ModelBinderAttribute does not match between action methods for parameter at index {parameterIndex} ({parameterAttribute1.NamedArguments.Count} vs {parameterAttribute2.NamedArguments.Count}).")); } else { // TODO } } } } } } } if (actionMethodForType1.ReturnType != actionMethodForType2.ReturnType) { comparisonResults.Add(new TypeFeatureComparisonResult( TypeComparisonFeature.HandlerActionMethod, false, $"Return type does not match between action methods ({actionMethodForType1.ReturnType.Name} vs {actionMethodForType2.ReturnType.Name}).")); } var attributesForType1 = actionMethodForType1.GetCustomAttributes() .ToArray(); var attributesForType2 = actionMethodForType2.GetCustomAttributes() .Where(attribute => !(attribute is AsyncStateMachineAttribute) && !(attribute is DebuggerStepThroughAttribute)) .ToArray(); if (attributesForType1.Count() != attributesForType2.Count()) { comparisonResults.Add(new TypeFeatureComparisonResult( TypeComparisonFeature.HandlerActionMethod, false, $"Custom attribute count does not match between action methods ({attributesForType1.Count()} vs {attributesForType2.Count()}).")); } else { for(var attributeIndex = 0; attributeIndex < attributesForType1.Length; attributeIndex++) { if (attributesForType1[attributeIndex].GetType() != attributesForType2[attributeIndex].GetType()) { comparisonResults.Add(new TypeFeatureComparisonResult( TypeComparisonFeature.HandlerActionMethod, false, $"Attribute types do not match between action methods (attribute index: {attributeIndex}).")); } else if (attributesForType1[attributeIndex] is RouteAttribute) { var routeTemplate1 = ((RouteAttribute)attributesForType1[attributeIndex]).Template; var routeTemplate2 = ((RouteAttribute)attributesForType2[attributeIndex]).Template; if (routeTemplate1 != routeTemplate2) { comparisonResults.Add(new TypeFeatureComparisonResult( TypeComparisonFeature.HandlerActionMethod, false, $"Route templates do not match between action methods ({routeTemplate1} vs {routeTemplate2}).")); } } else if (attributesForType1[attributeIndex] is ApiExplorerSettingsAttribute) { var apiExplorerSettings1 = (ApiExplorerSettingsAttribute)attributesForType1[attributeIndex]; var apiExplorerSettings2 = (ApiExplorerSettingsAttribute)attributesForType2[attributeIndex]; if (apiExplorerSettings1.GroupName != apiExplorerSettings2.GroupName) { comparisonResults.Add(new TypeFeatureComparisonResult( TypeComparisonFeature.HandlerActionMethod, false, $"ApiExplorerSettingsAttribute.GroupName does not match between action methods ({apiExplorerSettings1.GroupName} vs {apiExplorerSettings2.GroupName}).")); } if (apiExplorerSettings1.IgnoreApi != apiExplorerSettings2.IgnoreApi) { comparisonResults.Add(new TypeFeatureComparisonResult( TypeComparisonFeature.HandlerActionMethod, false, $"ApiExplorerSettingsAttribute.IgnoreApi does not match between action methods ({apiExplorerSettings1.IgnoreApi} vs {apiExplorerSettings2.IgnoreApi}).")); } } } } if (!comparisonResults.Any()) { comparisonResults.Add(new TypeFeatureComparisonResult( TypeComparisonFeature.HandlerActionMethod, true, $"Types have matching handler action methods.")); } return comparisonResults; } } public static class TypeFeatureComparers { public static Dictionary<TypeComparisonFeature, TypeFeatureComparer> All = new Dictionary<TypeComparisonFeature, TypeFeatureComparer> { { TypeComparisonFeature.Name , new TypeNameComparer() }, { TypeComparisonFeature.ParentType , new ParentTypeComparer() }, { TypeComparisonFeature.HandlerActionMethod , new HandlerActionMethodComparer() }, }; } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithFormFiles.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System.Linq; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithFormFiles { [Fact(DisplayName = "1 form file, returns string")] public void FluentControllerBuilder_FluentActionUsingFormFileReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticAction( new FluentAction("/route/url", HttpMethod.Post) .UsingFormFile("file") .To(file => $"Got file with name {file.FileName}!"), typeof(ControllerWithFormFileReturnsString)); } [Fact(DisplayName = "1 form file, returns string async")] public void FluentControllerBuilder_FluentActionUsingFormFileReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticAction( new FluentAction("/route/url", HttpMethod.Post) .UsingFormFile("file") .To(async file => { await Task.Delay(1); return $"Got file with name {file.FileName}!"; }), typeof(ControllerWithFormFileReturnsStringAsync)); } [Fact(DisplayName = "2 form files, returns string")] public void FluentControllerBuilder_FluentActionUsing2FormFilesReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticAction( new FluentAction("/route/url", HttpMethod.Post) .UsingFormFiles("files") .To(files => $"Got {files.Count()} n.o. files!"), typeof(ControllerWith2FormFilesReturnsString)); } [Fact(DisplayName = "2 form files, returns string async")] public void FluentControllerBuilder_FluentActionUsing2FormFilesReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticAction( new FluentAction("/route/url", HttpMethod.Post) .UsingFormFiles("files") .To(async files => { await Task.Delay(1); return $"Got {files.Count()} n.o. files!"; }), typeof(ControllerWith2FormFilesReturnsStringAsync)); } } } <|start_filename|>test/WebApps/SimpleMvc/Views/Plain/Hello.cshtml<|end_filename|> @model string <h2>Hello @Model!</h2> <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/Builder/FluentActionLoggers.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using Microsoft.Extensions.Logging; using System; using System.Collections.Concurrent; using System.Reflection; using System.Reflection.Emit; using System.Threading.Tasks; namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core.Builder { public static class FluentActionLoggers { public static ConcurrentDictionary<string, ILogger> All = new ConcurrentDictionary<string, ILogger>(); public static string Add(ILogger logger) { var key = Guid.NewGuid().ToString(); if (!All.TryAdd(key, logger)) { throw new Exception($"Tried to add a fluent action logger but key already exists in dictionary ({key})."); } return key; } public static FieldInfo FieldInfo => typeof(FluentActionLoggers).GetField("All"); public static MethodInfo MethodInfo => typeof(ConcurrentDictionary<string, ILogger>) .GetMethod("get_Item"); private static MethodInfo EmptyArrayMethod = typeof(Array) .GetMethod("Empty") .MakeGenericMethod(typeof(object)); private static MethodInfo LogDebugMethod = typeof(LoggerExtensions) .GetMethod("LogDebug", new Type[] { typeof(ILogger), typeof(string), typeof(object[]) }); public static void PushDebugLogOntoStack(ILGenerator ilGenerator, string loggerKey, string message) { // Push the logger from FluentActionLoggers.All[loggerKey] ilGenerator.Emit(OpCodes.Ldsfld, FieldInfo); ilGenerator.Emit(OpCodes.Ldstr, loggerKey); ilGenerator.Emit(OpCodes.Callvirt, MethodInfo); // Push the message ilGenerator.Emit(OpCodes.Ldstr, message); // Push an empty array ilGenerator.Emit(OpCodes.Call, EmptyArrayMethod); // Call LogDebug(logger, message, object[0]) ilGenerator.Emit(OpCodes.Call, LogDebugMethod); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/ControllerWithOnlyApiExplorerSettingsAttribute.cs<|end_filename|> using Microsoft.AspNetCore.Mvc; using System; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { public class ControllerWithGroupNameOnlyApiExplorerSettingsAttribute : Controller { [HttpGet] [Route("/route/url")] [ApiExplorerSettings(GroupName = "CustomGroupName")] public string HandlerAction() { return "Hello"; } } public class ControllerWithIgnoreApiOnlyApiExplorerSettingsAttribute : Controller { [HttpGet] [Route("/route/url")] [ApiExplorerSettings(IgnoreApi = true)] public string HandlerAction() { return "Hello"; } } public class ControllerWithApiExplorerSettingsAttribute : Controller { [HttpGet] [Route("/route/url")] [ApiExplorerSettings(GroupName = "CustomGroupName", IgnoreApi = true)] public string HandlerAction() { return "Hello"; } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithCustomAttributesOnClass.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System; using System.Reflection; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithCustomAttributesOnClass { [Fact(DisplayName = "1 custom attribute on class (empty), returns string")] public void FluentControllerBuilder_FluentActionWith1EmptyCustomAttributeOnClassReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .WithCustomAttributeOnClass<MyCustomAttribute>() .To(() => "hello"), typeof(ControllerWith1EmptyCustomAttributeOnClassReturnsString), null); } [Fact(DisplayName = "1 custom attribute on class (const), returns string")] public void FluentControllerBuilder_FluentActionWith1ConstructorCustomAttributeOnClassReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .WithCustomAttributeOnClass<MyCustomAttribute>(new Type[] { typeof(int) }, new object[] { 10 }) .To(() => "hello"), typeof(ControllerWith1ConstructorCustomAttributeOnClassReturnsString), null); } [Fact(DisplayName = "1 custom attribute on class (const with Type[]), returns string")] public void FluentControllerBuilder_FluentActionWith1ConstructorWithInfoCustomOnClassAttributeReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .WithCustomAttributeOnClass<MyCustomAttribute>( typeof(MyCustomAttribute).GetConstructor(new Type[] { typeof(int) }), new object[] { 10 }) .To(() => "hello"), typeof(ControllerWith1ConstructorCustomAttributeOnClassReturnsString), null); } [Fact(DisplayName = "1 custom attribute on class (prop with Type[]), returns string")] public void FluentControllerBuilder_FluentActionWith1PropertyCustomAttributeOnClassReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .WithCustomAttributeOnClass<MyCustomAttribute>(new Type[0], new object[0], new string[] { "Property" }, new object[] { "prop" }) .To(() => "hello"), typeof(ControllerWith1PropertyCustomAttributeOnClassReturnsString), null); } [Fact(DisplayName = "1 custom attribute on class (prop), returns string")] public void FluentControllerBuilder_FluentActionWith1PropertyWithInfoCustomAttributeOnClassReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .WithCustomAttributeOnClass<MyCustomAttribute>( typeof(MyCustomAttribute).GetConstructor(new Type[0]), new object[0], new PropertyInfo[] { typeof(MyCustomAttribute).GetProperty("Property") }, new object[] { "prop" }) .To(() => "hello"), typeof(ControllerWith1PropertyCustomAttributeOnClassReturnsString), null); } [Fact(DisplayName = "1 custom attribute on class (field), returns string")] public void FluentControllerBuilder_FluentActionWith1FieldCustomAttributeOnClassReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .WithCustomAttributeOnClass<MyCustomAttribute>( typeof(MyCustomAttribute).GetConstructor(new Type[0]), new object[0], new FieldInfo[] { typeof(MyCustomAttribute).GetField("Field") }, new object[] { "field" }) .To(() => "hello"), typeof(ControllerWith1FieldCustomAttributeOnClassReturnsString), null); } [Fact(DisplayName = "1 custom attribute on class (const - prop), returns string")] public void FluentControllerBuilder_FluentActionWith1ConstructorPropertyWithInfoCustomAttributeOnClassReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .WithCustomAttributeOnClass<MyCustomAttribute>( typeof(MyCustomAttribute).GetConstructor(new Type[] { typeof(int) }), new object[] { 10 }, new PropertyInfo[] { typeof(MyCustomAttribute).GetProperty("Property") }, new object[] { "prop" }) .To(() => "hello"), typeof(ControllerWith1ConstructorPropertyCustomAttributeOnClassReturnsString), null); } [Fact(DisplayName = "1 custom attribute on class (const - field), returns string")] public void FluentControllerBuilder_FluentActionWith1ConstructorFieldWithInfoCustomAttributeOnClassReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .WithCustomAttributeOnClass<MyCustomAttribute>( typeof(MyCustomAttribute).GetConstructor(new Type[] { typeof(int) }), new object[] { 10 }, new FieldInfo[] { typeof(MyCustomAttribute).GetField("Field") }, new object[] { "field" }) .To(() => "hello"), typeof(ControllerWith1ConstructorFieldCustomAttributeOnClassReturnsString), null); } [Fact(DisplayName = "1 custom attribute on class (field - prop), returns string")] public void FluentControllerBuilder_FluentActionWith1FieldPropertyWithInfoCustomAttributeOnClassReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .WithCustomAttributeOnClass<MyCustomAttribute>( typeof(MyCustomAttribute).GetConstructor(new Type[0]), new object[0], new PropertyInfo[] { typeof(MyCustomAttribute).GetProperty("Property") }, new object[] { "prop" }, new FieldInfo[] { typeof(MyCustomAttribute).GetField("Field") }, new object[] { "field" }) .To(() => "hello"), typeof(ControllerWith1FieldPropertyCustomAttributeOnClassReturnsString), null); } [Fact(DisplayName = "1 custom attribute on class (const - field - prop), returns string")] public void FluentControllerBuilder_FluentActionWith1ConstructorFieldPropertyWithInfoCustomAttributeOnClassReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .WithCustomAttributeOnClass<MyCustomAttribute>( typeof(MyCustomAttribute).GetConstructor(new Type[] { typeof(int) }), new object[] { 10 }, new PropertyInfo[] { typeof(MyCustomAttribute).GetProperty("Property") }, new object[] { "prop" }, new FieldInfo[] { typeof(MyCustomAttribute).GetField("Field") }, new object[] { "field" }) .To(() => "hello"), typeof(ControllerWith1ConstructorFieldPropertyCustomAttributeOnClassReturnsString), null); } [Fact(DisplayName = "2 custom attributes on class (empty, empty), returns string")] public void FluentControllerBuilder_FluentActionWith2EmptyCustomAttributesOnClassReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .WithCustomAttributeOnClass<MyCustomAttribute>() .WithCustomAttributeOnClass<MySecondCustomAttribute>() .To(() => "hello"), typeof(ControllerWith2EmptyCustomAttributesOnClassReturnsString), null); } [Fact(DisplayName = "1 custom attribute on class (empty), returns ViewResult async")] public void FluentControllerBuilder_FluentActionWith1EmptyCustomAttributeOnClassReturnsViewResultAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .WithCustomAttributeOnClass<MyCustomAttribute>() .To(async () => { await Task.Delay(1); return "hello"; }) .ToView("~/Path/To/ViewWithStringModel.cshtml"), typeof(ControllerWith1EmptyCustomAttributeOnClassReturnsViewResultAsync), null); } [Fact(DisplayName = "2 custom attributes on class (empty, empty), returns ViewResult async")] public void FluentControllerBuilder_FluentActionWith2EmptyCustomAttributesOnClassReturnsViewResultAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .WithCustomAttributeOnClass<MyCustomAttribute>() .WithCustomAttributeOnClass<MySecondCustomAttribute>() .To(async () => { await Task.Delay(1); return "hello"; }) .ToView("~/Path/To/ViewWithStringModel.cshtml"), typeof(ControllerWith2EmptyCustomAttributesOnClassReturnsViewResultAsync), null); } } } <|start_filename|>test/WebApps/MvcWithSwagger/Services/NoteService.cs<|end_filename|> using System; using System.Collections.Generic; using System.Threading.Tasks; namespace MvcWithSwagger { public class NoteItem { public int Id { get; set; } public string Name { get; set; } } public interface INoteService { IList<NoteItem> List(); Task<IList<NoteItem>> ListAsync(); EntityAddResultItem Add(NoteItem note); Task<EntityAddResultItem> AddAsync(NoteItem note); NoteItem Get(int noteId); Task<NoteItem> GetAsync(int noteId); EntityUpdateResultItem Update(int noteId, NoteItem note); Task<EntityUpdateResultItem> UpdateAsync(int noteId, NoteItem note); EntityRemoveResultItem Remove(int noteId); Task<EntityRemoveResultItem> RemoveAsync(int noteId); } public class NoteService : INoteService { public IList<NoteItem> List() { return new List<NoteItem> { new NoteItem { Id = 1, Name = "<NAME>" }, new NoteItem { Id = 2, Name = "<NAME>" }, new NoteItem { Id = 3, Name = "<NAME>" } }; } public async Task<IList<NoteItem>> ListAsync() { await Task.Delay(200); return List(); } public EntityAddResultItem Add(NoteItem note) { return new EntityAddResultItem { Id = DateTimeOffset.Now.Millisecond, Timestamp = DateTimeOffset.Now }; } public async Task<EntityAddResultItem> AddAsync(NoteItem note) { await Task.Delay(200); return Add(note); } public NoteItem Get(int noteId) { return new NoteItem { Id = 1, Name = "<NAME>" }; } public async Task<NoteItem> GetAsync(int noteId) { await Task.Delay(200); return Get(noteId); } public EntityUpdateResultItem Update(int noteId, NoteItem note) { return new EntityUpdateResultItem { Id = noteId, Timestamp = DateTimeOffset.Now }; } public async Task<EntityUpdateResultItem> UpdateAsync(int noteId, NoteItem note) { await Task.Delay(200); return Update(noteId, note); } public EntityRemoveResultItem Remove(int noteId) { return new EntityRemoveResultItem { Id = noteId, Timestamp = DateTimeOffset.Now }; } public async Task<EntityRemoveResultItem> RemoveAsync(int noteId) { await Task.Delay(200); return Remove(noteId); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithServices.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithServices { [Fact(DisplayName = "1 service, returns string")] public void FluentControllerBuilder_FluentActionUsingServiceReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingService<IStringTestService>() .To(stringTestService => stringTestService.GetTestString() + "FromAFluentAction"), typeof(ControllerWithStringService), new object[] { new StringTestService() }); } [Fact(DisplayName = "1 service, returns string async")] public void FluentControllerBuilder_FluentActionUsingServiceReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingService<IStringTestService>() .To(async stringTestService => await stringTestService.GetTestStringAsync() + "FromAFluentAction"), typeof(ControllerWithStringServiceAsync), new object[] { new StringTestService() }); } [Fact(DisplayName = "1 service, returns list of users")] public void FluentControllerBuilder_FluentActionUsingServiceReturnsListOfUsers() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingService<IUserService>() .To(userService => userService.ListUsers()), typeof(ControllerWithUserService), new object[] { new UserService() }); } [Fact(DisplayName = "1 service, returns list of users async")] public void FluentControllerBuilder_FluentActionUsingServiceReturnsListOfUsersAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingService<IUserService>() .To(userService => userService.ListUsersAsync()), typeof(ControllerWithUserServiceAsync), new object[] { new UserService() }); } // No support for multiple parameters of same service [Fact(DisplayName = "2 services of same interface, throws")] public void FluentControllerBuilder_FluentActionUsingMultipleServicesOfSameInterfaceReturnsString() { Assert.Throws<Exception>(() => BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingService<IStringTestService>() .UsingService<IStringTestService>() .To((stringTestService1, stringTestService2) => stringTestService1.GetTestString() + "And" + stringTestService2.GetTestString()), typeof(ControllerWithMultipleServicesOfSameInterface), new object[] { new StringTestService(), new StringTestService2() }) ); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithAuthorizeOnClass.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithAuthorizeClass { [Fact(DisplayName = "1 authorize class (empty), returns string")] public void FluentControllerBuilder_FluentActionWith1AuthorizeClassReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .AuthorizeClass() .To(() => "hello"), typeof(ControllerWith1AuthorizeClassReturnsString), null); } [Fact(DisplayName = "1 authorize class (policy), returns string")] public void FluentControllerBuilder_FluentActionWith1AuthorizeClassPolicyReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .AuthorizeClass(policy: "CanSayHello") .To(() => "hello"), typeof(ControllerWith1AuthorizeClassPolicyReturnsString), null); } [Fact(DisplayName = "1 authorize class (roles), returns string")] public void FluentControllerBuilder_FluentActionWith1AuthorizeClassRolesReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .AuthorizeClass(roles: "Admin") .To(() => "hello"), typeof(ControllerWith1AuthorizeClassRolesReturnsString), null); } [Fact(DisplayName = "1 authorize class (authenticationSchemes), returns string")] public void FluentControllerBuilder_FluentActionWith1AuthorizeClassAuthenticationSchemesReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .AuthorizeClass(authenticationSchemes: "Scheme") .To(() => "hello"), typeof(ControllerWith1AuthorizeClassAuthenticationSchemesReturnsString), null); } [Fact(DisplayName = "1 authorize class (policy - roles - authenticationSchemes), returns string")] public void FluentControllerBuilder_FluentActionWith1AuthorizeClassPolicyRolesAuthenticationSchemesReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .AuthorizeClass("CanSayHello", "Admin", "Scheme") .To(() => "hello"), typeof(ControllerWith1AuthorizeClassPolicyRolesAuthenticationSchemesReturnsString), null); } [Fact(DisplayName = "1 authorize class (empty), returns ViewResult async")] public void FluentControllerBuilder_FluentActionWith1AuthorizeClassReturnsViewResultAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .AuthorizeClass() .To(async () => { await Task.Delay(1); return "hello"; }) .ToView("~/Path/To/ViewWithStringModel.cshtml"), typeof(ControllerWith1AuthorizeClassReturnsViewResultAsync), null); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/ControllersWithHeaders.cs<|end_filename|> using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { public class ControllerWithHeaderReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction([FromHeader]string name) { return $"Hello {name}!"; } } public class ControllerWithHeaderReturnsStringAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<string> HandlerAction([FromHeader]string name) { await Task.Delay(1); return $"Hello {name}!"; } } public class ControllerWithHeaderAndDefaultValueReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction([FromHeader]string name = "Hanzel") { return $"Hello {name}!"; } } public class ControllerWithHeaderAndDefaultValueReturnsStringAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<string> HandlerAction([FromHeader]string name = "Hanzel") { await Task.Delay(1); return $"Hello {name}!"; } } public class ControllerWithTwoIdenticalHeadersReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction([FromHeader]string name) { return $"Hello {name}! I said hello {name}!"; } } public class ControllerWithTwoIdenticalHeadersReturnsStringAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<string> HandlerAction([FromHeader]string name) { await Task.Delay(1); return $"Hello {name}! I said hello {name}!"; } } } <|start_filename|>test/WebApps/SimpleMvc/Views/Form/UploadFile.cshtml<|end_filename|>  <h2>Upload File.</h2> <form method="post" class="form-horizontal" enctype="multipart/form-data"> <div class="form-group"> <label for="file" class="col-md-2 control-label">File:</label> <div class="col-md-10"> <input type="file" name="file" class="form-control" /> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <button type="submit" class="btn btn-default">Upload file</button> </div> </div> </form> <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/ControllersWithAuthorizeOnClass.cs<|end_filename|> using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { [Authorize] public class ControllerWith1AuthorizeClassReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction() { return "hello"; } } [Authorize("CanSayHello")] public class ControllerWith1AuthorizeClassPolicyReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction() { return "hello"; } } [Authorize(Roles = "Admin")] public class ControllerWith1AuthorizeClassRolesReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction() { return "hello"; } } [Authorize(AuthenticationSchemes = "Scheme")] public class ControllerWith1AuthorizeClassAuthenticationSchemesReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction() { return "hello"; } } [Authorize(Policy = "CanSayHello", Roles = "Admin", AuthenticationSchemes = "Scheme")] public class ControllerWith1AuthorizeClassPolicyRolesAuthenticationSchemesReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction() { return "hello"; } } [Authorize] public class ControllerWith1AuthorizeClassReturnsViewResultAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<ViewResult> HandlerAction() { await Task.Delay(1); return View("~/Path/To/ViewWithStringModel.cshtml", "hello"); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/ControllersWithViewComponentResultAsync.cs<|end_filename|> using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { public class ControllerWithNoUsingsXToReturnsViewComponentAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<ViewComponentResult> HandlerAction() { await Task.Delay(1); return ViewComponent("ViewComponentWithStringModel", "Hello World!"); } } public class ControllerWithNoUsingsXDoReturnsViewComponentAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<ViewComponentResult> HandlerAction() { await Task.Delay(1); return ViewComponent("ViewComponentWithoutModel"); } } public class ControllerWithNoUsings1Do1ToReturnsViewComponentAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<ViewComponentResult> HandlerAction() { await Task.Delay(1); return ViewComponent("ViewComponentWithStringModel", "baz"); } } public class ControllerWith1BodyReturnsViewComponentAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<ViewComponentResult> HandlerAction([FromBody]string name) { await Task.Delay(1); return ViewComponent("ViewComponentWithStringModel", $"Hello {name}!"); } } public class ControllerWith1Body1RouteParamReturnsViewComponentAsync : Controller { [HttpGet] [Route("/route/{lastName}")] public async Task<ViewComponentResult> HandlerAction([FromBody]string firstName, [FromRoute]string lastName) { await Task.Delay(1); return ViewComponent("ViewComponentWithStringModel", $"Hello {firstName} {lastName}!"); } } public class ControllerWith1Body1RouteParam2ToReturnsViewComponentAsync : Controller { [HttpGet] [Route("/route/{lastName}")] public async Task<ViewComponentResult> HandlerAction([FromBody]string firstName, [FromRoute]string lastName) { await Task.Delay(1); return ViewComponent("ViewComponentWithStringModel", $"Hello {firstName} {lastName}!"); } } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/FluentActionControllerDefinition.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using System.Reflection; namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions { public class FluentActionControllerDefinition { public string Id { get; set; } public string Name { get; set; } public string ActionName { get; set; } public TypeInfo TypeInfo { get; set; } public string RouteTemplate => FluentAction.RouteTemplate; public FluentActionBase FluentAction { get; set; } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/ControllersWithCustomAttributesOnClass.cs<|end_filename|> using Microsoft.AspNetCore.Mvc; using System; using System.Threading.Tasks; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { [MyCustomAttribute()] public class ControllerWith1EmptyCustomAttributeOnClassReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction() { return "hello"; } } [MyCustomAttribute(10)] public class ControllerWith1ConstructorCustomAttributeOnClassReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction() { return "hello"; } } [MyCustomAttribute(Property = "prop")] public class ControllerWith1PropertyCustomAttributeOnClassReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction() { return "hello"; } } [MyCustomAttribute(Property = "field")] public class ControllerWith1FieldCustomAttributeOnClassReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction() { return "hello"; } } [MyCustomAttribute(ConstructorArg = 10, Property = "prop")] public class ControllerWith1ConstructorPropertyCustomAttributeOnClassReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction() { return "hello"; } } [MyCustomAttribute(ConstructorArg = 10, Field = "field")] public class ControllerWith1ConstructorFieldCustomAttributeOnClassReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction() { return "hello"; } } [MyCustomAttribute(Property = "prop", Field = "field")] public class ControllerWith1FieldPropertyCustomAttributeOnClassReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction() { return "hello"; } } [MyCustomAttribute(ConstructorArg = 10, Property = "prop", Field = "field")] public class ControllerWith1ConstructorFieldPropertyCustomAttributeOnClassReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction() { return "hello"; } } [MyCustomAttribute()] [MySecondCustomAttribute()] public class ControllerWith2EmptyCustomAttributesOnClassReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction() { return "hello"; } } [MyCustomAttribute()] public class ControllerWith1EmptyCustomAttributeOnClassReturnsViewResultAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<ViewResult> HandlerAction() { await Task.Delay(1); return View("~/Path/To/ViewWithStringModel.cshtml", "hello"); } } [MyCustomAttribute()] [MySecondCustomAttribute()] public class ControllerWith2EmptyCustomAttributesOnClassReturnsViewResultAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<ViewResult> HandlerAction() { await Task.Delay(1); return View("~/Path/To/ViewWithStringModel.cshtml", "hello"); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/ControllersWithCustomAttributes.cs<|end_filename|> using Microsoft.AspNetCore.Mvc; using System; using System.Threading.Tasks; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { public class MyCustomAttribute : Attribute { public int ConstructorArg { get; set; } public string Property { get; set; } public string Field; public MyCustomAttribute() { } public MyCustomAttribute(int constructorArg) { ConstructorArg = constructorArg; } } public class MySecondCustomAttribute : Attribute { } public class ControllerWith1EmptyCustomAttributeReturnsString : Controller { [HttpGet] [Route("/route/url")] [MyCustomAttribute()] public string HandlerAction() { return "hello"; } } public class ControllerWith1ConstructorCustomAttributeReturnsString : Controller { [HttpGet] [Route("/route/url")] [MyCustomAttribute(10)] public string HandlerAction() { return "hello"; } } public class ControllerWith1PropertyCustomAttributeReturnsString : Controller { [HttpGet] [Route("/route/url")] [MyCustomAttribute(Property = "prop")] public string HandlerAction() { return "hello"; } } public class ControllerWith1FieldCustomAttributeReturnsString : Controller { [HttpGet] [Route("/route/url")] [MyCustomAttribute(Property = "field")] public string HandlerAction() { return "hello"; } } public class ControllerWith1ConstructorPropertyCustomAttributeReturnsString : Controller { [HttpGet] [Route("/route/url")] [MyCustomAttribute(ConstructorArg = 10, Property = "prop")] public string HandlerAction() { return "hello"; } } public class ControllerWith1ConstructorFieldCustomAttributeReturnsString : Controller { [HttpGet] [Route("/route/url")] [MyCustomAttribute(ConstructorArg = 10, Field = "field")] public string HandlerAction() { return "hello"; } } public class ControllerWith1FieldPropertyCustomAttributeReturnsString : Controller { [HttpGet] [Route("/route/url")] [MyCustomAttribute(Property = "prop", Field = "field")] public string HandlerAction() { return "hello"; } } public class ControllerWith1ConstructorFieldPropertyCustomAttributeReturnsString : Controller { [HttpGet] [Route("/route/url")] [MyCustomAttribute(ConstructorArg = 10, Property = "prop", Field = "field")] public string HandlerAction() { return "hello"; } } public class ControllerWith2EmptyCustomAttributesReturnsString : Controller { [HttpGet] [Route("/route/url")] [MyCustomAttribute()] [MySecondCustomAttribute()] public string HandlerAction() { return "hello"; } } public class ControllerWith1EmptyCustomAttributeReturnsViewResultAsync : Controller { [HttpGet] [Route("/route/url")] [MyCustomAttribute()] public async Task<ViewResult> HandlerAction() { await Task.Delay(1); return View("~/Path/To/ViewWithStringModel.cshtml", "hello"); } } public class ControllerWith2EmptyCustomAttributesReturnsViewResultAsync : Controller { [HttpGet] [Route("/route/url")] [MyCustomAttribute()] [MySecondCustomAttribute()] public async Task<ViewResult> HandlerAction() { await Task.Delay(1); return View("~/Path/To/ViewWithStringModel.cshtml", "hello"); } } } <|start_filename|>samples/HelloWorld/Startup.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; namespace HelloWorld { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc().AddFluentActions(); } public void Configure(IApplicationBuilder app) { app.UseRouting(); app.UseFluentActions(actions => { actions.RouteGet("/").To(() => "Hello World!"); }); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithPartialViewResult.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithPartialViewResult { [Fact(DisplayName = "no usings, no To, returns PartialViewResult")] public void FluentControllerBuilder_FluentActionNoUsingsNoToReturnsPartialView() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .ToPartialView("~/Path/To/PartialViewWithoutModel.cshtml"), typeof(ControllerWithNoUsingsNoToReturnsPartialView), null); } [Fact(DisplayName = "1 body (string), no To, returns PartialViewResult")] public void FluentControllerBuilder_FluentAction1BodyNoToReturnsPartialView() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingBody<string>() .ToPartialView("~/Path/To/PartialViewWithStringModel.cshtml"), typeof(ControllerPassing1BodyReturnsPartialView), new object[] { "Text" }); } [Fact(DisplayName = "1 body (string), 1 route param (string), no To, returns PartialViewResult")] public void FluentControllerBuilder_FluentAction1Body1RouteParamNoToReturnsPartialView() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url/{unused}", HttpMethod.Get) .UsingBody<string>() .UsingRouteParameter<string>("unused") .ToPartialView("~/Path/To/PartialViewWithStringModel.cshtml"), typeof(ControllerWith1Body1RouteParamPassing1BodyReturnsPartialView), new object[] { "Text", "Unused" }); } [Fact(DisplayName = "no usings, 1 To, returns PartialViewResult")] public void FluentControllerBuilder_FluentActionNoUsings1ToReturnsPartialView() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(() => "Hello World!") .ToPartialView("~/Path/To/PartialViewWithStringModel.cshtml"), typeof(ControllerWithNoUsingsXToReturnsPartialView), null); } [Fact(DisplayName = "no usings, 3 To, returns PartialViewResult")] public void FluentControllerBuilder_FluentActionNoUsings3ToReturnsPartialView() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(() => "Hello") .UsingResult() .To(text => $"{text} World") .UsingResult() .To(text => $"{text}!") .ToPartialView("~/Path/To/PartialViewWithStringModel.cshtml"), typeof(ControllerWithNoUsingsXToReturnsPartialView), null); } [Fact(DisplayName = "no usings, 1 Do, returns PartialViewResult")] public void FluentControllerBuilder_FluentActionNoUsings1DoReturnsPartialView() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .Do(() => { /* woop woop */ }) .ToPartialView("~/Path/To/PartialViewWithoutModel.cshtml"), typeof(ControllerWithNoUsingsXDoReturnsPartialView), null); } [Fact(DisplayName = "no usings, 3 Do, returns PartialViewResult")] public void FluentControllerBuilder_FluentActionNoUsings3DoReturnsPartialView() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .Do(() => { /* woop woop */ }) .Do(() => { /* woop woop */ }) .Do(() => { /* woop woop */ }) .ToPartialView("~/Path/To/PartialViewWithoutModel.cshtml"), typeof(ControllerWithNoUsingsXDoReturnsPartialView), null); } [Fact(DisplayName = "no usings, 1 Do, 1 To, returns PartialViewResult")] public void FluentControllerBuilder_FluentActionNoUsings1Do1ToReturnsPartialView() { var foo = "bar"; BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .Do(() => { foo = "baz"; }) .To(() => foo) .ToPartialView("~/Path/To/PartialViewWithStringModel.cshtml"), typeof(ControllerWithNoUsings1Do1ToReturnsPartialView), null); } [Fact(DisplayName = "1 body (string), returns PartialViewResult")] public void FluentControllerBuilder_FluentAction1BodyReturnsPartialView() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingBody<string>() .To(name => $"Hello {name}!") .ToPartialView("~/Path/To/PartialViewWithStringModel.cshtml"), typeof(ControllerWith1BodyReturnsPartialView), new object[] { "Bob" }); } [Fact(DisplayName = "1 body (string), 1 Do, 1 To, returns PartialViewResult")] public void FluentControllerBuilder_FluentAction1Body1DoReturnsPartialView() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .Do(() => { /* woop woop */ }) .UsingBody<string>() .To(name => $"Hello {name}!") .ToPartialView("~/Path/To/PartialViewWithStringModel.cshtml"), typeof(ControllerWith1BodyReturnsPartialView), new object[] { "Bob" }); } [Fact(DisplayName = "1 body (string), 1 route param (string), returns PartialViewResult")] public void FluentControllerBuilder_FluentAction1Body1RouteParamReturnsPartialView() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/{lastName}", HttpMethod.Get) .UsingBody<string>() .UsingRouteParameter<string>("lastName") .To((firstName, lastName) => $"Hello {firstName} {lastName}!") .ToPartialView("~/Path/To/PartialViewWithStringModel.cshtml"), typeof(ControllerWith1Body1RouteParamReturnsPartialView), new object[] { "Bob", "Bobsson" }); } [Fact(DisplayName = "1 body (string), 1 route param (string), 2 To, returns PartialViewResult")] public void FluentControllerBuilder_FluentAction1Body1RouteParam2ToReturnsPartialView() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/{lastName}", HttpMethod.Get) .UsingBody<string>() .To(firstName => $"Hello {firstName}") .UsingRouteParameter<string>("lastName") .To(lastName => $"{lastName}!") .ToPartialView("~/Path/To/PartialViewWithStringModel.cshtml"), typeof(ControllerWith1Body1RouteParam2ToReturnsPartialView), new object[] { "Bob", "Bobsson" }); } } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/LinqExtensions.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using System; using System.Collections; using System.Collections.Generic; namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions { public static class DivideLinqExtension { public static IEnumerable<IEnumerable<TSource>> Divide<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate, bool putHitElementInNextGroup = false) { var enumerator = source.GetEnumerator(); if (!enumerator.MoveNext()) yield break; ContiguousGroup<TSource> current = null; while (true) { current = new ContiguousGroup<TSource>(enumerator, predicate, putHitElementInNextGroup); yield return current; if (current.EndOfCollection) { yield break; } } } class ContiguousGroup<TSource> : IEnumerable<TSource> { private IEnumerator<TSource> Enumerator; private Func<TSource, bool> Predicate; private bool PutHitElementInNextGroup; internal bool EndOfCollection; public ContiguousGroup(IEnumerator<TSource> enumerator, Func<TSource, bool> predicate, bool putHitElementInNextGroup) { Enumerator = enumerator; Predicate = predicate; PutHitElementInNextGroup = putHitElementInNextGroup; } public IEnumerator<TSource> GetEnumerator() { var isFirstElement = true; while (true) { var current = Enumerator.Current; var hit = Predicate(current); if (isFirstElement || !hit || (hit && !PutHitElementInNextGroup)) { yield return Enumerator.Current; if (!Enumerator.MoveNext()) { EndOfCollection = true; yield break; } else if (hit && !PutHitElementInNextGroup) { yield break; } } else { yield break; } isFirstElement = false; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithTempData.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithTempData { [Fact(DisplayName = "1 TempData, returns string")] public void FluentControllerBuilder_FluentActionWithTempDataReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingTempData() .To(tempData => { tempData["foo"] = "bar"; return (string)tempData["foo"]; }), typeof(ControllerWithTempDataReturnsString), null); } [Fact(DisplayName = "1 TempData, returns string async")] public void FluentControllerBuilder_FluentActionWithTempDataReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingTempData() .To(async tempData => { await Task.Delay(1); tempData["foo"] = "bar"; return (string)tempData["foo"]; }), typeof(ControllerWithTempDataReturnsStringAsync), null); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithRouteParameters.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithRouteParameters { [Fact(DisplayName = "1 route parameter (string), returns string")] public void FluentControllerBuilder_FluentActionUsingRouteParmeterReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/{name}", HttpMethod.Get) .UsingRouteParameter<string>("name") .To(name => $"Hello {name}!"), typeof(ControllerWithRouteParameterReturnsString), new object[] { "Charlie" }); } [Fact(DisplayName = "1 route parameter (string), returns string async")] public void FluentControllerBuilder_FluentActionUsingRouteParmeterReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/{name}", HttpMethod.Get) .UsingRouteParameter<string>("name") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }), typeof(ControllerWithRouteParameterReturnsStringAsync), new object[] { "Charlie" }); } [Fact(DisplayName = "1 route parameter (string) with used default value, returns string")] public void FluentControllerBuilder_FluentActionUsingRouteParmeterWithUsedDefaultValueReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/{name}", HttpMethod.Get) .UsingRouteParameter<string>("name", "Hanzel") .To(name => $"Hello {name}!"), typeof(ControllerWithRouteParameterAndDefaultValueReturnsString), new object[] { Type.Missing }); } [Fact(DisplayName = "1 route parameter (string) with used default value, returns string async")] public void FluentControllerBuilder_FluentActionUsingRouteParmeterWithUsedDefaultValueReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/{name}", HttpMethod.Get) .UsingRouteParameter<string>("name", "Hanzel") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }), typeof(ControllerWithRouteParameterAndDefaultValueReturnsStringAsync), new object[] { Type.Missing }); } [Fact(DisplayName = "1 route parameter (string) with unused default value, returns string")] public void FluentControllerBuilder_FluentActionUsingRouteParmeterWithUnusedDefaultValueReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/{name}", HttpMethod.Get) .UsingRouteParameter<string>("name", "Hanzel") .To(name => $"Hello {name}!"), typeof(ControllerWithRouteParameterAndDefaultValueReturnsString), new object[] { "Charlie" }); } [Fact(DisplayName = "1 route parameter (string) with unused default value, returns string async")] public void FluentControllerBuilder_FluentActionUsingRouteParmeterWithUnusedDefaultValueReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/{name}", HttpMethod.Get) .UsingRouteParameter<string>("name", "Hanzel") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }), typeof(ControllerWithRouteParameterAndDefaultValueReturnsStringAsync), new object[] { "Charlie" }); } [Fact(DisplayName = "2 route parameters (string, identical), returns string")] public void FluentControllerBuilder_FluentActionUsingTwoIdenticalRouteParmetersReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/{name}", HttpMethod.Get) .UsingRouteParameter<string>("name") .UsingRouteParameter<string>("name") .To((name1, name2) => $"Hello {name1}! I said hello {name2}!"), typeof(ControllerWithTwoIdenticalRouteParametersReturnsString), new object[] { "Charlie" }); } [Fact(DisplayName = "2 route parameters (string, identical), returns string async")] public void FluentControllerBuilder_FluentActionUsingTwoIdenticalRouteParmetersReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/{name}", HttpMethod.Get) .UsingRouteParameter<string>("name") .UsingRouteParameter<string>("name") .To(async (name1, name2) => { await Task.Delay(1); return $"Hello {name1}! I said hello {name2}!"; }), typeof(ControllerWithTwoIdenticalRouteParametersReturnsStringAsync), new object[] { "Charlie" }); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.Utils/NoOpBinder.cs<|end_filename|> using Microsoft.AspNetCore.Mvc.ModelBinding; using System.Threading.Tasks; namespace ExplicitlyImpl.FluentActions.Test.Utils { public class NoOpBinder : IModelBinder { public static readonly IModelBinder Instance = new NoOpBinder(); public Task BindModelAsync(ModelBindingContext bindingContext) { return Task.CompletedTask; } } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/Builder/ControllerMethodBuilderForFluentActionAsync.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using Microsoft.Extensions.Logging; using System; using System.Collections.Concurrent; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Threading.Tasks; namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core.Builder { public class ControllerMethodBuilderForFluentActionAsync : ControllerMethodBuilder { public FluentActionDefinition FluentActionDefinition { get; set; } public ILogger Logger { get; set; } internal AsyncStateMachineTypeBuilder StateMachineBuilder { get; set; } public ControllerMethodBuilderForFluentActionAsync(FluentActionDefinition fluentActionDefinition, ILogger logger = null) { FluentActionDefinition = fluentActionDefinition; Logger = logger; } public override void Build() { StateMachineBuilder = AsyncStateMachineTypeBuilder.Create(TypeBuilder, FluentActionDefinition, Logger); NestedTypes.Add(StateMachineBuilder.Type); var usingsForMethodParameters = FluentActionDefinition.Handlers .SelectMany(usingHandler => usingHandler.Usings) .Where(@using => @using.IsMethodParameter) .Distinct() .ToArray(); var methodParameterIndices = usingsForMethodParameters .Select((@using, index) => new { Using = @using, Index = index }) .ToDictionary( indexedUsing => indexedUsing.Using.GetHashCode(), indexedUsing => indexedUsing.Index + 1 // 1-based index ); var methodParameterTypes = usingsForMethodParameters .Select(@using => @using.Type) .ToArray(); var returnType = FluentActionDefinition.Handlers.Last().ReturnType; var returnTypeTask = typeof(Task<>).MakeGenericType(returnType); MethodBuilder.SetReturnType(returnTypeTask); MethodBuilder.SetParameters(methodParameterTypes); SetHttpMethodAttribute(FluentActionDefinition.HttpMethod); SetRouteAttribute(FluentActionDefinition.RouteTemplate); foreach (var customAttribute in FluentActionDefinition.CustomAttributes) { SetCustomAttribute(customAttribute); } foreach (var usingDefinition in usingsForMethodParameters) { var methodParameterIndex = methodParameterIndices[usingDefinition.GetHashCode()]; usingDefinition.DefineMethodParameter(MethodBuilder, FluentActionDefinition, usingDefinition, methodParameterIndex); } var dictionaryField = typeof(FluentActionDelegates) .GetField("All"); var dictionaryGetMethod = typeof(ConcurrentDictionary<,>) .MakeGenericType(typeof(string), typeof(Delegate)) .GetMethod("get_Item"); var ilGenerator = MethodBuilder.GetILGenerator(); // === Generate IL for action method ========================== var asyncTaskMethodBuilderType = typeof(AsyncTaskMethodBuilder<>).MakeGenericType(returnType); // Declare local variables var stateMachineLocalVariable = ilGenerator.DeclareLocal(StateMachineBuilder.Type); // Create a StateMachine and store it locally ilGenerator.Emit(OpCodes.Newobj, StateMachineBuilder.Constructor); ilGenerator.Emit(OpCodes.Stloc, stateMachineLocalVariable); // Store reference to parent in field StateMachine.Parent ilGenerator.Emit(OpCodes.Ldloc, stateMachineLocalVariable); ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Stfld, StateMachineBuilder.ParentField); // Create an AsyncTaskMethodBuilder and store it in field StateMachine.AsyncTaskMethodBuilder ilGenerator.Emit(OpCodes.Ldloc, stateMachineLocalVariable); ilGenerator.Emit(OpCodes.Call, asyncTaskMethodBuilderType.GetMethod("Create")); ilGenerator.Emit(OpCodes.Stfld, StateMachineBuilder.AsyncTaskMethodBuilderField); // Set field StateMachine.State = 0 ilGenerator.Emit(OpCodes.Ldloc, stateMachineLocalVariable); ilGenerator.Emit(OpCodes.Ldc_I4_0); ilGenerator.Emit(OpCodes.Stfld, StateMachineBuilder.StateField); // Store parameters to fields in StateMachine foreach (var usingDefinition in usingsForMethodParameters) { var methodParameterIndex = methodParameterIndices[usingDefinition.GetHashCode()]; var methodParameterField = StateMachineBuilder.MethodParameterFields[methodParameterIndex - 1]; ilGenerator.Emit(OpCodes.Ldloc, stateMachineLocalVariable); ilGenerator.Emit(OpCodes.Ldarg, methodParameterIndex); ilGenerator.Emit(OpCodes.Stfld, methodParameterField); } var handlers = StateMachineBuilder.States .SelectMany(state => state.Handlers) .Where(handler => handler.Definition.Type == FluentActionHandlerType.Func || handler.Definition.Type == FluentActionHandlerType.Action); // Store delegates to fields in StateMachine foreach (var handler in handlers) { var delegateKey = FluentActionDelegates.Add(handler.Definition.Delegate); // Push Delegate ilGenerator.Emit(OpCodes.Ldloc, stateMachineLocalVariable); ilGenerator.Emit(OpCodes.Ldsfld, FluentActionDelegates.FieldInfo); ilGenerator.Emit(OpCodes.Ldstr, delegateKey); ilGenerator.Emit(OpCodes.Callvirt, FluentActionDelegates.MethodInfo); // Store in field StateMachine.StateXHandlerYDelegate ilGenerator.Emit(OpCodes.Stfld, handler.DelegateField); } // Start the AsyncTaskMethodBuilder ilGenerator.Emit(OpCodes.Ldloc, stateMachineLocalVariable); ilGenerator.Emit(OpCodes.Ldflda, StateMachineBuilder.AsyncTaskMethodBuilderField); ilGenerator.Emit(OpCodes.Ldloca, stateMachineLocalVariable); ilGenerator.Emit(OpCodes.Call, asyncTaskMethodBuilderType.GetMethod("Start").MakeGenericMethod(StateMachineBuilder.Type)); // Return the Task of AsyncTaskMethodBuilder ilGenerator.Emit(OpCodes.Ldloc, stateMachineLocalVariable); ilGenerator.Emit(OpCodes.Ldflda, StateMachineBuilder.AsyncTaskMethodBuilderField); ilGenerator.Emit(OpCodes.Call, asyncTaskMethodBuilderType.GetProperty("Task").GetGetMethod()); ilGenerator.Emit(OpCodes.Ret); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.Utils/TypeComparer.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using System; using System.Collections.Generic; using System.Linq; namespace ExplicitlyImpl.FluentActions.Test.Utils { public class TypeComparer { public readonly IEnumerable<TypeComparisonFeature> FeaturesToCompare; public readonly TypeComparerOptions Options; public TypeComparer(IEnumerable<TypeComparisonFeature> featuresToCompare, TypeComparerOptions options) { FeaturesToCompare = featuresToCompare; Options = options; } public TypeComparisonResults Compare<T1, T2>() { return Compare(typeof(T1), typeof(T2), FeaturesToCompare, Options); } public static TypeComparisonResults Compare<T1, T2>(IEnumerable<TypeComparisonFeature> featuresToCompare, TypeComparerOptions options) { return Compare(typeof(T1), typeof(T2), featuresToCompare, options); } public TypeComparisonResults Compare(Type type1, Type type2) { return Compare(type1, type2, FeaturesToCompare, Options); } public static TypeComparisonResults Compare(Type type1, Type type2, IEnumerable<TypeComparisonFeature> featuresToCompare, TypeComparerOptions options) { var comparedFeaturesResults = new List<TypeFeatureComparisonResult>(); foreach (var featureToCompare in featuresToCompare) { var comparedFeatureResults = CompareFeature(type1, type2, featureToCompare, options); comparedFeaturesResults.AddRange(comparedFeatureResults); if (options.StopAtFirstMismatch && comparedFeatureResults.Any(comparedFeatureResult => !comparedFeatureResult.CompleteMatch)) { break; } } return new TypeComparisonResults( featuresToCompare, comparedFeaturesResults ); } public static IEnumerable<TypeFeatureComparisonResult> CompareFeature(Type type1, Type type2, TypeComparisonFeature feature, TypeComparerOptions options) { return TypeFeatureComparers.All[feature].Compare(type1, type2, options); } } public class TypeComparerOptions { public bool StopAtFirstMismatch { get; set; } } public class TypeComparisonResults { public readonly IEnumerable<TypeComparisonFeature> ComparedFeatures; public readonly IEnumerable<TypeFeatureComparisonResult> ComparedFeaturesResults; public readonly bool CompleteMatch; public TypeComparisonResults(IEnumerable<TypeComparisonFeature> comparedFeatures, IEnumerable<TypeFeatureComparisonResult> comparedFeaturesResults) { ComparedFeatures = comparedFeatures; ComparedFeaturesResults = comparedFeaturesResults; CompleteMatch = comparedFeaturesResults.All(comparison => comparison.CompleteMatch); } public IEnumerable<TypeComparisonFeature> MismatchingFeatures => ComparedFeaturesResults .Where(comparedFeatureResults => !comparedFeatureResults.CompleteMatch) .Select(comparedFeatureResults => comparedFeatureResults.ComparedFeature); public IEnumerable<TypeFeatureComparisonResult> MismatchingFeaturesResults => ComparedFeaturesResults .Where(comparedFeatureResults => !comparedFeatureResults.CompleteMatch); public IEnumerable<TypeComparisonFeature> MatchingFeatures => ComparedFeaturesResults .Where(comparedFeatureResults => comparedFeatureResults.CompleteMatch) .Select(comparedFeatureResults => comparedFeatureResults.ComparedFeature); public IEnumerable<TypeFeatureComparisonResult> MatchingFeaturesResults => ComparedFeaturesResults .Where(comparedFeatureResults => comparedFeatureResults.CompleteMatch); } public class TypeFeatureComparisonResult { public readonly TypeComparisonFeature ComparedFeature; public readonly bool CompleteMatch; public readonly string Message; public TypeFeatureComparisonResult(TypeComparisonFeature comparedFeature, bool completeMatch, string message) { ComparedFeature = comparedFeature; CompleteMatch = completeMatch; Message = message; } } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/UsingDefinitions/UsingRequestDefinition.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions { public class FluentActionUsingRequestDefinition : FluentActionUsingDefinition { public override bool IsControllerProperty => true; public override string ControllerPropertyName => "Request"; } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithParentType.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithParentType { [Fact(DisplayName = "1 parent type, returns string")] public void FluentControllerBuilder_FluentActionWithParentTypeReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .InheritingFrom<BaseController>() .To(() => $"hello"), typeof(ControllerWithParentTypeReturnsString), null); } [Fact(DisplayName = "1 parent type in config, returns string")] public void FluentControllerBuilder_FluentActionWithParentTypeInConfigReturnsString() { var actionCollection = FluentActionCollection.DefineActions( actions => { actions.Configure(config => { config.InheritingFrom(typeof(BaseController)); }); actions.Add( new FluentAction("/route/url", HttpMethod.Get) .InheritingFrom<BaseController>() .To(() => $"hello") ); } ); BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( actionCollection.FluentActions[0], typeof(ControllerWithParentTypeReturnsString), null); } [Fact(DisplayName = "1 parent type in config")] public void FluentControllerBuilder_FluentActionCollectionWithParentTypeInConfig() { var actionCollection = FluentActionCollection.DefineActions( actions => { actions.Configure(config => { config.InheritingFrom<BaseController>(); }); actions .RouteGet("/users", "ListUsers") .UsingService<IUserService>() .To(userService => userService.ListUsers()); actions .RoutePost("/users", "AddUser") .UsingService<IUserService>() .UsingBody<UserItem>() .To((userService, user) => userService.AddUser(user)); actions .RouteGet("/users/{userId}", "GetUser") .UsingService<IUserService>() .UsingRouteParameter<int>("userId") .To((userService, userId) => userService.GetUserById(userId)); actions .RoutePut("/users/{userId}", "UpdateUser") .UsingService<IUserService>() .UsingRouteParameter<int>("userId") .UsingBody<UserItem>() .To((userService, userId, user) => userService.UpdateUser(userId, user)); actions .RouteDelete("/users/{userId}", "RemoveUser") .UsingService<IUserService>() .UsingRouteParameter<int>("userId") .To((userService, userId) => userService.RemoveUser(userId)); } ); foreach (var action in actionCollection) { Assert.Equal(typeof(BaseController), action.Definition.ParentType); } } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithProperty.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using Microsoft.AspNetCore.Http; using System; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithProperty { [Fact(DisplayName = "1 Property (Response), returns string")] public void FluentControllerBuilder_FluentActionWithPropertyReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingProperty<HttpResponse>("Response") .To(response => { if (response == null) { throw new Exception("Response is null inside fluent action delegate."); } return "Hello"; }), typeof(ControllerWithPropertyReturnsString), null); } [Fact(DisplayName = "1 Property (Response), returns string async")] public void FluentControllerBuilder_FluentActionWithPropertyReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .DoAsync(async () => { await Task.Delay(1); }) .UsingProperty<HttpResponse>("Response") .To(async response => { await Task.Delay(1); if (response == null) { throw new Exception("Response is null inside fluent action delegate."); } return "Hello"; }), typeof(ControllerWithPropertyReturnsStringAsync), null); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithQueryStringParameters.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithQueryStringParameters { [Fact(DisplayName = "1 query string parameter (string), returns string")] public void FluentControllerBuilder_FluentActionUsingQueryStringParmeterReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingQueryStringParameter<string>("name") .To(name => $"Hello {name}!"), typeof(ControllerWithQueryStringParameterReturnsString), new object[] { "Charlie" }); } [Fact(DisplayName = "1 query string parameter (string), returns string async")] public void FluentControllerBuilder_FluentActionUsingQueryStringParmeterReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingQueryStringParameter<string>("name") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }), typeof(ControllerWithQueryStringParameterReturnsStringAsync), new object[] { "Charlie" }); } [Fact(DisplayName = "1 query string parameter (string) with used default value, returns string")] public void FluentControllerBuilder_FluentActionUsingQueryStringParameterWithUsedDefaultValueReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingQueryStringParameter<string>("name", "Hanzel") .To(name => $"Hello {name}!"), typeof(ControllerWithQueryStringParameterAndDefaultValueReturnsString), new object[] { Type.Missing }); } [Fact(DisplayName = "1 query string parameter (string) with used default value, returns string async")] public void FluentControllerBuilder_FluentActionUsingQueryStringParameterWithUsedDefaultValueReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingQueryStringParameter<string>("name", "Hanzel") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }), typeof(ControllerWithQueryStringParameterAndDefaultValueReturnsStringAsync), new object[] { Type.Missing }); } [Fact(DisplayName = "1 query string parameter (string) with unused default value, returns string")] public void FluentControllerBuilder_FluentActionUsingQueryStringParameterWithUnusedDefaultValueReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingQueryStringParameter<string>("name", "Hanzel") .To(name => $"Hello {name}!"), typeof(ControllerWithQueryStringParameterAndDefaultValueReturnsString), new object[] { "Charlie" }); } [Fact(DisplayName = "1 query string parameter (string) with unused default value, returns string async")] public void FluentControllerBuilder_FluentActionUsingQueryStringParameterWithUnusedDefaultValueReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingQueryStringParameter<string>("name", "Hanzel") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }), typeof(ControllerWithQueryStringParameterAndDefaultValueReturnsStringAsync), new object[] { "Charlie" }); } [Fact(DisplayName = "2 query string parameters (string, identical), returns string")] public void FluentControllerBuilder_FluentActionUsingTwoIdenticalQueryStringParmetersReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingQueryStringParameter<string>("name") .UsingQueryStringParameter<string>("name") .To((name1, name2) => $"Hello {name1}! I said hello {name2}!"), typeof(ControllerWithTwoIdenticalQueryStringParametersReturnsString), new object[] { "Charlie" }); } [Fact(DisplayName = "2 query string parameters (string, identical), returns string async")] public void FluentControllerBuilder_FluentActionUsingTwoIdenticalQueryStringParmetersReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingQueryStringParameter<string>("name") .UsingQueryStringParameter<string>("name") .To(async (name1, name2) => { await Task.Delay(1); return $"Hello {name1}! I said hello {name2}!"; }), typeof(ControllerWithTwoIdenticalQueryStringParametersReturnsStringAsync), new object[] { "Charlie" }); } } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/HttpMethod.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions { public enum HttpMethod { Delete, Get, Head, Options, Patch, Post, Put } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithViewComponentResultAsync.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithViewComponentResultAsync { [Fact(DisplayName = "no usings, 1 To, returns ViewComponentResult async")] public void FluentControllerBuilder_FluentActionNoUsings1ToReturnsViewComponentAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(async () => { await Task.Delay(1); return "Hello World!"; }) .ToViewComponent("ViewComponentWithStringModel"), typeof(ControllerWithNoUsingsXToReturnsViewComponentAsync), null); } [Fact(DisplayName = "no usings, 3 To, returns ViewComponentResult async")] public void FluentControllerBuilder_FluentActionNoUsings3ToReturnsViewComponentAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(async () => { await Task.Delay(1); return "Hello"; }) .UsingResult() .To(async text => { await Task.Delay(1); return $"{text} World"; }) .UsingResult() .To(async text => { await Task.Delay(1); return $"{text}!"; }) .ToViewComponent("ViewComponentWithStringModel"), typeof(ControllerWithNoUsingsXToReturnsViewComponentAsync), null); } [Fact(DisplayName = "no usings, 1 Do, returns ViewComponentResult async")] public void FluentControllerBuilder_FluentActionNoUsings1DoReturnsViewComponentAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .DoAsync(async () => { await Task.Delay(1); }) .ToViewComponent("ViewComponentWithoutModel"), typeof(ControllerWithNoUsingsXDoReturnsViewComponentAsync), null); } [Fact(DisplayName = "no usings, 3 Do, returns ViewComponentResult async")] public void FluentControllerBuilder_FluentActionNoUsings3DoReturnsViewComponentAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .DoAsync(async () => { await Task.Delay(1); }) .DoAsync(async () => { await Task.Delay(1); }) .DoAsync(async () => { await Task.Delay(1); }) .ToViewComponent("ViewComponentWithoutModel"), typeof(ControllerWithNoUsingsXDoReturnsViewComponentAsync), null); } [Fact(DisplayName = "no usings, 1 Do, 1 To, returns ViewComponentResult async")] public void FluentControllerBuilder_FluentActionNoUsings1Do1ToReturnsViewComponentAsync() { var foo = "bar"; BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .DoAsync(async () => { await Task.Delay(1); foo = "baz"; }) .To(async () => { await Task.Delay(1); return foo; }) .ToViewComponent("ViewComponentWithStringModel"), typeof(ControllerWithNoUsings1Do1ToReturnsViewComponentAsync), null); } [Fact(DisplayName = "1 body (string), returns ViewComponentResult async")] public void FluentControllerBuilder_FluentAction1BodyReturnsViewComponentAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingBody<string>() .To(async (name) => { await Task.Delay(1); return $"Hello {name}!"; }) .ToViewComponent("ViewComponentWithStringModel"), typeof(ControllerWith1BodyReturnsViewComponentAsync), new object[] { "Bob" }); } [Fact(DisplayName = "1 body (string), 1 Do, 1 To, returns ViewComponentResult async")] public void FluentControllerBuilder_FluentAction1Body1DoReturnsViewComponentAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .DoAsync(async () => { await Task.Delay(1); }) .UsingBody<string>() .To(async (name) => { await Task.Delay(1); return $"Hello {name}!"; }) .ToViewComponent("ViewComponentWithStringModel"), typeof(ControllerWith1BodyReturnsViewComponentAsync), new object[] { "Bob" }); } [Fact(DisplayName = "1 body (string), 1 route param (string), returns ViewComponentResult async")] public void FluentControllerBuilder_FluentAction1Body1RouteParamReturnsViewComponentAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/{lastName}", HttpMethod.Get) .UsingBody<string>() .UsingRouteParameter<string>("lastName") .To(async (firstName, lastName) => { await Task.Delay(1); return $"Hello {firstName} {lastName}!"; }) .ToViewComponent("ViewComponentWithStringModel"), typeof(ControllerWith1Body1RouteParamReturnsViewComponentAsync), new object[] { "Bob", "Bobsson" }); } [Fact(DisplayName = "1 body (string), 1 route param (string), 2 To, returns ViewComponentResult async")] public void FluentControllerBuilder_FluentAction1Body1RouteParam2ToReturnsViewComponentAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/{lastName}", HttpMethod.Get) .UsingBody<string>() .To(async firstName => { await Task.Delay(1); return $"Hello {firstName}"; }) .UsingRouteParameter<string>("lastName") .To(async lastName => { await Task.Delay(1); return $"{lastName}!"; }) .ToViewComponent("ViewComponentWithStringModel"), typeof(ControllerWith1Body1RouteParam2ToReturnsViewComponentAsync), new object[] { "Bob", "Bobsson" }); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/ControllersWithRouteParameters.cs<|end_filename|> using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { public class ControllerWithRouteParameterReturnsString : Controller { [HttpGet] [Route("/route/{name}")] public string HandlerAction([FromRoute]string name) { return $"Hello {name}!"; } } public class ControllerWithRouteParameterReturnsStringAsync : Controller { [HttpGet] [Route("/route/{name}")] public async Task<string> HandlerAction([FromRoute]string name) { await Task.Delay(1); return $"Hello {name}!"; } } public class ControllerWithRouteParameterAndDefaultValueReturnsString : Controller { [HttpGet] [Route("/route/{name}")] public string HandlerAction([FromRoute]string name = "Hanzel") { return $"Hello {name}!"; } } public class ControllerWithRouteParameterAndDefaultValueReturnsStringAsync : Controller { [HttpGet] [Route("/route/{name}")] public async Task<string> HandlerAction([FromRoute]string name = "Hanzel") { await Task.Delay(1); return $"Hello {name}!"; } } public class ControllerWithTwoIdenticalRouteParametersReturnsString : Controller { [HttpGet] [Route("/route/{name}")] public string HandlerAction([FromRoute]string name) { return $"Hello {name}! I said hello {name}!"; } } public class ControllerWithTwoIdenticalRouteParametersReturnsStringAsync : Controller { [HttpGet] [Route("/route/{name}")] public async Task<string> HandlerAction([FromRoute]string name) { await Task.Delay(1); return $"Hello {name}! I said hello {name}!"; } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithBody.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithBody { [Fact(DisplayName = "1 body (string), returns string")] public void FluentControllerBuilder_FluentActionUsingBodyReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingBody<string>() .To(name => $"Hello {name}!"), typeof(ControllerWithBodyReturnsString), new object[] { "Charlie" }); } [Fact(DisplayName = "1 body (string), returns string async")] public void FluentControllerBuilder_FluentActionUsingBodyReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingBody<string>() .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }), typeof(ControllerWithBodyReturnsStringAsync), new object[] { "Charlie" }); } [Fact(DisplayName = "1 body (string) with used default value, returns string")] public void FluentControllerBuilder_FluentActionUsingBodyWithUsedDefaultValueReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingBody<string>("Hanzel") .To(name => $"Hello {name}!"), typeof(ControllerWithBodyAndDefaultValueReturnsString), new object[] { Type.Missing }); } [Fact(DisplayName = "1 body (string) with used default value, returns string async")] public void FluentControllerBuilder_FluentActionUsingBodyWithUsedDefaultValueReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingBody<string>("Hanzel") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }), typeof(ControllerWithBodyAndDefaultValueReturnsStringAsync), new object[] { Type.Missing }); } [Fact(DisplayName = "1 body (string) with unused default value, returns string")] public void FluentControllerBuilder_FluentActionUsingBodyWithUnusedDefaultValueReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingBody<string>("Hanzel") .To(name => $"Hello {name}!"), typeof(ControllerWithBodyAndDefaultValueReturnsString), new object[] { "Charlie" }); } [Fact(DisplayName = "1 body (string) with unused default value, returns string")] public void FluentControllerBuilder_FluentActionUsingBodyWithUnusedDefaultValueReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingBody<string>("Hanzel") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }), typeof(ControllerWithBodyAndDefaultValueReturnsStringAsync), new object[] { "Charlie" }); } [Fact(DisplayName = "2 body (string, identical), returns string")] public void FluentControllerBuilder_FluentActionUsingTwoIdenticalBodysReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingBody<string>() .UsingBody<string>() .To(async (name1, name2) => { await Task.Delay(1); return $"Hello {name1}! I said hello {name2}!"; }), typeof(ControllerWithTwoIdenticalBodysReturnsStringAsync), new object[] { "Charlie" }); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithoutUsings.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System; using System.Threading.Tasks; using Xunit; using static ExplicitlyImpl.AspNetCore.Mvc.FluentActions.FluentActionControllerDefinitionBuilder; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithoutUsings { [Fact(DisplayName = "No handler, throws")] public void FluentControllerBuilder_ThrowsOnFluentActionWithoutHandler() { var fluentAction = new FluentAction("/route/url", HttpMethod.Get); Assert.Throws<FluentActionValidationException>(() => BuilderTestUtils.BuildAction(fluentAction)); } [Fact(DisplayName = "No usings, returns string")] public void FluentControllerBuilder_FluentActionWithoutUsingsAndReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(() => "Hello"), typeof(ParameterlessControllerReturnsString), null); } [Fact(DisplayName = "No usings, returns string async")] public void FluentControllerBuilder_FluentActionWithoutUsingsAndReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(async () => { await Task.Delay(1); return "Hello"; }), typeof(ParameterlessControllerReturnsStringAsync), null); } [Fact(DisplayName = "No usings, returns int")] public void FluentControllerBuilder_FluentActionWithoutUsingsAndReturnsInt() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(() => 13), typeof(ParameterlessControllerReturnsInt), null); } [Fact(DisplayName = "No usings, returns int async")] public void FluentControllerBuilder_FluentActionWithoutUsingsAndReturnsIntAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(async () => { await Task.Delay(1); return 13; }), typeof(ParameterlessControllerReturnsIntAsync), null); } [Fact(DisplayName = "No usings, returns guid")] public void FluentControllerBuilder_FluentActionWithoutUsingsAndReturnsGuid() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(() => new Guid("2a6d4959-817c-4514-90f3-52b518e9ddb0")), typeof(ParameterlessControllerReturnsGuid), null); } [Fact(DisplayName = "No usings, returns guid async")] public void FluentControllerBuilder_FluentActionWithoutUsingsAndReturnsGuidAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(async () => { await Task.Delay(1); return new Guid("2a6d4959-817c-4514-90f3-52b518e9ddb0"); }), typeof(ParameterlessControllerReturnsGuidAsync), null); } [Fact(DisplayName = "No usings, returns enum")] public void FluentControllerBuilder_FluentActionWithoutUsingsAndReturnsEnum() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(() => ExampleEnumWithoutUsings.ExampleEnumValue2), typeof(ParameterlessControllerReturnsEnum), null); } [Fact(DisplayName = "No usings, returns enum async")] public void FluentControllerBuilder_FluentActionWithoutUsingsAndReturnsEnumAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(async () => { await Task.Delay(1); return ExampleEnumWithoutUsings.ExampleEnumValue2; }), typeof(ParameterlessControllerReturnsEnumAsync), null); } [Fact(DisplayName = "No usings, returns object")] public void FluentControllerBuilder_FluentActionWithoutUsingsAndReturnsObject() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(() => new ExampleClassWithoutUsings { StringField = "Hello", IntField = 14, StringProperty = "World!" }), typeof(ParameterlessControllerReturnsObject), null); } [Fact(DisplayName = "No usings, returns object async")] public void FluentControllerBuilder_FluentActionWithoutUsingsAndReturnsObjectAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(async () => { await Task.Delay(1); return new ExampleClassWithoutUsings { StringField = "Hello", IntField = 14, StringProperty = "World!" }; }), typeof(ParameterlessControllerReturnsObjectAsync), null); } } } <|start_filename|>test/WebApps/MvcWithSwagger/Services/UserService.cs<|end_filename|> using System; using System.Collections.Generic; using System.Threading.Tasks; namespace MvcWithSwagger { public class UserItem { public int Id { get; set; } public string Name { get; set; } } public interface IUserService { IList<UserItem> List(); Task<IList<UserItem>> ListAsync(); EntityAddResultItem Add(UserItem user); Task<EntityAddResultItem> AddAsync(UserItem user); UserItem Get(int userId); Task<UserItem> GetAsync(int userId); EntityUpdateResultItem Update(int userId, UserItem user); Task<EntityUpdateResultItem> UpdateAsync(int userId, UserItem user); EntityRemoveResultItem Remove(int userId); Task<EntityRemoveResultItem> RemoveAsync(int userId); } public class UserService : IUserService { public IList<UserItem> List() { return new List<UserItem> { new UserItem { Id = 1, Name = "<NAME>" }, new UserItem { Id = 2, Name = "<NAME>" }, new UserItem { Id = 3, Name = "<NAME>" } }; } public async Task<IList<UserItem>> ListAsync() { await Task.Delay(200); return List(); } public EntityAddResultItem Add(UserItem user) { return new EntityAddResultItem { Id = DateTimeOffset.Now.Millisecond, Timestamp = DateTimeOffset.Now }; } public async Task<EntityAddResultItem> AddAsync(UserItem user) { await Task.Delay(200); return Add(user); } public UserItem Get(int userId) { return new UserItem { Id = 1, Name = "<NAME>" }; } public async Task<UserItem> GetAsync(int userId) { await Task.Delay(200); return Get(userId); } public EntityUpdateResultItem Update(int userId, UserItem user) { return new EntityUpdateResultItem { Id = userId, Timestamp = DateTimeOffset.Now }; } public async Task<EntityUpdateResultItem> UpdateAsync(int userId, UserItem user) { await Task.Delay(200); return Update(userId, user); } public EntityRemoveResultItem Remove(int userId) { return new EntityRemoveResultItem { Id = userId, Timestamp = DateTimeOffset.Now }; } public async Task<EntityRemoveResultItem> RemoveAsync(int userId) { await Task.Delay(200); return Remove(userId); } } public class EntityAddResultItem { public int Id { get; set; } public DateTimeOffset Timestamp { get; set; } } public class EntityRemoveResultItem { public int Id { get; set; } public DateTimeOffset Timestamp { get; set; } } public class EntityUpdateResultItem { public int Id { get; set; } public DateTimeOffset Timestamp { get; set; } } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/UsingDefinitions/UsingFormFilesDefinition.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions { public class FluentActionUsingFormFilesDefinition : FluentActionUsingFormFileDefinition { } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithAllowAnonymous.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithAllowAnonymous { [Fact(DisplayName = "1 AllowAnonymous, returns string")] public void FluentControllerBuilder_FluentActionWith1AllowAnonymousReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .AllowAnonymous() .To(() => "hello"), typeof(ControllerWith1AllowAnonymousReturnsString), null); } [Fact(DisplayName = "1 AllowAnonymous, returns ViewResult async")] public void FluentControllerBuilder_FluentActionWith1AllowAnonymousReturnsViewResultAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .AllowAnonymous() .To(async () => { await Task.Delay(1); return "hello"; }) .ToView("~/Path/To/ViewWithStringModel.cshtml"), typeof(ControllerWith1AllowAnonymousReturnsViewResultAsync), null); } } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/UsingDefinitions/UsingFormFileDefinition.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using System; namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions { public class FluentActionUsingFormFileDefinition : FluentActionUsingDefinition { public string Name { get; set; } public override bool IsMethodParameter => true; public override string MethodParameterName => Name; public override int GetHashCode() { return Tuple.Create(GetType(), Type, Name.ToLowerInvariant()).GetHashCode(); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderOrderTestsSize1.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderOrderTestsSize1 { private readonly TestLogger TestLogger; public BuilderOrderTestsSize1(ITestOutputHelper testOutputHelper) { TestLogger = new TestLogger(testOutputHelper); } [Fact(DisplayName = "OrderTest, Size 1: [Do] throws")] public void FluentControllerBuilder_FluentActionOrderTestDoThrows() { Assert.Throws<FluentActionValidationException>(() => { BuilderTestUtils.BuildAction( new FluentAction("/route/url", HttpMethod.Get) .Do(() => { /* woop woop */ }), TestLogger); }); } [Fact(DisplayName = "OrderTest, Size 1: [DoA] throws")] public void FluentControllerBuilder_FluentActionOrderTestDoAThrows() { Assert.Throws<FluentActionValidationException>(() => { BuilderTestUtils.BuildAction( new FluentAction("/route/url", HttpMethod.Get) .DoAsync(async () => { await Task.Delay(1); }), TestLogger); }); } [Fact(DisplayName = "OrderTest, Size 1: [To] returns string")] public void FluentControllerBuilder_FluentActionOrderTestToReturnsString() { var text = ""; BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(() => { text += "To"; return "Hello"; }), typeof(ControllerForOrderTestsReturnsString), null, TestLogger); Assert.Equal("To", text); } [Fact(DisplayName = "OrderTest, Size 1: [ToA] returns string")] public void FluentControllerBuilder_FluentActionOrderTestToAReturnsString() { var text = ""; BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(async () => { await Task.Delay(1); text += "ToA"; return "Hello"; }), typeof(ControllerForOrderTestsReturnsStringAsync), null, TestLogger); Assert.Equal("ToA", text); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithViewComponentResult.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithViewComponentResult { [Fact(DisplayName = "no usings, no To, returns ViewComponentResult")] public void FluentControllerBuilder_FluentActionNoUsingsNoToReturnsViewComponent() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .ToViewComponent("ViewComponentWithoutModel"), typeof(ControllerWithNoUsingsNoToReturnsViewComponent), null); } [Fact(DisplayName = "1 body (string), no To, returns ViewComponentResult")] public void FluentControllerBuilder_FluentAction1BodyNoToReturnsViewComponent() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingBody<string>() .ToViewComponent("ViewComponentWithStringModel"), typeof(ControllerPassing1BodyReturnsViewComponent), new object[] { "Text" }); } [Fact(DisplayName = "1 body (string), 1 route param (string), no To, returns ViewComponentResult")] public void FluentControllerBuilder_FluentAction1Body1RouteParamNoToReturnsViewComponent() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url/{unused}", HttpMethod.Get) .UsingBody<string>() .UsingRouteParameter<string>("unused") .ToViewComponent("ViewComponentWithStringModel"), typeof(ControllerWith1Body1RouteParamPassing1BodyReturnsViewComponent), new object[] { "Text", "Unused" }); } [Fact(DisplayName = "no usings, 1 To, returns ViewComponentResult")] public void FluentControllerBuilder_FluentActionNoUsings1ToReturnsViewComponent() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(() => "Hello World!") .ToViewComponent("ViewComponentWithStringModel"), typeof(ControllerWithNoUsingsXToReturnsViewComponent), null); } [Fact(DisplayName = "no usings, 3 To, returns ViewComponentResult")] public void FluentControllerBuilder_FluentActionNoUsings3ToReturnsViewComponent() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(() => "Hello") .UsingResult() .To(text => $"{text} World") .UsingResult() .To(text => $"{text}!") .ToViewComponent("ViewComponentWithStringModel"), typeof(ControllerWithNoUsingsXToReturnsViewComponent), null); } [Fact(DisplayName = "no usings, 1 Do, returns ViewComponentResult")] public void FluentControllerBuilder_FluentActionNoUsings1DoReturnsViewComponent() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .Do(() => { /* woop woop */ }) .ToViewComponent("ViewComponentWithoutModel"), typeof(ControllerWithNoUsingsXDoReturnsViewComponent), null); } [Fact(DisplayName = "no usings, 3 Do, returns ViewComponentResult")] public void FluentControllerBuilder_FluentActionNoUsings3DoReturnsViewComponent() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .Do(() => { /* woop woop */ }) .Do(() => { /* woop woop */ }) .Do(() => { /* woop woop */ }) .ToViewComponent("ViewComponentWithoutModel"), typeof(ControllerWithNoUsingsXDoReturnsViewComponent), null); } [Fact(DisplayName = "no usings, 1 Do, 1 To, returns ViewComponentResult")] public void FluentControllerBuilder_FluentActionNoUsings1Do1ToReturnsViewComponent() { var foo = "bar"; BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .Do(() => { foo = "baz"; }) .To(() => foo) .ToViewComponent("ViewComponentWithStringModel"), typeof(ControllerWithNoUsings1Do1ToReturnsViewComponent), null); } [Fact(DisplayName = "1 body (string), returns ViewComponentResult")] public void FluentControllerBuilder_FluentAction1BodyReturnsViewComponent() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingBody<string>() .To(name => $"Hello {name}!") .ToViewComponent("ViewComponentWithStringModel"), typeof(ControllerWith1BodyReturnsViewComponent), new object[] { "Bob" }); } [Fact(DisplayName = "1 body (string), 1 Do, 1 To, returns ViewComponentResult")] public void FluentControllerBuilder_FluentAction1Body1DoReturnsViewComponent() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .Do(() => { /* woop woop */ }) .UsingBody<string>() .To(name => $"Hello {name}!") .ToViewComponent("ViewComponentWithStringModel"), typeof(ControllerWith1BodyReturnsViewComponent), new object[] { "Bob" }); } [Fact(DisplayName = "1 body (string), 1 route param (string), returns ViewComponentResult")] public void FluentControllerBuilder_FluentAction1Body1RouteParamReturnsViewComponent() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/{lastName}", HttpMethod.Get) .UsingBody<string>() .UsingRouteParameter<string>("lastName") .To((firstName, lastName) => $"Hello {firstName} {lastName}!") .ToViewComponent("ViewComponentWithStringModel"), typeof(ControllerWith1Body1RouteParamReturnsViewComponent), new object[] { "Bob", "Bobsson" }); } [Fact(DisplayName = "1 body (string), 1 route param (string), 2 To, returns ViewComponentResult")] public void FluentControllerBuilder_FluentAction1Body1RouteParam2ToReturnsViewComponent() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/{lastName}", HttpMethod.Get) .UsingBody<string>() .To(firstName => $"Hello {firstName}") .UsingRouteParameter<string>("lastName") .To(lastName => $"{lastName}!") .ToViewComponent("ViewComponentWithStringModel"), typeof(ControllerWith1Body1RouteParam2ToReturnsViewComponent), new object[] { "Bob", "Bobsson" }); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/ControllersWithBody.cs<|end_filename|> using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { public class ControllerWithBodyReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction([FromBody]string name) { return $"Hello {name}!"; } } public class ControllerWithBodyReturnsStringAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<string> HandlerAction([FromBody]string name) { await Task.Delay(1); return $"Hello {name}!"; } } public class ControllerWithBodyAndDefaultValueReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction([FromBody]string name = "Hanzel") { return $"Hello {name}!"; } } public class ControllerWithBodyAndDefaultValueReturnsStringAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<string> HandlerAction([FromBody]string name = "Hanzel") { await Task.Delay(1); return $"Hello {name}!"; } } public class ControllerWithTwoIdenticalBodysReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction([FromBody]string name) { return $"Hello {name}! I said hello {name}!"; } } public class ControllerWithTwoIdenticalBodysReturnsStringAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<string> HandlerAction([FromBody]string name) { await Task.Delay(1); return $"Hello {name}! I said hello {name}!"; } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/ControllersWithViewResult.cs<|end_filename|> using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { public class ControllerWithNoUsingsNoToReturnsView : Controller { [HttpGet] [Route("/route/url")] public ViewResult HandlerAction() { return View("~/Path/To/ViewWithoutModel.cshtml"); } } public class ControllerWithNoUsingsXToReturnsView : Controller { [HttpGet] [Route("/route/url")] public ViewResult HandlerAction() { return View("~/Path/To/ViewWithStringModel.cshtml", "Hello World!"); } } public class ControllerWithNoUsingsXDoReturnsView : Controller { [HttpGet] [Route("/route/url")] public ViewResult HandlerAction() { return View("~/Path/To/ViewWithoutModel.cshtml"); } } public class ControllerWithNoUsings1Do1ToReturnsView : Controller { [HttpGet] [Route("/route/url")] public ViewResult HandlerAction() { return View("~/Path/To/ViewWithStringModel.cshtml", "baz"); } } public class ControllerWith1BodyReturnsView : Controller { [HttpGet] [Route("/route/url")] public ViewResult HandlerAction([FromBody]string name) { return View("~/Path/To/ViewWithStringModel.cshtml", $"Hello {name}!"); } } public class ControllerPassing1BodyReturnsView : Controller { [HttpGet] [Route("/route/url")] public ViewResult HandlerAction([FromBody]string model) { return View("~/Path/To/ViewWithStringModel.cshtml", model); } } public class ControllerWith1Body1RouteParamPassing1BodyReturnsView : Controller { [HttpGet] [Route("/route/url/{unused}")] public ViewResult HandlerAction([FromBody]string model, [FromRoute]string unused) { return View("~/Path/To/ViewWithStringModel.cshtml", model); } } public class ControllerWith1Body1RouteParamReturnsView : Controller { [HttpGet] [Route("/route/{lastName}")] public ViewResult HandlerAction([FromBody]string firstName, [FromRoute]string lastName) { return View("~/Path/To/ViewWithStringModel.cshtml", $"Hello {firstName} {lastName}!"); } } public class ControllerWith1Body1RouteParam2ToReturnsView : Controller { [HttpGet] [Route("/route/{lastName}")] public ViewResult HandlerAction([FromBody]string firstName, [FromRoute]string lastName) { return View("~/Path/To/ViewWithStringModel.cshtml", $"Hello {firstName} {lastName}!"); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/ControllersWithFormFiles.cs<|end_filename|> using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { public class ControllerWithFormFileReturnsString : Controller { [HttpPost] [Route("/route/url")] public string HandlerAction(IFormFile file) { return $"Got file with name {file.FileName}!"; } } public class ControllerWithFormFileReturnsStringAsync : Controller { [HttpPost] [Route("/route/url")] public async Task<string> HandlerAction(IFormFile file) { await Task.Delay(1); return $"Got file with name {file.FileName}!"; } } public class ControllerWith2FormFilesReturnsString : Controller { [HttpPost] [Route("/route/url")] public string HandlerAction(IEnumerable<IFormFile> files) { return $"Got {files.Count()} n.o. files!"; } } public class ControllerWith2FormFilesReturnsStringAsync : Controller { [HttpPost] [Route("/route/url")] public async Task<string> HandlerAction(IEnumerable<IFormFile> files) { await Task.Delay(1); return $"Got {files.Count()} n.o. files!"; } } } <|start_filename|>test/WebApps/SimpleMvc/Controllers/HelloWorldController.cs<|end_filename|> using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace SimpleMvc.Controllers { public class HelloWorldController : Controller { public string HelloProp => "Hello from hello prop!"; public string HelloWorld() { return "Hello World!"; } public async Task<string> HelloWorldAsync() { await Task.Delay(2000); return "Hello World Async!"; } } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/FluentActionValidationException.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using System; namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions { public class FluentActionValidationException : Exception { public FluentActionValidationException() : base() { } public FluentActionValidationException(string message) : base(message) { } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/DescriptionTests.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using System.Linq; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class DescriptionTests { [Fact(DisplayName = "Description inside single action")] public void FluentControllerBuilder_FluentActionWithDescription() { var action = new FluentAction("/route/url", HttpMethod.Get) .WithDescription("Custom Description") .To(() => "Hello"); Assert.Equal("Custom Description", action.Definition.Description); } [Fact(DisplayName = "Description inside single action async")] public void FluentControllerBuilder_FluentActionWithDescriptionAsync() { var action = new FluentAction("/route/url", HttpMethod.Get) .WithDescription("Custom Description") .To(async () => { await Task.Delay(1); return "Hello"; }); Assert.Equal("Custom Description", action.Definition.Description); } [Fact(DisplayName = "Description inside action collection config")] public void FluentControllerBuilder_FluentActionCollectionWithDescription() { var actionCollection = FluentActionCollection.DefineActions( actions => { actions.Configure(config => { config.SetDescription(action => action.Id); }); actions .RouteGet("/users", "ListUsers") .UsingService<IUserService>() .To(userService => userService.ListUsers()); actions .RoutePost("/users", "AddUser") .UsingService<IUserService>() .UsingBody<UserItem>() .To((userService, user) => userService.AddUser(user)); actions .RouteGet("/users/{userId}", "GetUser") .UsingService<IUserService>() .UsingRouteParameter<int>("userId") .To((userService, userId) => userService.GetUserById(userId)); actions .RoutePut("/users/{userId}", "UpdateUser") .UsingService<IUserService>() .UsingRouteParameter<int>("userId") .UsingBody<UserItem>() .To((userService, userId, user) => userService.UpdateUser(userId, user)); actions .RouteDelete("/users/{userId}", "RemoveUser") .UsingService<IUserService>() .UsingRouteParameter<int>("userId") .To((userService, userId) => userService.RemoveUser(userId)); } ); foreach (var action in actionCollection) { Assert.Equal(action.Definition.Id, action.Definition.Description); } } } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/FluentActionDefinition.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions { public enum FluentActionHandlerType { Unknown, Func, Action, View, PartialView, ViewComponent, Controller } public class FluentActionHandlerDefinition { public FluentActionHandlerType Type { get; set; } public IList<FluentActionUsingDefinition> Usings { get; set; } public Type ReturnType { get; set; } public bool Async { get; set; } public Delegate Delegate { get; set; } // Path to view or name of view component public string ViewTarget { get; set; } public Type ViewComponentType { get; set; } public LambdaExpression Expression { get; set; } public FluentActionHandlerDefinition() { Type = FluentActionHandlerType.Unknown; Usings = new List<FluentActionUsingDefinition>(); } } public class FluentActionDefinition { public readonly string RouteTemplate; public readonly HttpMethod HttpMethod; public readonly string Id; public string Title { get; internal set; } public string Description { get; internal set; } public string GroupName { get; internal set; } public bool? IgnoreApi { get; internal set; } public Type ParentType { get; internal set; } public IList<FluentActionHandlerDefinition> Handlers { get; internal set; } internal FluentActionHandlerDefinition HandlerDraft { get; set; } internal FluentActionHandlerDefinition ExistingOrNewHandlerDraft { get { if (HandlerDraft == null) { HandlerDraft = new FluentActionHandlerDefinition(); } return HandlerDraft; } } public IList<FluentActionCustomAttribute> CustomAttributes { get; internal set; } public IList<FluentActionCustomAttribute> CustomAttributesOnClass { get; internal set; } public Type ReturnType => Handlers?.LastOrDefault()?.ReturnType; public bool IsMapRoute => Handlers.Count == 1 && Handlers.First().Type == FluentActionHandlerType.Controller; public bool IsAsync => Handlers.Any(handler => handler.Async); public FluentActionDefinition(string routeTemplate, HttpMethod httpMethod, string id = null) { RouteTemplate = routeTemplate; HttpMethod = httpMethod; Id = id; Handlers = new List<FluentActionHandlerDefinition>(); CustomAttributes = new List<FluentActionCustomAttribute>(); CustomAttributesOnClass = new List<FluentActionCustomAttribute>(); } public override string ToString() { return $"[{HttpMethod}]{RouteTemplate ?? "?"}"; } public void CommitHandlerDraft() { if (HandlerDraft == null) { // Users should not be able to get this throw new Exception("Tried to add an empty fluent action handler (no draft exists)."); } Handlers.Add(HandlerDraft); HandlerDraft = null; } } public class FluentActionBase { public readonly FluentActionDefinition Definition; public string RouteTemplate => Definition.RouteTemplate; public HttpMethod HttpMethod => Definition.HttpMethod; public string Id => Definition.Id; public FluentActionBase(HttpMethod httpMethod, string routeTemplate, string id = null) { Definition = new FluentActionDefinition(routeTemplate, httpMethod, id); } public FluentActionBase(string routeTemplate, HttpMethod httpMethod, string id = null) : this(httpMethod, routeTemplate, id) { } public FluentActionBase(FluentActionDefinition actionDefinition) { Definition = actionDefinition; } public override string ToString() { return Definition.ToString(); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/ControllersWithViewComponentResult.cs<|end_filename|> using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { public class ControllerWithNoUsingsNoToReturnsViewComponent : Controller { [HttpGet] [Route("/route/url")] public ViewComponentResult HandlerAction() { return ViewComponent("ViewComponentWithoutModel"); } } public class ControllerPassing1BodyReturnsViewComponent : Controller { [HttpGet] [Route("/route/url")] public ViewComponentResult HandlerAction([FromBody]string model) { return ViewComponent("ViewComponentWithStringModel", model); } } public class ControllerWith1Body1RouteParamPassing1BodyReturnsViewComponent : Controller { [HttpGet] [Route("/route/url/{unused}")] public ViewComponentResult HandlerAction([FromBody]string model, [FromRoute]string unused) { return ViewComponent("ViewComponentWithStringModel", model); } } public class ControllerWithNoUsingsXToReturnsViewComponent : Controller { [HttpGet] [Route("/route/url")] public ViewComponentResult HandlerAction() { return ViewComponent("ViewComponentWithStringModel", "Hello World!"); } } public class ControllerWithNoUsingsXDoReturnsViewComponent : Controller { [HttpGet] [Route("/route/url")] public ViewComponentResult HandlerAction() { return ViewComponent("ViewComponentWithoutModel"); } } public class ControllerWithNoUsings1Do1ToReturnsViewComponent : Controller { [HttpGet] [Route("/route/url")] public ViewComponentResult HandlerAction() { return ViewComponent("ViewComponentWithStringModel", "baz"); } } public class ControllerWith1BodyReturnsViewComponent : Controller { [HttpGet] [Route("/route/url")] public ViewComponentResult HandlerAction([FromBody]string name) { return ViewComponent("ViewComponentWithStringModel", $"Hello {name}!"); } } public class ControllerWith1Body1RouteParamReturnsViewComponent : Controller { [HttpGet] [Route("/route/{lastName}")] public ViewComponentResult HandlerAction([FromBody]string firstName, [FromRoute]string lastName) { return ViewComponent("ViewComponentWithStringModel", $"Hello {firstName} {lastName}!"); } } public class ControllerWith1Body1RouteParam2ToReturnsViewComponent : Controller { [HttpGet] [Route("/route/{lastName}")] public ViewComponentResult HandlerAction([FromBody]string firstName, [FromRoute]string lastName) { return ViewComponent("ViewComponentWithStringModel", $"Hello {firstName} {lastName}!"); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithHttpContext.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithHttpContext { [Fact(DisplayName = "1 HttpContext, returns string")] public void FluentControllerBuilder_FluentActionWithHttpContextReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingHttpContext() .To(httpContext => { if (httpContext == null) { throw new Exception("HttpContext is null inside fluent action delegate."); } return "Hello"; }), typeof(ControllerWithHttpContextReturnsString), null); } [Fact(DisplayName = "1 HttpContext, returns string async")] public void FluentControllerBuilder_FluentActionWithHttpContextReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .DoAsync(async () => { await Task.Delay(1); }) .UsingHttpContext() .To(async httpContext => { await Task.Delay(1); if (httpContext == null) { throw new Exception("HttpContext is null inside fluent action delegate."); } return "Hello"; }), typeof(ControllerWithHttpContextReturnsStringAsync), null); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/ControllersForReadMeExamples.cs<|end_filename|> using Microsoft.AspNetCore.Mvc; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { public class ControllerForReadMeExample1 : Controller { [HttpGet] [Route("/")] public string HandlerAction() { return $"Hello World!"; } } public class ControllerForReadMeExample2 : Controller { [HttpGet] [Route("/users/{userId}")] public ViewResult HandlerAction([FromServices]IUserService userService, [FromRoute]int userId) { var user = userService.GetUserById(userId); return View("~/Views/Users/DisplayUser.cshtml", user); } } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/TypeExtensions.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using System; namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions { public static class TypeExtensions { public static bool IsAnonymous(this Type type) { // This is not so great return type.Namespace == null; } } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/FluentActionControllerFeatureProvider.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using Microsoft.AspNetCore.Mvc.ApplicationParts; using Microsoft.AspNetCore.Mvc.Controllers; using System.Collections.Generic; namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions { public class FluentActionControllerFeatureProvider : IApplicationFeatureProvider<ControllerFeature> { public FluentActionControllerFeatureProviderContext Context { get; set; } public FluentActionControllerFeatureProvider(FluentActionControllerFeatureProviderContext context) { Context = context; } public void PopulateFeature(IEnumerable<ApplicationPart> parts, ControllerFeature feature) { if (Context.ControllerDefinitions == null) { return; } foreach (var controllerDefinition in Context.ControllerDefinitions) { if (!feature.Controllers.Contains(controllerDefinition.TypeInfo)) { feature.Controllers.Add(controllerDefinition.TypeInfo); } } } } public class FluentActionControllerFeatureProviderContext { public IEnumerable<FluentActionControllerDefinition> ControllerDefinitions { get; set; } } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/Builder/ControllerMethodBuilder.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core.Builder { public abstract class ControllerMethodBuilder { public TypeBuilder TypeBuilder { get; internal set; } public MethodBuilder MethodBuilder { get; internal set; } public List<TypeBuilder> NestedTypes { get; internal set; } public abstract void Build(); public void SetHttpMethodAttribute(HttpMethod httpMethod) { var attributeConstructorInfo = GetHttpMethodAttribute(httpMethod) .GetConstructor(new Type[0]); var attributeBuilder = new CustomAttributeBuilder(attributeConstructorInfo, new Type[0]); MethodBuilder.SetCustomAttribute(attributeBuilder); } public void SetRouteAttribute(string routeTemplate) { var attributeConstructorInfo = typeof(RouteAttribute) .GetConstructor(new Type[] { typeof(string) }); var attributeBuilder = new CustomAttributeBuilder(attributeConstructorInfo, new[] { routeTemplate }); MethodBuilder.SetCustomAttribute(attributeBuilder); } public void SetCustomAttribute(FluentActionCustomAttribute customAttribute) { SetCustomAttribute( customAttribute.Constructor, customAttribute.ConstructorArgs, customAttribute.NamedProperties, customAttribute.PropertyValues, customAttribute.NamedFields, customAttribute.FieldValues ); } public void SetCustomAttribute( ConstructorInfo constructor, object[] constructorArgs, PropertyInfo[] namedProperties, object[] propertyValues, FieldInfo[] namedFields, object[] fieldValues) { var attributeBuilder = new CustomAttributeBuilder( constructor, constructorArgs, namedProperties, propertyValues, namedFields, fieldValues ); MethodBuilder.SetCustomAttribute(attributeBuilder); } private static Type GetHttpMethodAttribute(HttpMethod httpMethod) { switch (httpMethod) { case HttpMethod.Delete: return typeof(HttpDeleteAttribute); case HttpMethod.Get: return typeof(HttpGetAttribute); case HttpMethod.Head: return typeof(HttpHeadAttribute); case HttpMethod.Options: return typeof(HttpOptionsAttribute); case HttpMethod.Patch: return typeof(HttpPatchAttribute); case HttpMethod.Post: return typeof(HttpPostAttribute); case HttpMethod.Put: return typeof(HttpPutAttribute); } throw new Exception($"Could not get corresponding attribute of {nameof(HttpMethod)} {httpMethod}."); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithForm.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithForm { [Fact(DisplayName = "1 form (string), returns string")] public void FluentControllerBuilder_FluentActionUsingFormReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingForm<string>() .To(name => $"Hello {name}!"), typeof(ControllerWithFormReturnsString), new object[] { "Charlie" }); } [Fact(DisplayName = "1 form (string), returns string async")] public void FluentControllerBuilder_FluentActionUsingFormReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingForm<string>() .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }), typeof(ControllerWithFormReturnsStringAsync), new object[] { "Charlie" }); } [Fact(DisplayName = "1 form (string) with used default value, returns string")] public void FluentControllerBuilder_FluentActionUsingFormWithUsedDefaultValueReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingForm<string>("Hanzel") .To(name => $"Hello {name}!"), typeof(ControllerWithFormAndDefaultValueReturnsString), new object[] { Type.Missing }); } [Fact(DisplayName = "1 form (string) with used default value, returns string async")] public void FluentControllerBuilder_FluentActionUsingFormWithUsedDefaultValueReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingForm<string>("Hanzel") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }), typeof(ControllerWithFormAndDefaultValueReturnsStringAsync), new object[] { Type.Missing }); } [Fact(DisplayName = "1 form (string) with unused default value, returns string")] public void FluentControllerBuilder_FluentActionUsingFormWithUnusedDefaultValueReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingForm<string>("Hanzel") .To(name => $"Hello {name}!"), typeof(ControllerWithFormAndDefaultValueReturnsString), new object[] { "Charlie" }); } [Fact(DisplayName = "1 form (string) with unused default value, returns string async")] public void FluentControllerBuilder_FluentActionUsingFormWithUnusedDefaultValueReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingForm<string>("Hanzel") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }), typeof(ControllerWithFormAndDefaultValueReturnsStringAsync), new object[] { "Charlie" }); } [Fact(DisplayName = "2 form (string, identical), returns string")] public void FluentControllerBuilder_FluentActionUsingTwoIdenticalFormsReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingForm<string>() .UsingForm<string>() .To((name1, name2) => $"Hello {name1}! I said hello {name2}!"), typeof(ControllerWithTwoIdenticalFormsReturnsString), new object[] { "Charlie" }); } [Fact(DisplayName = "2 form (string, identical), returns string async")] public void FluentControllerBuilder_FluentActionUsingTwoIdenticalFormsReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingForm<string>() .UsingForm<string>() .To(async (name1, name2) => { await Task.Delay(1); return $"Hello {name1}! I said hello {name2}!"; }), typeof(ControllerWithTwoIdenticalFormsReturnsStringAsync), new object[] { "Charlie" }); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/ControllersWithServices.cs<|end_filename|> using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { public class ControllerWithStringService : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction([FromServices]IStringTestService stringTestService) { return stringTestService.GetTestString() + "FromAFluentAction"; } } public class ControllerWithStringServiceAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<string> HandlerAction([FromServices]IStringTestService stringTestService) { return await stringTestService.GetTestStringAsync() + "FromAFluentAction"; } } public class ControllerWithUserService : Controller { [HttpGet] [Route("/route/url")] public IList<UserItem> HandlerAction([FromServices]IUserService userService) { return userService.ListUsers(); } } public class ControllerWithUserServiceAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<IList<UserItem>> HandlerAction([FromServices]IUserService userService) { return await userService.ListUsersAsync(); } } public class ControllerWithMultipleServicesOfSameInterface : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction([FromServices]IStringTestService stringTestService1, [FromServices]IStringTestService stringTestService2) { return stringTestService1.GetTestString() + "And" + stringTestService2.GetTestString(); } } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions/MvcStartupExtensions.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using System; using System.Linq; namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions { public static class ApplicationBuilderExtensions { public static IApplicationBuilder UseFluentActions( this IApplicationBuilder app, Action<FluentActionCollection> addFluentActions) { if (addFluentActions == null) { throw new ArgumentNullException(nameof(addFluentActions)); } var fluentActions = FluentActionCollection.DefineActions(addFluentActions); return app.UseFluentActions(fluentActions); } public static IApplicationBuilder UseFluentActions( this IApplicationBuilder app, FluentActionCollection fluentActions) { if (fluentActions == null) { throw new ArgumentNullException(nameof(fluentActions)); } var controllerDefinitionBuilder = new FluentActionControllerDefinitionBuilder(); var controllerDefinitions = fluentActions .Select(fluentAction => controllerDefinitionBuilder.Build(fluentAction)) .ToList(); if (!controllerDefinitions.Any()) { return app; } var context = (FluentActionControllerFeatureProviderContext)app .ApplicationServices .GetService(typeof(FluentActionControllerFeatureProviderContext)); if (context == null) { throw new Exception("Could not find a feature provider for fluent actions, did you remember to call app.AddMvc().AddFluentActions()?"); } if (context.ControllerDefinitions == null) { context.ControllerDefinitions = controllerDefinitions; } else { context.ControllerDefinitions = context.ControllerDefinitions.Concat(controllerDefinitions); } app.UseEndpoints(routes => { foreach (var controllerDefinition in controllerDefinitions .Where(controllerDefinition => controllerDefinition.FluentAction.Definition.IsMapRoute)) { routes.MapControllerRoute( controllerDefinition.Id, controllerDefinition.RouteTemplate.WithoutLeading("/"), new { controller = controllerDefinition.Name.WithoutTrailing("Controller"), action = controllerDefinition.ActionName }); } }); return app; } } public static class IMvcBuilderExtensions { public static IMvcBuilder AddFluentActions(this IMvcBuilder builder) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } // Stop if our feature provider has already been added (AddFluentActions has already been called) if (builder.Services.Any(s => s.ServiceType == typeof(FluentActionControllerFeatureProviderContext))) { return builder; } var context = new FluentActionControllerFeatureProviderContext(); builder.Services.TryAddSingleton(context); var fluentActionControllerFeatureProvider = new FluentActionControllerFeatureProvider(context); return builder.ConfigureApplicationPartManager(manager => { manager.FeatureProviders.Add(fluentActionControllerFeatureProvider); }); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/ControllersWithOrderTests.cs<|end_filename|> using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { public class ControllerForOrderTestsReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction() { return "Hello"; } } public class ControllerForOrderTestsReturnsStringAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<string> HandlerAction() { await Task.Delay(1); return "Hello"; } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/ControllersWithModelState.cs<|end_filename|> using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { public class ControllerWithModelStateReturnsString : Controller { [HttpPost] [Route("/route/url")] public string HandlerAction() { return $"Hello World!"; } } public class ControllerWithModelStateReturnsStringAsync : Controller { [HttpPost] [Route("/route/url")] public async Task<string> HandlerAction() { await Task.Delay(1); return $"Hello World!"; } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Config/Append/NestedAppendsReturnsHashContainer.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using Microsoft.AspNetCore.Mvc; using System; using System.Linq; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class NestedAppendsReturnsHashContainer { [Fact(DisplayName = "2 Append in nested collection config returns hash container")] public void FluentActionCollection_DefineActions_Config_NestedAppend_ReturnsHashContainer() { var innerActionCollection = FluentActionCollection.DefineActions( actions => { actions.Configure(config => { config.Append(action => action .UsingResult() .To(result => new StringContainer { Value = result.ToString() }) ); }); actions .RouteGet("/hello") .UsingQueryStringParameter<string>("name") .To(name => $"Hello {name}!"); actions .RouteGet("/helloAsync") .UsingQueryStringParameter<string>("name") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }); actions .RouteGet("/helloAsyncWithDo") .Do(() => { /* Doing nothing */ }) .UsingQueryStringParameter<string>("name") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }); actions .RouteGet("/helloAsyncWithAsyncDo") .Do(async () => { await Task.Delay(1); }) .UsingQueryStringParameter<string>("name") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }); actions .RouteGet("/hi/{name}") .UsingRouteParameter<string>("name") .To(name => $"Hi {name}!") .UsingResult() .To(greeting => $"{greeting} How are you?"); actions .RouteGet("/userCount") .UsingService<IUserService>() .To(userService => userService.ListUsers().Count()); actions .RouteGet("/toView") .ToView("~/path/to/view"); } ); var actionCollection = FluentActionCollection.DefineActions( actions => { actions.Configure(config => { config.Append(action => action .WithCustomAttribute<NestedAppendCustomAttribute>(new Type[] { typeof(string) }, new object[] { "AttrValue" }) .UsingResult() .UsingQueryStringParameter<string>("additional") .To((result, additional) => new HashContainer { Value = result.GetHashCode(), Additional = additional }) ); }); actions.Add(innerActionCollection); } ); foreach (var action in actionCollection) { switch (action.RouteTemplate) { case "/hello": BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( action, typeof(NestedAppend_HelloController), new object[] { "Bob", "Extra" }); break; case "/helloAsync": BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( action, typeof(NestedAppend_HelloAsyncController), new object[] { "Bob", "Extra" }); break; case "/helloAsyncWithDo": BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( action, typeof(NestedAppend_HelloAsyncWithDoController), new object[] { "Bob", "Extra" }); break; case "/helloAsyncWithAsyncDo": BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( action, typeof(NestedAppend_HelloAsyncWithAsyncDoController), new object[] { "Bob", "Extra" }); break; case "/hi/{name}": BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( action, typeof(NestedAppend_HiController), new object[] { "Bob", "Extra" }); break; case "/userCount": BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( action, typeof(NestedAppend_UserCountController), new object[] { new UserService(), "Extra" }); break; case "/toView": BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( action, typeof(NestedAppend_ToViewController), new object[] { "Extra" }); break; default: throw new Exception($"Could not find controller type to compare with for action {action}"); } } } } public class HashContainer { public int Value { get; set; } public string Additional { get; set; } public override bool Equals(object obj) { return obj is HashContainer && obj != null && ((HashContainer)obj).Value == Value && ((HashContainer)obj).Additional == Additional; } public override int GetHashCode() { return Value * 17 + (Additional ?? "").GetHashCode(); } } public class NestedAppendCustomAttribute : Attribute { public string Value { get; set; } public NestedAppendCustomAttribute(string value = null) { Value = value; } } public class NestedAppend_HelloController : Controller { [HttpGet] [Route("/hello")] [NestedAppendCustom("AttrValue")] public HashContainer HandlerAction([FromQuery]string name, [FromQuery]string additional) { return new HashContainer { Value = $"Hello {name}!".GetHashCode(), Additional = additional }; } } public class NestedAppend_HelloAsyncController : Controller { [HttpGet] [Route("/helloAsync")] [NestedAppendCustom("AttrValue")] public async Task<HashContainer> HandlerAction([FromQuery]string name, [FromQuery]string additional) { await Task.Delay(1); return new HashContainer { Value = $"Hello {name}!".GetHashCode(), Additional = additional }; } } public class NestedAppend_HelloAsyncWithDoController : Controller { [HttpGet] [Route("/helloAsyncWithDo")] [NestedAppendCustom("AttrValue")] public async Task<HashContainer> HandlerAction([FromQuery]string name, [FromQuery]string additional) { await Task.Delay(1); return new HashContainer { Value = $"Hello {name}!".GetHashCode(), Additional = additional }; } } public class NestedAppend_HelloAsyncWithAsyncDoController : Controller { [HttpGet] [Route("/helloAsyncWithAsyncDo")] [NestedAppendCustom("AttrValue")] public async Task<HashContainer> HandlerAction([FromQuery]string name, [FromQuery]string additional) { await Task.Delay(1); return new HashContainer { Value = $"Hello {name}!".GetHashCode(), Additional = additional }; } } public class NestedAppend_HiController : Controller { [HttpGet] [Route("/hi/{name}")] [NestedAppendCustom("AttrValue")] public HashContainer HandlerAction([FromRoute]string name, [FromQuery]string additional) { return new HashContainer { Value = $"Hi {name}! How are you?".GetHashCode(), Additional = additional }; } } public class NestedAppend_UserCountController : Controller { [HttpGet] [Route("/userCount")] [NestedAppendCustom("AttrValue")] public HashContainer HandlerAction([FromServices]IUserService userService, [FromQuery]string additional) { var userCount = userService.ListUsers().Count; return new HashContainer { Value = userCount.ToString().GetHashCode(), Additional = additional }; } } public class NestedAppend_ToViewController : Controller { [HttpGet] [Route("/toView")] [NestedAppendCustom("AttrValue")] public HashContainer HandlerAction([FromQuery]string additional) { var view = View("~/path/to/view"); return new HashContainer { Value = view.ToString().GetHashCode(), Additional = additional }; } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/ControllersWithPartialViewResultAsync.cs<|end_filename|> using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { public class ControllerWithNoUsingsXToReturnsPartialViewAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<PartialViewResult> HandlerAction() { await Task.Delay(1); return PartialView("~/Path/To/PartialViewWithStringModel.cshtml", "Hello World!"); } } public class ControllerWithNoUsingsXDoReturnsPartialViewAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<PartialViewResult> HandlerAction() { await Task.Delay(1); return PartialView("~/Path/To/PartialViewWithoutModel.cshtml"); } } public class ControllerWithNoUsings1Do1ToReturnsPartialViewAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<PartialViewResult> HandlerAction() { await Task.Delay(1); return PartialView("~/Path/To/PartialViewWithStringModel.cshtml", "baz"); } } public class ControllerWith1BodyReturnsPartialViewAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<PartialViewResult> HandlerAction([FromBody]string name) { await Task.Delay(1); return PartialView("~/Path/To/PartialViewWithStringModel.cshtml", $"Hello {name}!"); } } public class ControllerWith1Body1RouteParamReturnsPartialViewAsync : Controller { [HttpGet] [Route("/route/{lastName}")] public async Task<PartialViewResult> HandlerAction([FromBody]string firstName, [FromRoute]string lastName) { await Task.Delay(1); return PartialView("~/Path/To/PartialViewWithStringModel.cshtml", $"Hello {firstName} {lastName}!"); } } public class ControllerWith1Body1RouteParam2ToReturnsPartialViewAsync : Controller { [HttpGet] [Route("/route/{lastName}")] public async Task<PartialViewResult> HandlerAction([FromBody]string firstName, [FromRoute]string lastName) { await Task.Delay(1); return PartialView("~/Path/To/PartialViewWithStringModel.cshtml", $"Hello {firstName} {lastName}!"); } } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/UsingDefinitions/UsingParentDefinition.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions { public class FluentActionUsingParentDefinition : FluentActionUsingDefinition { } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithViewResult.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithViewResult { [Fact(DisplayName = "no usings, no To, returns ViewResult")] public void FluentControllerBuilder_FluentActionNoUsingsNoToReturnsView() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .ToView("~/Path/To/ViewWithoutModel.cshtml"), typeof(ControllerWithNoUsingsNoToReturnsView), null); } [Fact(DisplayName = "1 body (string), no To, returns ViewResult")] public void FluentControllerBuilder_FluentAction1BodyNoToReturnsView() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingBody<string>() .ToView("~/Path/To/ViewWithStringModel.cshtml"), typeof(ControllerPassing1BodyReturnsView), new object[] { "Text" }); } [Fact(DisplayName = "1 body (string), 1 route param (string), no To, returns ViewResult")] public void FluentControllerBuilder_FluentAction1Body1RouteParamNoToReturnsView() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url/{unused}", HttpMethod.Get) .UsingBody<string>() .UsingRouteParameter<string>("unused") .ToView("~/Path/To/ViewWithStringModel.cshtml"), typeof(ControllerWith1Body1RouteParamPassing1BodyReturnsView), new object[] { "Text", "Unused" }); } [Fact(DisplayName = "no usings, 1 To, returns ViewResult")] public void FluentControllerBuilder_FluentActionNoUsings1ToReturnsView() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(() => "Hello World!") .ToView("~/Path/To/ViewWithStringModel.cshtml"), typeof(ControllerWithNoUsingsXToReturnsView), null); } [Fact(DisplayName = "no usings, 3 To, returns ViewResult")] public void FluentControllerBuilder_FluentActionNoUsings3ToReturnsView() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(() => "Hello") .UsingResult() .To(text => $"{text} World") .UsingResult() .To(text => $"{text}!") .ToView("~/Path/To/ViewWithStringModel.cshtml"), typeof(ControllerWithNoUsingsXToReturnsView), null); } [Fact(DisplayName = "no usings, 1 Do, returns ViewResult")] public void FluentControllerBuilder_FluentActionNoUsings1DoReturnsView() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .Do(() => { /* woop woop */ }) .ToView("~/Path/To/ViewWithoutModel.cshtml"), typeof(ControllerWithNoUsingsXDoReturnsView), null); } [Fact(DisplayName = "no usings, 3 Do, returns ViewResult")] public void FluentControllerBuilder_FluentActionNoUsings3DoReturnsView() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .Do(() => { /* woop woop */ }) .Do(() => { /* woop woop */ }) .Do(() => { /* woop woop */ }) .ToView("~/Path/To/ViewWithoutModel.cshtml"), typeof(ControllerWithNoUsingsXDoReturnsView), null); } [Fact(DisplayName = "no usings, 1 Do, 1 To, returns ViewResult")] public void FluentControllerBuilder_FluentActionNoUsings1Do1ToReturnsView() { var foo = "bar"; BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .Do(() => { foo = "baz"; }) .To(() => foo) .ToView("~/Path/To/ViewWithStringModel.cshtml"), typeof(ControllerWithNoUsings1Do1ToReturnsView), null); } [Fact(DisplayName = "1 body (string), returns ViewResult")] public void FluentControllerBuilder_FluentAction1BodyReturnsView() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingBody<string>() .To(name => $"Hello {name}!") .ToView("~/Path/To/ViewWithStringModel.cshtml"), typeof(ControllerWith1BodyReturnsView), new object[] { "Bob" }); } [Fact(DisplayName = "1 body (string), 1 Do, 1 To, returns ViewResult")] public void FluentControllerBuilder_FluentAction1Body1DoReturnsView() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .Do(() => { /* woop woop */ }) .UsingBody<string>() .To(name => $"Hello {name}!") .ToView("~/Path/To/ViewWithStringModel.cshtml"), typeof(ControllerWith1BodyReturnsView), new object[] { "Bob" }); } [Fact(DisplayName = "1 body (string), 1 route param (string), returns ViewResult")] public void FluentControllerBuilder_FluentAction1Body1RouteParamReturnsView() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/{lastName}", HttpMethod.Get) .UsingBody<string>() .UsingRouteParameter<string>("lastName") .To((firstName, lastName) => $"Hello {firstName} {lastName}!") .ToView("~/Path/To/ViewWithStringModel.cshtml"), typeof(ControllerWith1Body1RouteParamReturnsView), new object[] { "Bob", "Bobsson" }); } [Fact(DisplayName = "1 body (string), 1 route param (string), 2 To, returns ViewResult")] public void FluentControllerBuilder_FluentAction1Body1RouteParam2ToReturnsView() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/{lastName}", HttpMethod.Get) .UsingBody<string>() .To(firstName => $"Hello {firstName}") .UsingRouteParameter<string>("lastName") .To(lastName => $"{lastName}!") .ToView("~/Path/To/ViewWithStringModel.cshtml"), typeof(ControllerWith1Body1RouteParam2ToReturnsView), new object[] { "Bob", "Bobsson" }); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithGroupBy.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithGroupByAsync { [Fact(DisplayName = "GroupBy inside single action (type comparison)")] public void FluentControllerBuilder_FluentActionWithGroupBy() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .GroupBy("CustomGroupName") .To(() => "Hello"), typeof(ControllerWithGroupNameOnlyApiExplorerSettingsAttribute), new object[0]); } [Fact(DisplayName = "IgnoreApi inside single action (type comparison)")] public void FluentControllerBuilder_FluentActionWithIgnoreApi() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .IgnoreApi() .To(() => "Hello"), typeof(ControllerWithIgnoreApiOnlyApiExplorerSettingsAttribute), new object[0]); } [Fact(DisplayName = "GroupBy + IgnoreApi inside single action (type comparison)")] public void FluentControllerBuilder_FluentActionWithGroupByAndIgnoreApi() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .GroupBy("CustomGroupName") .IgnoreApi() .To(() => "Hello"), typeof(ControllerWithApiExplorerSettingsAttribute), new object[0]); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithAuthorizeInConfig.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System.Linq; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithAuthorizeInConfig { [Fact(DisplayName = "Authorize (empty) in config")] public void FluentControllerBuilder_FluentActionWith1AuthorizeInConfig() { var actionCollection = FluentActionCollection.DefineActions( actions => { actions.Configure(config => { config.Authorize(); }); actions .RouteGet("/users", "ListUsers") .WithCustomAttribute<MySecondCustomAttribute>() .UsingService<IUserService>() .To(userService => userService.ListUsers()); actions .RoutePost("/users", "AddUser") .UsingService<IUserService>() .UsingBody<UserItem>() .To((userService, user) => userService.AddUser(user)); actions .RouteGet("/users/{userId}", "GetUser") .UsingService<IUserService>() .UsingRouteParameter<int>("userId") .To((userService, userId) => userService.GetUserById(userId)); actions .RoutePut("/users/{userId}", "UpdateUser") .UsingService<IUserService>() .UsingRouteParameter<int>("userId") .UsingBody<UserItem>() .To((userService, userId, user) => userService.UpdateUser(userId, user)); actions .RouteDelete("/users/{userId}", "RemoveUser") .UsingService<IUserService>() .UsingRouteParameter<int>("userId") .To((userService, userId) => userService.RemoveUser(userId)); } ); foreach (var action in actionCollection.Where(action => action.Id != "ListUsers")) { Assert.Equal(1, action.Definition.CustomAttributes.Count); } Assert.Equal(2, actionCollection.Single(action => action.Id == "ListUsers").Definition.CustomAttributes.Count); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithRequest.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithRequest { [Fact(DisplayName = "1 Request, returns string")] public void FluentControllerBuilder_FluentActionWithRequestReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingRequest() .To(request => { if (request == null) { throw new Exception("Request is null inside fluent action delegate."); } return "Hello"; }), typeof(ControllerWithRequestReturnsString), null); } [Fact(DisplayName = "1 Request, returns string async")] public void FluentControllerBuilder_FluentActionWithRequestReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .DoAsync(async () => { await Task.Delay(1); }) .UsingRequest() .To(async request => { await Task.Delay(1); if (request == null) { throw new Exception("Request is null inside fluent action delegate."); } return "Hello"; }), typeof(ControllerWithRequestReturnsStringAsync), null); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/GroupByTests.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class GroupByTests { [Fact(DisplayName = "GroupBy inside single action")] public void FluentControllerBuilder_FluentActionWithGroupBy() { var action = new FluentAction("/route/url", HttpMethod.Get) .GroupBy("CustomGroupName") .To(() => "Hello"); Assert.Equal("CustomGroupName", action.Definition.GroupName); } [Fact(DisplayName = "GroupBy inside single action async")] public void FluentControllerBuilder_FluentActionWithGroupByAsync() { var action = new FluentAction("/route/url", HttpMethod.Get) .GroupBy("CustomGroupName") .To(async () => { await Task.Delay(1); return "Hello"; }); Assert.Equal("CustomGroupName", action.Definition.GroupName); } [Fact(DisplayName = "GroupBy inside action collection config")] public void FluentControllerBuilder_FluentActionCollectionWithGroupBy() { var actionCollection = FluentActionCollection.DefineActions( actions => { actions.Configure(config => { config.GroupBy("CustomGroupName"); }); actions .RouteGet("/users", "ListUsers") .UsingService<IUserService>() .To(userService => userService.ListUsers()); actions .RoutePost("/users", "AddUser") .UsingService<IUserService>() .UsingBody<UserItem>() .To((userService, user) => userService.AddUser(user)); actions .RouteGet("/users/{userId}", "GetUser") .UsingService<IUserService>() .UsingRouteParameter<int>("userId") .To((userService, userId) => userService.GetUserById(userId)); actions .RoutePut("/users/{userId}", "UpdateUser") .UsingService<IUserService>() .UsingRouteParameter<int>("userId") .UsingBody<UserItem>() .To((userService, userId, user) => userService.UpdateUser(userId, user)); actions .RouteDelete("/users/{userId}", "RemoveUser") .UsingService<IUserService>() .UsingRouteParameter<int>("userId") .To((userService, userId) => userService.RemoveUser(userId)); } ); Assert.Equal("CustomGroupName", actionCollection.Config.GroupName); foreach (var action in actionCollection) { Assert.Equal("CustomGroupName", action.Definition.GroupName); } } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithViewBag.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithViewBag { [Fact(DisplayName = "1 ViewBag, returns string")] public void FluentControllerBuilder_FluentActionWithViewBagReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingViewBag() .To(viewBag => { viewBag.Foo = "bar"; return (string)viewBag.Foo; }), typeof(ControllerWithViewBagReturnsString), null); } [Fact(DisplayName = "1 ViewBag, returns string async")] public void FluentControllerBuilder_FluentActionWithViewBagReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingViewBag() .To(async viewBag => { await Task.Delay(1); viewBag.Foo = "bar"; return (string)viewBag.Foo; }), typeof(ControllerWithViewBagReturnsStringAsync), null); } } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/UsingDefinitions/UsingFormDefinition.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using Microsoft.AspNetCore.Mvc; using System; using System.Reflection; using System.Reflection.Emit; namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions { public class FluentActionUsingFormDefinition : FluentActionUsingDefinition { public override bool IsMethodParameter => true; public override ParameterBuilder DefineMethodParameter( MethodBuilder methodBuilder, FluentActionDefinition actionDefinition, FluentActionUsingDefinition usingDefinition, int parameterIndex) { var parameterBuilder = base.DefineMethodParameter(methodBuilder, actionDefinition, usingDefinition, parameterIndex); var attributeBuilder = new CustomAttributeBuilder(typeof(FromFormAttribute) .GetConstructor(new Type[0]), new Type[0]); parameterBuilder.SetCustomAttribute(attributeBuilder); return parameterBuilder; } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/ControllersWithAllowAnonymous.cs<|end_filename|> using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { public class ControllerWith1AllowAnonymousReturnsString : Controller { [HttpGet] [Route("/route/url")] [AllowAnonymous] public string HandlerAction() { return "hello"; } } public class ControllerWith1AllowAnonymousReturnsViewResultAsync : Controller { [HttpGet] [Route("/route/url")] [AllowAnonymous] public async Task<ViewResult> HandlerAction() { await Task.Delay(1); return View("~/Path/To/ViewWithStringModel.cshtml", "hello"); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/ControllersWithViewComponentTypeResult.cs<|end_filename|> using Microsoft.AspNetCore.Mvc; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { public class ViewComponentWithoutModel : ViewComponent { } public class ViewComponentWithStringModel : ViewComponent { public IViewComponentResult Invoke(string model) { return View((object)model); } } public class ControllerWithNoUsingsNoToReturnsViewComponentUsingType : Controller { [HttpGet] [Route("/route/url")] public ViewComponentResult HandlerAction() { return ViewComponent(typeof(ViewComponentWithoutModel)); } } public class ControllerWithNoUsingsXToReturnsViewComponentUsingType : Controller { [HttpGet] [Route("/route/url")] public ViewComponentResult HandlerAction() { return ViewComponent(typeof(ViewComponentWithStringModel), "Hello World!"); } } public class ControllerWithNoUsingsXDoReturnsViewComponentUsingType : Controller { [HttpGet] [Route("/route/url")] public ViewComponentResult HandlerAction() { return ViewComponent(typeof(ViewComponentWithoutModel)); } } public class ControllerWithNoUsings1Do1ToReturnsViewComponentUsingType : Controller { [HttpGet] [Route("/route/url")] public ViewComponentResult HandlerAction() { return ViewComponent(typeof(ViewComponentWithStringModel), "baz"); } } public class ControllerWith1BodyReturnsViewComponentUsingType : Controller { [HttpGet] [Route("/route/url")] public ViewComponentResult HandlerAction([FromBody]string name) { return ViewComponent(typeof(ViewComponentWithStringModel), $"Hello {name}!"); } } public class ControllerWith1Body1RouteParamReturnsViewComponentUsingType : Controller { [HttpGet] [Route("/route/{lastName}")] public ViewComponentResult HandlerAction([FromBody]string firstName, [FromRoute]string lastName) { return ViewComponent(typeof(ViewComponentWithStringModel), $"Hello {firstName} {lastName}!"); } } public class ControllerWith1Body1RouteParam2ToReturnsViewComponentUsingType : Controller { [HttpGet] [Route("/route/{lastName}")] public ViewComponentResult HandlerAction([FromBody]string firstName, [FromRoute]string lastName) { return ViewComponent(typeof(ViewComponentWithStringModel), $"Hello {firstName} {lastName}!"); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/TitleTests.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using System.Linq; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class TitleTests { [Fact(DisplayName = "Title inside single action")] public void FluentControllerBuilder_FluentActionWithTitle() { var action = new FluentAction("/route/url", HttpMethod.Get) .WithTitle("Custom Title") .To(() => "Hello"); Assert.Equal("Custom Title", action.Definition.Title); } [Fact(DisplayName = "Title inside single action async")] public void FluentControllerBuilder_FluentActionWithTitleAsync() { var action = new FluentAction("/route/url", HttpMethod.Get) .WithTitle("Custom Title") .To(async () => { await Task.Delay(1); return "Hello"; }); Assert.Equal("Custom Title", action.Definition.Title); } [Fact(DisplayName = "Title inside action collection config")] public void FluentControllerBuilder_FluentActionCollectionWithTitle() { var actionCollection = FluentActionCollection.DefineActions( actions => { actions.Configure(config => { config.SetTitle(action => action.Id); }); actions .RouteGet("/users", "ListUsers") .UsingService<IUserService>() .To(userService => userService.ListUsers()); actions .RoutePost("/users", "AddUser") .UsingService<IUserService>() .UsingBody<UserItem>() .To((userService, user) => userService.AddUser(user)); actions .RouteGet("/users/{userId}", "GetUser") .UsingService<IUserService>() .UsingRouteParameter<int>("userId") .To((userService, userId) => userService.GetUserById(userId)); actions .RoutePut("/users/{userId}", "UpdateUser") .UsingService<IUserService>() .UsingRouteParameter<int>("userId") .UsingBody<UserItem>() .To((userService, userId, user) => userService.UpdateUser(userId, user)); actions .RouteDelete("/users/{userId}", "RemoveUser") .UsingService<IUserService>() .UsingRouteParameter<int>("userId") .To((userService, userId) => userService.RemoveUser(userId)); } ); foreach (var action in actionCollection) { Assert.Equal(action.Definition.Id, action.Definition.Title); } } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/BaseController.cs<|end_filename|> using Microsoft.AspNetCore.Mvc; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { public class BaseController : Controller { public string Hello(string name = "Unnamed player") { return $"Hello {name}!"; } } public class BaseController2 : Controller { } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/Builder/BuilderHelper.cs<|end_filename|> using System; using System.Linq; using System.Threading.Tasks; namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core.Builder { public static class BuilderHelper { public static Type GetDelegateType(FluentActionHandlerDefinition handler) { if (handler.Type == FluentActionHandlerType.Action && !handler.Async) { return GetActionType(handler); } else { return GetFuncType(handler); } } public static Type GetReturnTypeOrTaskType(FluentActionHandlerDefinition handler) { if (handler.Async && handler.ReturnType == null) { return typeof(Task); } else if (handler.Async && handler.ReturnType != null) { return typeof(Task<>).MakeGenericType(handler.ReturnType); } else { return handler.ReturnType; } } public static Type GetFuncType(FluentActionHandlerDefinition handler) { var argumentTypes = handler.Usings.Select(@using => @using.Type).ToList(); var resultType = GetReturnTypeOrTaskType(handler); argumentTypes.Add(resultType); var unspecifiedGenericFuncType = GetUnspecifiedGenericFuncType(argumentTypes.Count); var specifiedGenericFuncType = unspecifiedGenericFuncType.MakeGenericType(argumentTypes.ToArray()); return specifiedGenericFuncType; } public static Type GetUnspecifiedGenericFuncType(int arguments) { switch (arguments) { case 1: return typeof(Func<>); case 2: return typeof(Func<,>); case 3: return typeof(Func<,,>); case 4: return typeof(Func<,,,>); case 5: return typeof(Func<,,,,>); case 6: return typeof(Func<,,,,,>); case 7: return typeof(Func<,,,,,,>); case 8: return typeof(Func<,,,,,,,>); } throw new Exception($"Fluent actions supports only up to eight arguments."); } public static Type GetActionType(FluentActionHandlerDefinition handler) { var argumentTypes = handler.Usings.Select(@using => @using.Type).ToList(); if (argumentTypes.Count == 0) { return typeof(Action); } else { var unspecifiedGenericActionType = GetUnspecifiedGenericActionType(argumentTypes.Count); var specifiedGenericActionType = unspecifiedGenericActionType.MakeGenericType(argumentTypes.ToArray()); return specifiedGenericActionType; } } public static Type GetUnspecifiedGenericActionType(int arguments) { switch (arguments) { case 1: return typeof(Action<>); case 2: return typeof(Action<,>); case 3: return typeof(Action<,,>); case 4: return typeof(Action<,,,>); case 5: return typeof(Action<,,,,>); case 6: return typeof(Action<,,,,,>); case 7: return typeof(Action<,,,,,,>); case 8: return typeof(Action<,,,,,,,>); } throw new Exception($"Fluent actions supports only up to eight arguments."); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithViewComponentTypeResult.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithViewComponentTypeResult { [Fact(DisplayName = "no usings, no To, returns ViewComponentResult (type)")] public void FluentControllerBuilder_FluentActionNoUsingsNoToReturnsViewComponentUsingType() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .ToViewComponent(typeof(ViewComponentWithoutModel)), typeof(ControllerWithNoUsingsNoToReturnsViewComponentUsingType), null); } [Fact(DisplayName = "no usings, 1 To, returns ViewComponentResult (type)")] public void FluentControllerBuilder_FluentActionNoUsings1ToReturnsViewComponentUsingType() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(() => "Hello World!") .ToViewComponent(typeof(ViewComponentWithStringModel)), typeof(ControllerWithNoUsingsXToReturnsViewComponentUsingType), null); } [Fact(DisplayName = "no usings, 3 To, returns ViewComponentResult (type)")] public void FluentControllerBuilder_FluentActionNoUsings3ToReturnsViewComponentUsingType() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(() => "Hello") .UsingResult() .To(text => $"{text} World") .UsingResult() .To(text => $"{text}!") .ToViewComponent(typeof(ViewComponentWithStringModel)), typeof(ControllerWithNoUsingsXToReturnsViewComponentUsingType), null); } [Fact(DisplayName = "no usings, 1 Do, returns ViewComponentResult (type)")] public void FluentControllerBuilder_FluentActionNoUsings1DoReturnsViewComponentUsingType() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .Do(() => { /* woop woop */ }) .ToViewComponent(typeof(ViewComponentWithoutModel)), typeof(ControllerWithNoUsingsXDoReturnsViewComponentUsingType), null); } [Fact(DisplayName = "no usings, 3 Do, returns ViewComponentResult (type)")] public void FluentControllerBuilder_FluentActionNoUsings3DoReturnsViewComponentUsingType() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .Do(() => { /* woop woop */ }) .Do(() => { /* woop woop */ }) .Do(() => { /* woop woop */ }) .ToViewComponent(typeof(ViewComponentWithoutModel)), typeof(ControllerWithNoUsingsXDoReturnsViewComponentUsingType), null); } [Fact(DisplayName = "no usings, 1 Do, 1 To, returns ViewComponentResult (type)")] public void FluentControllerBuilder_FluentActionNoUsings1Do1ToReturnsViewComponentUsingType() { var foo = "bar"; BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .Do(() => { foo = "baz"; }) .To(() => foo) .ToViewComponent(typeof(ViewComponentWithStringModel)), typeof(ControllerWithNoUsings1Do1ToReturnsViewComponentUsingType), null); } [Fact(DisplayName = "1 body (string), returns ViewComponentResult (type)")] public void FluentControllerBuilder_FluentAction1BodyReturnsViewComponentUsingType() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingBody<string>() .To(name => $"Hello {name}!") .ToViewComponent(typeof(ViewComponentWithStringModel)), typeof(ControllerWith1BodyReturnsViewComponentUsingType), new object[] { "Bob" }); } [Fact(DisplayName = "1 body (string), 1 Do, 1 To, returns ViewComponentResult (type)")] public void FluentControllerBuilder_FluentAction1Body1DoReturnsViewComponentUsingType() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .Do(() => { /* woop woop */ }) .UsingBody<string>() .To(name => $"Hello {name}!") .ToViewComponent(typeof(ViewComponentWithStringModel)), typeof(ControllerWith1BodyReturnsViewComponentUsingType), new object[] { "Bob" }); } [Fact(DisplayName = "1 body (string), 1 route param (string), returns ViewComponentResult (type)")] public void FluentControllerBuilder_FluentAction1Body1RouteParamReturnsViewComponentUsingType() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/{lastName}", HttpMethod.Get) .UsingBody<string>() .UsingRouteParameter<string>("lastName") .To((firstName, lastName) => $"Hello {firstName} {lastName}!") .ToViewComponent(typeof(ViewComponentWithStringModel)), typeof(ControllerWith1Body1RouteParamReturnsViewComponentUsingType), new object[] { "Bob", "Bobsson" }); } [Fact(DisplayName = "1 body (string), 1 route param (string), 2 To, returns ViewComponentResult (type)")] public void FluentControllerBuilder_FluentAction1Body1RouteParam2ToReturnsViewComponentUsingType() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/{lastName}", HttpMethod.Get) .UsingBody<string>() .To(firstName => $"Hello {firstName}") .UsingRouteParameter<string>("lastName") .To(lastName => $"{lastName}!") .ToViewComponent(typeof(ViewComponentWithStringModel)), typeof(ControllerWith1Body1RouteParam2ToReturnsViewComponentUsingType), new object[] { "Bob", "Bobsson" }); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/ControllersWithViewBag.cs<|end_filename|> using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { public class ControllerWithViewBagReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction() { ViewBag.Foo = "bar"; return (string)ViewBag.Foo; } } public class ControllerWithViewBagReturnsStringAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<string> HandlerAction() { await Task.Delay(1); ViewBag.Foo = "bar"; return (string)ViewBag.Foo; } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderOrderTestsSize2.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using Microsoft.Extensions.Logging; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; using System; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderOrderTestsSize2 { private readonly TestLogger TestLogger; public BuilderOrderTestsSize2(ITestOutputHelper testOutputHelper) { TestLogger = new TestLogger(testOutputHelper); } [Fact(DisplayName = "OrderTest, Size 2: [Do-Do] throws")] public void FluentControllerBuilder_FluentActionOrderTestDoDoThrows() { Assert.Throws<FluentActionValidationException>(() => { BuilderTestUtils.BuildAction( new FluentAction("/route/url", HttpMethod.Get) .Do(() => { /* woop woop */ }) .Do(() => { /* woop woop */ }), TestLogger); }); } [Fact(DisplayName = "OrderTest, Size 2: [Do-DoA] throws")] public void FluentControllerBuilder_FluentActionOrderTestDoDoAThrows() { Assert.Throws<FluentActionValidationException>(() => { BuilderTestUtils.BuildAction( new FluentAction("/route/url", HttpMethod.Get) .Do(() => { /* woop woop */ }) .DoAsync(async () => { await Task.Delay(1); }), TestLogger); }); } [Fact(DisplayName = "OrderTest, Size 2: [Do-To] returns string")] public void FluentControllerBuilder_FluentActionOrderTestDoToReturnsString() { var text = ""; BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .Do(() => { text += "Do"; }) .To(() => { text += "To"; return "Hello"; }), typeof(ControllerForOrderTestsReturnsString), null, TestLogger); Assert.Equal("DoTo", text); } [Fact(DisplayName = "OrderTest, Size 2: [Do-ToA] returns string")] public void FluentControllerBuilder_FluentActionOrderTestDoToAReturnsString() { var text = ""; BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .Do(() => { text += "Do"; }) .To(async () => { await Task.Delay(1); text += "ToA"; return "Hello"; }), typeof(ControllerForOrderTestsReturnsStringAsync), null, TestLogger); Assert.Equal("DoToA", text); } [Fact(DisplayName = "OrderTest, Size 2: [DoA-Do] throws")] public void FluentControllerBuilder_FluentActionOrderTestDoADoThrows() { Assert.Throws<FluentActionValidationException>(() => { BuilderTestUtils.BuildAction( new FluentAction("/route/url", HttpMethod.Get) .DoAsync(async () => { await Task.Delay(1); }) .Do(() => { /* woop woop */ }), TestLogger); }); } [Fact(DisplayName = "OrderTest, Size 2: [DoA-DoA] throws")] public void FluentControllerBuilder_FluentActionOrderTestDoADoAThrows() { Assert.Throws<FluentActionValidationException>(() => { BuilderTestUtils.BuildAction( new FluentAction("/route/url", HttpMethod.Get) .DoAsync(async () => { await Task.Delay(1); }) .DoAsync(async () => { await Task.Delay(1); }), TestLogger); }); } [Fact(DisplayName = "OrderTest, Size 2: [DoA-To] returns string")] public void FluentControllerBuilder_FluentActionOrderTestDoAToReturnsString() { var text = ""; BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .DoAsync(async () => { await Task.Delay(1); text += "DoA"; }) .To(() => { text += "To"; return "Hello"; }), typeof(ControllerForOrderTestsReturnsStringAsync), null, TestLogger); Assert.Equal("DoATo", text); } [Fact(DisplayName = "OrderTest, Size 2: [DoA-ToA] returns string")] public void FluentControllerBuilder_FluentActionOrderTestDoAToAReturnsString() { var text = ""; BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .DoAsync(async () => { await Task.Delay(1); text += "DoA"; }) .To(async () => { await Task.Delay(1); text += "ToA"; return "Hello"; }), typeof(ControllerForOrderTestsReturnsStringAsync), null, TestLogger); Assert.Equal("DoAToA", text); } [Fact(DisplayName = "OrderTest, Size 2: [To-Do] throws")] public void FluentControllerBuilder_FluentActionOrderTestToDoThrows() { Assert.Throws<FluentActionValidationException>(() => { BuilderTestUtils.BuildAction( new FluentAction("/route/url", HttpMethod.Get) .To(() => "Unused") .Do(() => { /* woop woop */ }), TestLogger); }); } [Fact(DisplayName = "OrderTest, Size 2: [To-DoA] throws")] public void FluentControllerBuilder_FluentActionOrderTestToDoAThrows() { Assert.Throws<FluentActionValidationException>(() => { BuilderTestUtils.BuildAction( new FluentAction("/route/url", HttpMethod.Get) .To(() => "Unused") .DoAsync(async () => { await Task.Delay(1); }), TestLogger); }); } [Fact(DisplayName = "OrderTest, Size 2: [To-To] returns string")] public void FluentControllerBuilder_FluentActionOrderTestToToReturnsString() { var text = ""; BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(() => { text += "To"; return "He"; }) .UsingResult() .To(he => { text += "To"; return $"{he}llo"; }), typeof(ControllerForOrderTestsReturnsString), null, TestLogger); Assert.Equal("ToTo", text); } [Fact(DisplayName = "OrderTest, Size 2: [To-ToA] returns string")] public void FluentControllerBuilder_FluentActionOrderTestToToAReturnsString() { var text = ""; BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(() => { text += "To"; return "He"; }) .UsingResult() .To(async he => { await Task.Delay(1); text += "ToA"; return $"{he}llo"; }), typeof(ControllerForOrderTestsReturnsStringAsync), null, TestLogger); Assert.Equal("ToToA", text); } [Fact(DisplayName = "OrderTest, Size 2: [ToA-Do] throws")] public void FluentControllerBuilder_FluentActionOrderTestToADoThrows() { Assert.Throws<FluentActionValidationException>(() => { BuilderTestUtils.BuildAction( new FluentAction("/route/url", HttpMethod.Get) .To(async () => { await Task.Delay(1); return "Unused"; }) .Do(() => { /* woop woop */ }), TestLogger); }); } [Fact(DisplayName = "OrderTest, Size 2: [ToA-DoA] throws")] public void FluentControllerBuilder_FluentActionOrderTestToADoAThrows() { Assert.Throws<FluentActionValidationException>(() => { BuilderTestUtils.BuildAction( new FluentAction("/route/url", HttpMethod.Get) .To(async () => { await Task.Delay(1); return "Unused"; }) .DoAsync(async () => { await Task.Delay(1); }), TestLogger); }); } [Fact(DisplayName = "OrderTest, Size 2: [ToA-To] returns string")] public void FluentControllerBuilder_FluentActionOrderTestToAToReturnsString() { var text = ""; BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(async () => { await Task.Delay(1); text += "ToA"; return "He"; }) .UsingResult() .To(he => { text += "To"; return $"{he}llo"; }), typeof(ControllerForOrderTestsReturnsStringAsync), null, TestLogger); Assert.Equal("ToATo", text); } [Fact(DisplayName = "OrderTest, Size 2: [ToA-ToA] returns string")] public void FluentControllerBuilder_FluentActionOrderTestToAToAReturnsString() { var text = ""; BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(async () => { await Task.Delay(1); text += "ToA"; return "He"; }) .UsingResult() .To(async he => { await Task.Delay(1); text += "ToA"; return $"{he}llo"; }), typeof(ControllerForOrderTestsReturnsStringAsync), null, TestLogger); Assert.Equal("ToAToA", text); } } } <|start_filename|>test/WebApps/SimpleApi/Actions/UserActions.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; namespace SimpleApi { public static class UserActions { public static FluentActionCollection All => FluentActionCollection.DefineActions( actions => { actions.Configure(config => { config.GroupBy("UserActions"); config.SetTitleFromResource(typeof(Localization.Actions), action => $"{action.Id}_Title"); config.SetDescriptionFromResource(typeof(Localization.Actions), action => $"{action.Id}_Description"); }); actions .RouteGet("/users", "ListUsers") .UsingService<IUserService>() .To(userService => userService.List()); actions .RoutePost("/users", "AddUser") .UsingService<IUserService>() .UsingBody<UserItem>() .To((userService, user) => userService.Add(user)); actions .RouteGet("/users/{userId}", "GetUser") .UsingService<IUserService>() .UsingRouteParameter<int>("userId") .To((userService, userId) => userService.Get(userId)); actions .RoutePut("/users/{userId}", "UpdateUser") .UsingService<IUserService>() .UsingRouteParameter<int>("userId") .UsingBody<UserItem>() .To((userService, userId, user) => userService.Update(userId, user)); actions .RouteDelete("/users/{userId}", "RemoveUser") .UsingService<IUserService>() .UsingRouteParameter<int>("userId") .To((userService, userId) => userService.Remove(userId)); } ); } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/Builder/ControllerTypeBuilder.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core.Builder { public class ControllerTypeBuilder { public ModuleBuilder ModuleBuilder { get; internal set; } public TypeBuilder TypeBuilder { get; internal set; } public List<TypeBuilder> NestedTypes { get; internal set; } private ControllerTypeBuilder() { } public void BuildMethod(string name, ControllerMethodBuilder controllerMethodBuilder) { var methodBuilder = TypeBuilder.DefineMethod(name, MethodAttributes.Public | MethodAttributes.HideBySig); controllerMethodBuilder.TypeBuilder = TypeBuilder; controllerMethodBuilder.NestedTypes = new List<TypeBuilder>(); controllerMethodBuilder.MethodBuilder = methodBuilder; controllerMethodBuilder.Build(); NestedTypes = controllerMethodBuilder.NestedTypes; } public void SetCustomAttribute( ConstructorInfo constructor, object[] constructorArgs, PropertyInfo[] namedProperties, object[] propertyValues, FieldInfo[] namedFields, object[] fieldValues) { var attributeBuilder = new CustomAttributeBuilder( constructor, constructorArgs, namedProperties, propertyValues, namedFields, fieldValues ); TypeBuilder.SetCustomAttribute(attributeBuilder); } public TypeInfo CreateTypeInfo() { var typeInfo = TypeBuilder.CreateTypeInfo(); foreach(var nestedType in NestedTypes) { nestedType.CreateTypeInfo(); } return typeInfo; } public static ControllerTypeBuilder Create(ModuleBuilder moduleBuilder, string typeName, Type parentType = null) { var typeBuilder = moduleBuilder.DefineType( typeName, TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit, parentType ?? typeof(Controller)); typeBuilder.DefineDefaultConstructor(MethodAttributes.Public); return new ControllerTypeBuilder { ModuleBuilder = moduleBuilder, TypeBuilder = typeBuilder }; } public static ControllerTypeBuilder Create(string assemblyName, string moduleName, string typeName, Type parentType = null) { var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly( new AssemblyName(assemblyName), AssemblyBuilderAccess.Run); var moduleBuilder = assemblyBuilder.DefineDynamicModule(moduleName); return Create(moduleBuilder, typeName, parentType); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/ControllersWithModelBinders.cs<|end_filename|> using ExplicitlyImpl.FluentActions.Test.Utils; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Core; using System.Threading.Tasks; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { public class ControllerWithModelBinderReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction([ModelBinder(BinderType = typeof(NoOpBinder))]string name) { return $"Hello {name}!"; } } public class ControllerWithModelBinderReturnsStringAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<string> HandlerAction([ModelBinder(BinderType = typeof(NoOpBinder))]string name) { await Task.Delay(1); return $"Hello {name}!"; } } public class ControllerWithModelBinderAndNamePropertyReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction([ModelBinder(BinderType = typeof(NoOpBinder), Name = "NoOpName")]string name) { return $"Hello {name}!"; } } public class ControllerWithModelBinderAndNamePropertyReturnsStringAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<string> HandlerAction([ModelBinder(BinderType = typeof(NoOpBinder), Name = "NoOpName")]string name) { await Task.Delay(1); return $"Hello {name}!"; } } public class ControllerWithModelBinderAndDefaultValueReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction([ModelBinder(BinderType = typeof(NoOpBinder))]string name = "Hanzel") { return $"Hello {name}!"; } } public class ControllerWithModelBinderAndDefaultValueReturnsStringAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<string> HandlerAction([ModelBinder(BinderType = typeof(NoOpBinder))]string name = "Hanzel") { await Task.Delay(1); return $"Hello {name}!"; } } public class ControllerWithTwoIdenticalModelBindersReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction([ModelBinder(BinderType = typeof(NoOpBinder))]string name) { return $"Hello {name}! I said hello {name}!"; } } public class ControllerWithTwoIdenticalModelBindersReturnsStringAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<string> HandlerAction([ModelBinder(BinderType = typeof(NoOpBinder))]string name) { await Task.Delay(1); return $"Hello {name}! I said hello {name}!"; } } } <|start_filename|>test/WebApps/SimpleMvc/Views/Form/UploadFiles.cshtml<|end_filename|>  <h2>Upload Files.</h2> <form method="post" class="form-horizontal" enctype="multipart/form-data"> <div class="form-group"> <label for="file" class="col-md-2 control-label">Files:</label> <div class="col-md-10"> <input type="file" name="files" class="form-control" multiple /> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <button type="submit" class="btn btn-default">Upload files</button> </div> </div> </form> <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/Builder/ControllerMethodBuilderForFluentAction.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Concurrent; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Threading.Tasks; using System.Collections.Generic; namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core.Builder { public class ControllerMethodBuilderForFluentAction : ControllerMethodBuilder { public FluentActionDefinition FluentActionDefinition { get; set; } public ControllerMethodBuilderForFluentAction(FluentActionDefinition fluentActionDefinition) { FluentActionDefinition = fluentActionDefinition; } public override void Build() { var usingsForMethodParameters = FluentActionDefinition.Handlers .SelectMany(handler => handler.Usings) .Where(@using => @using.IsMethodParameter) .Distinct() .ToArray(); var methodParameterIndices = usingsForMethodParameters .Select((@using, index) => new { Using = @using, Index = index }) .ToDictionary( indexedUsing => indexedUsing.Using.GetHashCode(), indexedUsing => indexedUsing.Index + 1 // 1-based index ); var methodParameterTypes = usingsForMethodParameters .Select(@using => @using.Type) .ToArray(); var returnType = FluentActionDefinition.Handlers.Last().ReturnType; if (FluentActionDefinition.IsAsync) { returnType = typeof(Task<>).MakeGenericType(returnType); } MethodBuilder.SetReturnType(returnType); MethodBuilder.SetParameters(methodParameterTypes); SetHttpMethodAttribute(FluentActionDefinition.HttpMethod); SetRouteAttribute(FluentActionDefinition.RouteTemplate); foreach (var customAttribute in FluentActionDefinition.CustomAttributes) { SetCustomAttribute(customAttribute); } foreach (var usingDefinition in usingsForMethodParameters) { var methodParameterIndex = methodParameterIndices[usingDefinition.GetHashCode()]; usingDefinition.DefineMethodParameter(MethodBuilder, FluentActionDefinition, usingDefinition, methodParameterIndex); } var ilGenerator = MethodBuilder.GetILGenerator(); LocalBuilder localVariableForPreviousReturnValue = null; foreach (var handler in FluentActionDefinition.Handlers) { if (handler.Type == FluentActionHandlerType.Func) { var handlerReturnType = BuilderHelper.GetReturnTypeOrTaskType(handler); var localVariableForReturnValue = ilGenerator.DeclareLocal(handlerReturnType); var funcType = BuilderHelper.GetFuncType(handler); var delegateKey = FluentActionDelegates.Add(handler.Delegate); // Push Delegate ilGenerator.Emit(OpCodes.Ldsfld, FluentActionDelegates.FieldInfo); ilGenerator.Emit(OpCodes.Ldstr, delegateKey); ilGenerator.Emit(OpCodes.Callvirt, FluentActionDelegates.MethodInfo); // Push arguments for Func foreach (var usingDefinition in handler.Usings) { EmitUsingDefinitionValue(ilGenerator, usingDefinition, methodParameterIndices, localVariableForPreviousReturnValue); } // Push Func.Invoke ilGenerator.Emit(OpCodes.Callvirt, funcType.GetMethod("Invoke")); // Push storing result in local variable ilGenerator.Emit(OpCodes.Stloc, localVariableForReturnValue); // Make sure next handler has access to previous handler's return value localVariableForPreviousReturnValue = localVariableForReturnValue; } else if (handler.Type == FluentActionHandlerType.Action) { var actionType = BuilderHelper.GetActionType(handler); var delegateKey = FluentActionDelegates.Add(handler.Delegate); // Push Delegate ilGenerator.Emit(OpCodes.Ldsfld, FluentActionDelegates.FieldInfo); ilGenerator.Emit(OpCodes.Ldstr, delegateKey); ilGenerator.Emit(OpCodes.Callvirt, FluentActionDelegates.MethodInfo); // Push arguments for Action foreach (var usingDefinition in handler.Usings) { EmitUsingDefinitionValue(ilGenerator, usingDefinition, methodParameterIndices, localVariableForPreviousReturnValue); } // Push Action.Invoke ilGenerator.Emit(OpCodes.Callvirt, actionType.GetMethod("Invoke")); // This handler does not produce a result localVariableForPreviousReturnValue = null; } else if (handler.Type == FluentActionHandlerType.View || handler.Type == FluentActionHandlerType.PartialView || (handler.Type == FluentActionHandlerType.ViewComponent && handler.ViewComponentType == null)) { if (handler.ViewTarget == null) { throw new Exception("Must specify a view target."); } var localVariableForReturnValue = ilGenerator.DeclareLocal(handler.ReturnType); // Call one of the following controller methods: // Controller.View(string pathName, object model) // Controller.PartialView(string pathName, object model) // Controller.ViewComponent(string componentName, object arguments) ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldstr, handler.ViewTarget); Type[] viewMethodParameterTypes = null; if (handler.Usings.Any()) { EmitUsingDefinitionValue(ilGenerator, handler.Usings.Last(), methodParameterIndices, localVariableForPreviousReturnValue); viewMethodParameterTypes = new[] { typeof(string), typeof(object) }; } else if (localVariableForPreviousReturnValue != null) { ilGenerator.Emit(OpCodes.Ldloc, localVariableForPreviousReturnValue); viewMethodParameterTypes = new[] { typeof(string), typeof(object) }; } else { viewMethodParameterTypes = new[] { typeof(string) }; } MethodInfo viewMethod = null; if (handler.Type == FluentActionHandlerType.View) { viewMethod = typeof(Controller).GetMethod("View", viewMethodParameterTypes); } else if (handler.Type == FluentActionHandlerType.PartialView) { viewMethod = typeof(Controller).GetMethod("PartialView", viewMethodParameterTypes); } else if (handler.Type == FluentActionHandlerType.ViewComponent) { viewMethod = typeof(Controller).GetMethod("ViewComponent", viewMethodParameterTypes); } ilGenerator.Emit(OpCodes.Callvirt, viewMethod); // Push storing result in local variable ilGenerator.Emit(OpCodes.Stloc, localVariableForReturnValue); // Make sure next handler has access to previous handler's return value localVariableForPreviousReturnValue = localVariableForReturnValue; } else if (handler.Type == FluentActionHandlerType.ViewComponent) { if (handler.ViewComponentType == null) { throw new Exception("Must specify a target view component type."); } var localVariableForReturnValue = ilGenerator.DeclareLocal(handler.ReturnType); // Call the following controller method: // Controller.ViewComponent(Type componentType, object arguments) ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldtoken, handler.ViewComponentType); ilGenerator.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle", new[] { typeof(RuntimeTypeHandle) })); Type[] viewMethodParameterTypes = null; if (localVariableForPreviousReturnValue != null) { ilGenerator.Emit(OpCodes.Ldloc, localVariableForPreviousReturnValue); viewMethodParameterTypes = new[] { typeof(Type), typeof(object) }; } else { viewMethodParameterTypes = new[] { typeof(Type) }; } var viewMethod = typeof(Controller).GetMethod("ViewComponent", viewMethodParameterTypes); ilGenerator.Emit(OpCodes.Callvirt, viewMethod); // Push storing result in local variable ilGenerator.Emit(OpCodes.Stloc, localVariableForReturnValue); // Make sure next handler has access to previous handler's return value localVariableForPreviousReturnValue = localVariableForReturnValue; } } // Return last handlers return value ilGenerator.Emit(OpCodes.Ldloc, localVariableForPreviousReturnValue); ilGenerator.Emit(OpCodes.Ret); } private void EmitUsingDefinitionValue( ILGenerator ilGenerator, FluentActionUsingDefinition usingDefinition, Dictionary<int, int> methodParameterIndices, LocalBuilder localVariableForPreviousReturnValue) { var ilHandle = new IlHandle { Generator = ilGenerator }; var usingDefinitionHash = usingDefinition.GetHashCode(); var methodParameterIndex = methodParameterIndices.ContainsKey(usingDefinitionHash) ? methodParameterIndices[usingDefinitionHash] : -1; if (usingDefinition.IsMethodParameter) { ilHandle.Generator.Emit(OpCodes.Ldarg, methodParameterIndex); } else if (usingDefinition.IsControllerProperty) { ilHandle.Generator.Emit(OpCodes.Ldarg_0); ilHandle.Generator.Emit(OpCodes.Callvirt, typeof(Controller).GetProperty(usingDefinition.ControllerPropertyName).GetGetMethod()); } else if (usingDefinition is FluentActionUsingPropertyDefinition) { var propertyName = ((FluentActionUsingPropertyDefinition)usingDefinition).PropertyName; var parentType = FluentActionDefinition.ParentType ?? typeof(Controller); var property = parentType.GetProperty(propertyName); if (property == null) { throw new Exception($"Could not find property {propertyName} on type {parentType.FullName}."); } var propertyGetMethod = property.GetGetMethod(); if (propertyGetMethod == null) { throw new Exception($"Missing public get method on property {propertyName} on type {parentType.FullName}."); } ilHandle.Generator.Emit(OpCodes.Ldarg_0); ilHandle.Generator.Emit(OpCodes.Callvirt, propertyGetMethod); } else if (usingDefinition is FluentActionUsingParentDefinition) { ilHandle.Generator.Emit(OpCodes.Ldarg_0); } else if (usingDefinition is FluentActionUsingResultDefinition) { if (localVariableForPreviousReturnValue == null) { throw new Exception("Cannot use previous result from handler as no previous result exists."); } ilHandle.Generator.Emit(OpCodes.Ldloc, localVariableForPreviousReturnValue); if (localVariableForPreviousReturnValue.LocalType.IsValueType) { ilHandle.Generator.Emit(OpCodes.Box, localVariableForPreviousReturnValue.LocalType); } } else { throw new Exception($"Got unknown using definition: {usingDefinition.GetType()}"); } } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithAuthorize.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithAuthorize { [Fact(DisplayName = "1 authorize (empty), returns string")] public void FluentControllerBuilder_FluentActionWith1AuthorizeReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .Authorize() .To(() => "hello"), typeof(ControllerWith1AuthorizeReturnsString), null); } [Fact(DisplayName = "1 authorize (policy), returns string")] public void FluentControllerBuilder_FluentActionWith1AuthorizePolicyReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .Authorize(policy: "CanSayHello") .To(() => "hello"), typeof(ControllerWith1AuthorizePolicyReturnsString), null); } [Fact(DisplayName = "1 authorize (roles), returns string")] public void FluentControllerBuilder_FluentActionWith1AuthorizeRolesReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .Authorize(roles: "Admin") .To(() => "hello"), typeof(ControllerWith1AuthorizeRolesReturnsString), null); } [Fact(DisplayName = "1 authorize (authenticationSchemes), returns string")] public void FluentControllerBuilder_FluentActionWith1AuthorizeAuthenticationSchemesReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .Authorize(authenticationSchemes: "Scheme") .To(() => "hello"), typeof(ControllerWith1AuthorizeAuthenticationSchemesReturnsString), null); } [Fact(DisplayName = "1 authorize (policy - roles - authenticationSchemes), returns string")] public void FluentControllerBuilder_FluentActionWith1AuthorizePolicyRolesAuthenticationSchemesReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .Authorize("CanSayHello", "Admin", "Scheme") .To(() => "hello"), typeof(ControllerWith1AuthorizePolicyRolesAuthenticationSchemesReturnsString), null); } [Fact(DisplayName = "1 authorize (empty), returns ViewResult async")] public void FluentControllerBuilder_FluentActionWith1AuthorizeReturnsViewResultAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .Authorize() .To(async () => { await Task.Delay(1); return "hello"; }) .ToView("~/Path/To/ViewWithStringModel.cshtml"), typeof(ControllerWith1AuthorizeReturnsViewResultAsync), null); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/ControllersWithPartialViewResult.cs<|end_filename|> using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { public class ControllerWithNoUsingsNoToReturnsPartialView : Controller { [HttpGet] [Route("/route/url")] public PartialViewResult HandlerAction() { return PartialView("~/Path/To/PartialViewWithoutModel.cshtml"); } } public class ControllerPassing1BodyReturnsPartialView : Controller { [HttpGet] [Route("/route/url")] public PartialViewResult HandlerAction([FromBody]string model) { return PartialView("~/Path/To/PartialViewWithStringModel.cshtml", model); } } public class ControllerWith1Body1RouteParamPassing1BodyReturnsPartialView : Controller { [HttpGet] [Route("/route/url/{unused}")] public PartialViewResult HandlerAction([FromBody]string model, [FromRoute]string unused) { return PartialView("~/Path/To/PartialViewWithStringModel.cshtml", model); } } public class ControllerWithNoUsingsXToReturnsPartialView : Controller { [HttpGet] [Route("/route/url")] public PartialViewResult HandlerAction() { return PartialView("~/Path/To/PartialViewWithStringModel.cshtml", "Hello World!"); } } public class ControllerWithNoUsingsXDoReturnsPartialView : Controller { [HttpGet] [Route("/route/url")] public PartialViewResult HandlerAction() { return PartialView("~/Path/To/PartialViewWithoutModel.cshtml"); } } public class ControllerWithNoUsings1Do1ToReturnsPartialView : Controller { [HttpGet] [Route("/route/url")] public PartialViewResult HandlerAction() { return PartialView("~/Path/To/PartialViewWithStringModel.cshtml", "baz"); } } public class ControllerWith1BodyReturnsPartialView : Controller { [HttpGet] [Route("/route/url")] public PartialViewResult HandlerAction([FromBody]string name) { return PartialView("~/Path/To/PartialViewWithStringModel.cshtml", $"Hello {name}!"); } } public class ControllerWith1Body1RouteParamReturnsPartialView : Controller { [HttpGet] [Route("/route/{lastName}")] public PartialViewResult HandlerAction([FromBody]string firstName, [FromRoute]string lastName) { return PartialView("~/Path/To/PartialViewWithStringModel.cshtml", $"Hello {firstName} {lastName}!"); } } public class ControllerWith1Body1RouteParam2ToReturnsPartialView : Controller { [HttpGet] [Route("/route/{lastName}")] public PartialViewResult HandlerAction([FromBody]string firstName, [FromRoute]string lastName) { return PartialView("~/Path/To/PartialViewWithStringModel.cshtml", $"Hello {firstName} {lastName}!"); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/ControllersWithQueryStringParameters.cs<|end_filename|> using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { public class ControllerWithQueryStringParameterReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction([FromQuery]string name) { return $"Hello {name}!"; } } public class ControllerWithQueryStringParameterReturnsStringAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<string> HandlerAction([FromQuery]string name) { await Task.Delay(1); return $"Hello {name}!"; } } public class ControllerWithQueryStringParameterAndDefaultValueReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction([FromQuery]string name = "Hanzel") { return $"Hello {name}!"; } } public class ControllerWithQueryStringParameterAndDefaultValueReturnsStringAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<string> HandlerAction([FromQuery]string name = "Hanzel") { await Task.Delay(1); return $"Hello {name}!"; } } public class ControllerWithTwoIdenticalQueryStringParametersReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction([FromQuery]string name) { return $"Hello {name}! I said hello {name}!"; } } public class ControllerWithTwoIdenticalQueryStringParametersReturnsStringAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<string> HandlerAction([FromQuery]string name) { await Task.Delay(1); return $"Hello {name}! I said hello {name}!"; } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithModelBinders.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using ExplicitlyImpl.FluentActions.Test.Utils; using System; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithModelBinders { [Fact(DisplayName = "1 model binder (string), returns string")] public void FluentControllerBuilder_FluentActionUsingModelBinderReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingModelBinder<string>(typeof(NoOpBinder)) .To(name => $"Hello {name}!"), typeof(ControllerWithModelBinderReturnsString), new object[] { "Charlie" }); } [Fact(DisplayName = "1 model binder (string), returns string async")] public void FluentControllerBuilder_FluentActionUsingModelBinderReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingModelBinder<string>(typeof(NoOpBinder)) .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }), typeof(ControllerWithModelBinderReturnsStringAsync), new object[] { "Charlie" }); } [Fact(DisplayName = "1 model binder (string) with name property, returns string")] public void FluentControllerBuilder_FluentActionUsingModelBinderWithNamePropertyReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingModelBinder<string>(typeof(NoOpBinder), "NoOpName2") .To(name => $"Hello {name}!"), typeof(ControllerWithModelBinderAndNamePropertyReturnsString), new object[] { "Charlie" }); } [Fact(DisplayName = "1 model binder (string) with name property, returns string async")] public void FluentControllerBuilder_FluentActionUsingModelBinderWithNamePropertyReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingModelBinder<string>(typeof(NoOpBinder), "NoOpName2") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }), typeof(ControllerWithModelBinderAndNamePropertyReturnsStringAsync), new object[] { "Charlie" }); } [Fact(DisplayName = "1 model binder (string) with used default value, returns string")] public void FluentControllerBuilder_FluentActionUsingModelBinderWithUsedDefaultValueReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingModelBinder<string>(typeof(NoOpBinder), null, "Hanzel") .To(name => $"Hello {name}!"), typeof(ControllerWithModelBinderAndDefaultValueReturnsString), new object[] { Type.Missing }); } [Fact(DisplayName = "1 model binder (string) with used default value, returns string async")] public void FluentControllerBuilder_FluentActionUsingModelBinderWithUsedDefaultValueReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingModelBinder<string>(typeof(NoOpBinder), null, "Hanzel") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }), typeof(ControllerWithModelBinderAndDefaultValueReturnsStringAsync), new object[] { Type.Missing }); } [Fact(DisplayName = "1 model binder (string) with unused default value, returns string")] public void FluentControllerBuilder_FluentActionUsingModelBinderWithUnusedDefaultValueReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingModelBinder<string>(typeof(NoOpBinder), null, "Hanzel") .To(name => $"Hello {name}!"), typeof(ControllerWithModelBinderAndDefaultValueReturnsString), new object[] { "Charlie" }); } [Fact(DisplayName = "1 model binder (string) with unused default value, returns string async")] public void FluentControllerBuilder_FluentActionUsingModelBinderWithUnusedDefaultValueReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingModelBinder<string>(typeof(NoOpBinder), null, "Hanzel") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }), typeof(ControllerWithModelBinderAndDefaultValueReturnsStringAsync), new object[] { "Charlie" }); } [Fact(DisplayName = "2 model binders (string, identical), returns string")] public void FluentControllerBuilder_FluentActionUsingTwoIdenticalModelBindersReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingModelBinder<string>(typeof(NoOpBinder)) .UsingModelBinder<string>(typeof(NoOpBinder)) .To((name1, name2) => $"Hello {name1}! I said hello {name2}!"), typeof(ControllerWithTwoIdenticalModelBindersReturnsString), new object[] { "Charlie" }); } [Fact(DisplayName = "2 model binders (string, identical), returns string async")] public void FluentControllerBuilder_FluentActionUsingTwoIdenticalModelBindersReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingModelBinder<string>(typeof(NoOpBinder)) .UsingModelBinder<string>(typeof(NoOpBinder)) .To(async (name1, name2) => { await Task.Delay(1); return $"Hello {name1}! I said hello {name2}!"; }), typeof(ControllerWithTwoIdenticalModelBindersReturnsStringAsync), new object[] { "Charlie" }); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Services/StringService.cs<|end_filename|> using System.Threading.Tasks; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public interface IStringTestService { string GetTestString(); Task<string> GetTestStringAsync(); } public class StringTestService : IStringTestService { public string GetTestString() { return "ThisIsAString"; } public async Task<string> GetTestStringAsync() { await Task.Delay(1); return "ThisIsAString"; } } public class StringTestService2 : IStringTestService { public string GetTestString() { return "ThisIsAlsoAString"; } public async Task<string> GetTestStringAsync() { await Task.Delay(1); return "ThisIsAlsoAString"; } } } <|start_filename|>test/WebApps/MvcWithSwagger/Startup.cs<|end_filename|> using System; using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using NSwag.Annotations; namespace MvcWithSwagger { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services .AddMvc() .AddFluentActions() .AddFluentActions() // Test multiple calls to AddFluentActions ; services.AddTransient<IUserService, UserService>(); services.AddTransient<INoteService, NoteService>(); services.AddSwaggerDocument(config => { config.Title = "API docs"; config.Version = "0.1.0"; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.EnvironmentName == "Development") { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseCookiePolicy(); app.UseRouting(); app.UseFluentActions(actions => { actions .RouteGet("/") .WithCustomAttribute<OpenApiTagsAttribute>( new Type[] { typeof(string[]) }, new object[] { new string[] { "Hello World" } } ) .To(() => "Hello World!"); actions.Add(UserActions.All); actions.Add(NoteActions.All); }); // Test multiple calls to UseFluentActions app.UseFluentActions(actions => { actions .RouteGet("/starlord") .WithCustomAttribute<OpenApiTagsAttribute>( new Type[] { typeof(string[]) }, new object[] { new string[] { "Hello Starlord" } } ) .To(() => "Hello Starlord!"); }); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); app.UseOpenApi(config => { config.Path = "/api/docs/api.json"; }); app.UseSwaggerUi3(config => { config.DocumentPath = "/api/docs/api.json"; config.Path = "/api/docs"; }); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithViewData.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithViewData { [Fact(DisplayName = "1 ViewData, returns string")] public void FluentControllerBuilder_FluentActionWithViewDataReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingViewData() .To(viewData => { viewData["foo"] = "bar"; return (string)viewData["foo"]; }), typeof(ControllerWithViewDataReturnsString), null); } [Fact(DisplayName = "1 ViewData, returns string async")] public void FluentControllerBuilder_FluentActionWithViewDataReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingViewData() .To(async viewData => { await Task.Delay(1); viewData["foo"] = "bar"; return (string)viewData["foo"]; }), typeof(ControllerWithViewDataReturnsStringAsync), null); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithViewResultAsync.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithViewResultAsync { [Fact(DisplayName = "no usings, 1 To, returns ViewResult async")] public void FluentControllerBuilder_FluentActionNoUsings1ToReturnsViewAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(async () => { await Task.Delay(1); return "Hello World!"; }) .ToView("~/Path/To/ViewWithStringModel.cshtml"), typeof(ControllerWithNoUsingsXToReturnsViewAsync), null); } [Fact(DisplayName = "no usings, 3 To, returns ViewResult async")] public void FluentControllerBuilder_FluentActionNoUsings3ToReturnsViewAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .To(async () => { await Task.Delay(1); return "Hello"; }) .UsingResult() .To(async text => { await Task.Delay(1); return $"{text} World"; }) .UsingResult() .To(async text => { await Task.Delay(1); return $"{text}!"; }) .ToView("~/Path/To/ViewWithStringModel.cshtml"), typeof(ControllerWithNoUsingsXToReturnsViewAsync), null); } [Fact(DisplayName = "no usings, 1 Do, returns ViewResult async")] public void FluentControllerBuilder_FluentActionNoUsings1DoReturnsViewAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .DoAsync(async () => { await Task.Delay(1); }) .ToView("~/Path/To/ViewWithoutModel.cshtml"), typeof(ControllerWithNoUsingsXDoReturnsViewAsync), null); } [Fact(DisplayName = "no usings, 3 Do, returns ViewResult async")] public void FluentControllerBuilder_FluentActionNoUsings3DoReturnsViewAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .DoAsync(async () => { await Task.Delay(1); }) .DoAsync(async () => { await Task.Delay(1); }) .DoAsync(async () => { await Task.Delay(1); }) .ToView("~/Path/To/ViewWithoutModel.cshtml"), typeof(ControllerWithNoUsingsXDoReturnsViewAsync), null); } [Fact(DisplayName = "no usings, 1 Do, 1 To, returns ViewResult async")] public void FluentControllerBuilder_FluentActionNoUsings1Do1ToReturnsViewAsync() { var foo = "bar"; BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .DoAsync(async () => { await Task.Delay(1); foo = "baz"; }) .To(async () => { await Task.Delay(1); return foo; }) .ToView("~/Path/To/ViewWithStringModel.cshtml"), typeof(ControllerWithNoUsings1Do1ToReturnsViewAsync), null); } [Fact(DisplayName = "1 body (string), returns ViewResult async")] public void FluentControllerBuilder_FluentAction1BodyReturnsViewAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingBody<string>() .To(async (name) => { await Task.Delay(1); return $"Hello {name}!"; }) .ToView("~/Path/To/ViewWithStringModel.cshtml"), typeof(ControllerWith1BodyReturnsViewAsync), new object[] { "Bob" }); } [Fact(DisplayName = "1 body (string), 1 Do, 1 To, returns ViewResult async")] public void FluentControllerBuilder_FluentAction1Body1DoReturnsViewAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .DoAsync(async () => { await Task.Delay(1); }) .UsingBody<string>() .To(async (name) => { await Task.Delay(1); return $"Hello {name}!"; }) .ToView("~/Path/To/ViewWithStringModel.cshtml"), typeof(ControllerWith1BodyReturnsViewAsync), new object[] { "Bob" }); } [Fact(DisplayName = "1 body (string), 1 route param (string), returns ViewResult async")] public void FluentControllerBuilder_FluentAction1Body1RouteParamReturnsViewAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/{lastName}", HttpMethod.Get) .UsingBody<string>() .UsingRouteParameter<string>("lastName") .To(async (firstName, lastName) => { await Task.Delay(1); return $"Hello {firstName} {lastName}!"; }) .ToView("~/Path/To/ViewWithStringModel.cshtml"), typeof(ControllerWith1Body1RouteParamReturnsViewAsync), new object[] { "Bob", "Bobsson" }); } [Fact(DisplayName = "1 body (string), 1 route param (string), 2 To, returns ViewResult async")] public void FluentControllerBuilder_FluentAction1Body1RouteParam2ToReturnsViewAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/{lastName}", HttpMethod.Get) .UsingBody<string>() .To(async firstName => { await Task.Delay(1); return $"Hello {firstName}"; }) .UsingRouteParameter<string>("lastName") .To(async lastName => { await Task.Delay(1); return $"{lastName}!"; }) .ToView("~/Path/To/ViewWithStringModel.cshtml"), typeof(ControllerWith1Body1RouteParam2ToReturnsViewAsync), new object[] { "Bob", "Bobsson" }); } } } <|start_filename|>test/WebApps/SimpleMvc/Views/Home/About.cshtml<|end_filename|> @{ ViewData["Title"] = "About"; } <h2>@ViewData["Title"].</h2> <h4>@(ViewBag.ViewBagMessage ?? "No ViewBag message.")</h4> <h4>@(ViewData.ContainsKey("ViewDataMessage") ? ViewData["ViewDataMessage"] : "No ViewData message.")</h4> <h4>@(TempData.ContainsKey("TempDataMessage") ? TempData["TempDataMessage"] : "No TempData message.")</h4> <|start_filename|>test/WebApps/SimpleMvc/Views/Form/SubmitWithModelState.cshtml<|end_filename|>  <h2>Submit with model state.</h2> <form method="post" class="form-horizontal" enctype="multipart/form-data"> @Html.AntiForgeryToken() <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="text" name="textValue" /> <button type="submit" class="btn btn-default">Submit</button> </div> </div> </form> <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/ControllersWithFormValues.cs<|end_filename|> using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { public class ControllerWithFormValueReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction([FromForm]string name) { return $"Hello {name}!"; } } public class ControllerWithFormValueReturnsStringAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<string> HandlerAction([FromForm]string name) { await Task.Delay(1); return $"Hello {name}!"; } } public class ControllerWithFormValueAndDefaultValueReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction([FromForm]string name = "Hanzel") { return $"Hello {name}!"; } } public class ControllerWithFormValueAndDefaultValueReturnsStringAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<string> HandlerAction([FromForm]string name = "Hanzel") { await Task.Delay(1); return $"Hello {name}!"; } } public class ControllerWithTwoIdenticalFormValuesReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction([FromForm]string name) { return $"Hello {name}! I said hello {name}!"; } } public class ControllerWithTwoIdenticalFormValuesReturnsStringAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<string> HandlerAction([FromForm]string name) { await Task.Delay(1); return $"Hello {name}! I said hello {name}!"; } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/Controllers/ControllersWithForm.cs<|end_filename|> using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers { public class ControllerWithFormReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction([FromForm]string name) { return $"Hello {name}!"; } } public class ControllerWithFormReturnsStringAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<string> HandlerAction([FromForm]string name) { await Task.Delay(1); return $"Hello {name}!"; } } public class ControllerWithFormAndDefaultValueReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction([FromForm]string name = "Hanzel") { return $"Hello {name}!"; } } public class ControllerWithFormAndDefaultValueReturnsStringAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<string> HandlerAction([FromForm]string name = "Hanzel") { await Task.Delay(1); return $"Hello {name}!"; } } public class ControllerWithTwoIdenticalFormsReturnsString : Controller { [HttpGet] [Route("/route/url")] public string HandlerAction([FromForm]string name) { return $"Hello {name}! I said hello {name}!"; } } public class ControllerWithTwoIdenticalFormsReturnsStringAsync : Controller { [HttpGet] [Route("/route/url")] public async Task<string> HandlerAction([FromForm]string name) { await Task.Delay(1); return $"Hello {name}! I said hello {name}!"; } } } <|start_filename|>test/WebApps/SimpleMvc/Startup.cs<|end_filename|> using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using SimpleMvc.Controllers; using Microsoft.AspNetCore.Authorization; using SimpleMvc.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Diagnostics; using Microsoft.AspNetCore.Authentication; using Microsoft.Extensions.Options; using Microsoft.Extensions.Logging; using System.Text.Encodings.Web; namespace SimpleMvc { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services .AddMvc() .AddFluentActions(); services.AddAuthentication(o => { o.DefaultScheme = "AuthScheme"; }).AddScheme<AuthHandlerOptions, AuthHandler>("AuthScheme", (options) => { }); services.AddTransient<IUserService, UserService>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.EnvironmentName == "Development") { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseFluentActions( actions => { actions.Configure(config => { config.InheritingFrom<HelloWorldController>(); config.Append(action => action .UsingResult() .UsingResponse() .To(async (result, response) => { await Task.Delay(1); response.StatusCode = 418; return result is string ? $">> {result}" : result; }) ); }); actions .Route("/helloWorld", HttpMethod.Get) .To(() => "Hello World!"); actions .Route("/helloWorldAsync", HttpMethod.Get) .To(async () => { await Task.Delay(2000); return "Hello World Async!"; }); actions .RouteGet("/helloWorldAsyncWithDo") .DoAsync(async () => { await Task.Delay(2000); }) .To(() => "Hello World Async (with Do)!"); actions .RouteGet("/helloWorldFromParent") .UsingParent<HelloWorldController>() .To(parent => parent.HelloWorld()); actions .RouteGet("/helloWorldFromParentAsync") .InheritingFrom<HelloWorldController>() .UsingParent() .To(async parent => await parent.HelloWorldAsync()); actions .RouteGet("/hello") .UsingQueryStringParameter<string>("name") .ToView("~/Views/Plain/Hello.cshtml"); actions .Route("/helloWithAttributes", HttpMethod.Get) .WithCustomAttribute<AuthorizeAttribute>(new Type[0], new object[0], new string[] { "AuthenticationSchemes" }, new object[] { "AuthScheme" }) .To(() => "Hello With Attributes!"); actions .Route("/toHome", HttpMethod.Get) .ToMvcController<HomeController>() .ToMvcAction(homeController => homeController.Index()); actions .Route("/toAbout", HttpMethod.Get) .UsingViewBag() .UsingViewData() .UsingTempData() .Do((viewBag, viewData, tempData) => { viewData["ViewDataMessage"] = "ViewData message from fluent action."; tempData["TempDataMessage"] = "TempData message from fluent action."; viewBag.ViewBagMessage = "ViewBag message from fluent action."; }) .ToView("~/Views/Home/About.cshtml"); actions .Route("/toError", HttpMethod.Get) .UsingHttpContext() .To((httpContext) => new ErrorViewModel { RequestId = Activity.Current?.Id ?? httpContext.TraceIdentifier }) .ToView("~/Views/Shared/Error.cshtml"); actions .Route("/users", HttpMethod.Get, "List users.") .UsingService<IUserService>() .To(userService => userService.List()) .ToView("~/views/users/list.cshtml"); actions .Route("/api/users", HttpMethod.Get, "List users.") .UsingService<IUserService>() .To(userService => userService.List()); actions .RouteGet("/uploadFile", "Form to upload file.") .ToView("~/Views/Form/UploadFile.cshtml"); actions .RoutePost("/uploadFile", "Upload file.") .UsingFormFile("file") .To(file => $"Got {file.FileName}!"); actions .RouteGet("/uploadFiles", "Form to upload files.") .ToView("~/Views/Form/UploadFiles.cshtml"); actions .RoutePost("/uploadFiles", "Upload files.") .UsingFormFiles("files") .To(files => $"Got {files.Count()} n.o. files!"); actions .RouteGet("/submitWithAntiForgeryToken", "Form to submit with anti forgery token.") .ToView("~/Views/Form/SubmitWithAntiForgeryToken.cshtml"); actions .RoutePost("/submitWithAntiForgeryToken", "Submit with anti forgery token.") .ValidateAntiForgeryToken() .To(() => "Got submission!"); actions .RouteGet("/submitWithModelState", "Form to submit with model state.") .ToView("~/Views/Form/SubmitWithModelState.cshtml"); actions .RoutePost("/submitWithModelState", "Submit with model state.") .UsingModelState() .UsingForm<ModelStateFormModel>() .To((modelState, model) => modelState.IsValid ? "Model valid! :)" : "Model invalid :("); actions .RouteGet("/201") .UsingResponse() .To(response => { response.StatusCode = 201; return "Hello from 201!"; }); actions .RouteGet("/203") .UsingProperty<HttpResponse>("Response") .To(response => { response.StatusCode = 203; return "Hello from 203!"; }); actions .RouteGet("/request") .UsingRequest() .To(request => $"Hello from {request.Path}!"); actions .RouteGet("/helloProp") .UsingProperty<string>("HelloProp") .To(helloProp => helloProp); actions .RouteGet("/Home/Error") .WithCustomAttribute<ResponseCacheAttribute>( new Type[0], new object[0], new string[] { "Duration", "Location", "NoStore" }, new object[] { 0, ResponseCacheLocation.None, true }) .UsingHttpContext() .To(httpContext => new ErrorViewModel { RequestId = Activity.Current?.Id ?? httpContext.TraceIdentifier }) .ToView("~/Views/Shared/Error.cshtml"); actions .RouteGet("/Home/Error2") .ResponseCache( duration: 0, location: ResponseCacheLocation.None, noStore: false ) .UsingHttpContext() .To(httpContext => new ErrorViewModel { RequestId = Activity.Current?.Id ?? httpContext.TraceIdentifier }) .ToView("~/Views/Shared/Error.cshtml"); } ); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } public class AuthHandlerOptions : AuthenticationSchemeOptions { } public class AuthHandler : AuthenticationHandler<AuthHandlerOptions> { public AuthHandler(IOptionsMonitor<AuthHandlerOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) { } protected override Task<AuthenticateResult> HandleAuthenticateAsync() { return Task.FromResult(AuthenticateResult.Fail("Access denied.")); } } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/Builder/FluentActionDelegates.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using System; using System.Collections.Concurrent; using System.Reflection; using System.Reflection.Emit; namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core.Builder { public static class FluentActionDelegates { public static ConcurrentDictionary<string, Delegate> All = new ConcurrentDictionary<string, Delegate>(); public static string Add(Delegate value) { var key = Guid.NewGuid().ToString(); if (!All.TryAdd(key, value)) { throw new Exception($"Tried to add a fluent action delegate but key already exists in dictionary ({key})."); } return key; } public static FieldInfo FieldInfo => typeof(FluentActionDelegates).GetField("All"); public static MethodInfo MethodInfo => typeof(ConcurrentDictionary<string, Delegate>) .GetMethod("get_Item"); public static void PushDelegateOntoStack(ILGenerator ilGenerator, string delegateKey) { ilGenerator.Emit(OpCodes.Ldsfld, FieldInfo); ilGenerator.Emit(OpCodes.Ldstr, delegateKey); ilGenerator.Emit(OpCodes.Callvirt, MethodInfo); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestUtils.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.Utils; using Microsoft.AspNetCore.Mvc; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Xunit; using Moq; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.Extensions.Logging; using Xunit.Abstractions; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public static class BuilderTestUtils { public static void AssertConstantValuesOfBuiltController(FluentActionControllerDefinition builtController, FluentActionBase fluentAction) { var builtControllerTypeInfo = builtController.TypeInfo; Assert.Equal(fluentAction.RouteTemplate, builtController.RouteTemplate); Assert.Equal("HandlerAction", builtController.ActionName); Assert.Equal(builtControllerTypeInfo.Name, builtController.Id); Assert.Equal(builtControllerTypeInfo.Name, builtController.Name); Assert.Equal(fluentAction, builtController.FluentAction); Assert.StartsWith("FluentAction", builtControllerTypeInfo.Name); Assert.EndsWith("Controller", builtControllerTypeInfo.Name); } public static void BuildActionAndCompareToStaticAction( FluentActionBase fluentAction, Type staticControllerType, ILogger logger = null) { var builtController = BuildAction(fluentAction, logger); AssertConstantValuesOfBuiltController(builtController, fluentAction); CompareBuiltControllerToStaticController(builtController.TypeInfo.UnderlyingSystemType, staticControllerType); } public static void BuildActionAndCompareToStaticActionWithResult( FluentActionBase fluentAction, Type staticControllerType, object[] actionMethodArguments, ILogger logger = null) { var builtController = BuildAction(fluentAction, logger); AssertConstantValuesOfBuiltController(builtController, fluentAction); CompareBuiltControllerToStaticController(builtController.TypeInfo.UnderlyingSystemType, staticControllerType); CompareActionMethodResults(fluentAction, builtController, staticControllerType, actionMethodArguments); } public static void CompareActionMethodResults(FluentActionBase fluentAction, FluentActionControllerDefinition builtController, Type staticControllerType, object[] actionMethodArguments = null) { var resultsFromBuiltController = InvokeActionMethod(builtController.TypeInfo, actionMethodArguments); var resultsFromStaticController = InvokeActionMethod(staticControllerType.GetTypeInfo(), actionMethodArguments); if (resultsFromBuiltController == null) { throw new Exception($"Invoked action method returns null of built controller {builtController.Name}."); } if (resultsFromStaticController == null) { throw new Exception($"Invoked action method returns null of statically defined controller {staticControllerType.Name}."); } var returnTypeIsAsync = fluentAction.Definition.IsAsync; var returnType = returnTypeIsAsync ? typeof(Task<>).MakeGenericType(fluentAction.Definition.ReturnType) : fluentAction.Definition.ReturnType; if (!returnType.IsAssignableFrom(resultsFromBuiltController.GetType())) { throw new Exception($"Incorrect return type from invoked action method of built controller {builtController.Name} ({resultsFromBuiltController.GetType().Name} should be {fluentAction.Definition.ReturnType})."); } if (!returnType.IsAssignableFrom(resultsFromStaticController.GetType())) { throw new Exception($"Incorrect return type from invoked action method of statically defined controller {staticControllerType.Name} ({resultsFromStaticController.GetType().Name} should be {fluentAction.Definition.ReturnType})."); } if (returnTypeIsAsync) { resultsFromBuiltController = GetTaskResult(resultsFromBuiltController); resultsFromStaticController = GetTaskResult(resultsFromStaticController); } if (!IsEqual(resultsFromBuiltController, resultsFromStaticController)) { throw new Exception($"Results from invoked action methods does not match between built controller {builtController.Name} and statically defined controller {staticControllerType.Name} ({resultsFromBuiltController} vs {resultsFromStaticController})."); } } private static object GetTaskResult(object taskWithResult) { try { var genericArgumentType = taskWithResult.GetType().GetGenericArguments()[0]; var resultProperty = typeof(Task<>).MakeGenericType(genericArgumentType).GetProperty("Result"); return resultProperty.GetValue(taskWithResult); } catch (Exception exception) { throw new Exception("Could not get results of generic task.", exception); } } private static bool IsEqual(object value1, object value2) { var typeInfo = value1.GetType().GetTypeInfo(); if (typeInfo.IsPrimitive) { return value1.Equals(value2); } else if (value1 is string) { return value1 != null && value1.Equals(value2); } else if (value1 is IEnumerable) { return Enumerable.SequenceEqual((IEnumerable<object>)value1, (IEnumerable<object>)value2); } else if (value1 is ViewResult && value2 is ViewResult) { var viewResult1 = ((ViewResult)value1); var viewResult2 = ((ViewResult)value2); return viewResult1.ContentType == viewResult2.ContentType && viewResult1.StatusCode == viewResult2.StatusCode && viewResult1.ViewName == viewResult2.ViewName; } else if (value1 is PartialViewResult && value2 is PartialViewResult) { var viewResult1 = ((PartialViewResult)value1); var viewResult2 = ((PartialViewResult)value2); return viewResult1.ContentType == viewResult2.ContentType && viewResult1.StatusCode == viewResult2.StatusCode && viewResult1.ViewName == viewResult2.ViewName; } else if (value1 is ViewComponentResult && value2 is ViewComponentResult) { var viewResult1 = ((ViewComponentResult)value1); var viewResult2 = ((ViewComponentResult)value2); return viewResult1.ContentType == viewResult2.ContentType && viewResult1.StatusCode == viewResult2.StatusCode && viewResult1.ViewComponentName == viewResult2.ViewComponentName && viewResult1.ViewComponentType == viewResult2.ViewComponentType; } else { return value1 != null && value1.Equals(value2); } } private static object InvokeActionMethod(TypeInfo controllerTypeInfo, object[] arguments) { try { var instance = Activator.CreateInstance(controllerTypeInfo.UnderlyingSystemType); var mockedControllerContext = MockControllerContext(); var setControllerContextMethod = typeof(Controller).GetProperty("ControllerContext").GetSetMethod(); setControllerContextMethod.Invoke(instance, new object[] { mockedControllerContext }); var mockedTempDataProvider = Mock.Of<ITempDataProvider>(); var tempData = new TempDataDictionary(mockedControllerContext.HttpContext, mockedTempDataProvider); var setTempDataMethod = typeof(Controller).GetProperty("TempData").GetSetMethod(); setTempDataMethod.Invoke(instance, new object[] { tempData }); var method = controllerTypeInfo.GetMethod("HandlerAction"); return method.Invoke(instance, arguments); } catch (Exception exception) { throw new Exception($"Could not invoke action method for controller type {controllerTypeInfo.Name}.", exception); } } private static ControllerContext MockControllerContext() { var request = new Mock<HttpRequest>(); var headerDictionary = new HeaderDictionary(); var response = new Mock<HttpResponse>(); response.SetupGet(r => r.Headers).Returns(headerDictionary); var httpContext = new Mock<HttpContext>(); httpContext.SetupGet(a => a.Response).Returns(response.Object); httpContext.SetupGet(a => a.Request).Returns(request.Object); var actionContext = new ActionContext(httpContext.Object, new RouteData(), new ControllerActionDescriptor()); return new ControllerContext(actionContext); } public static void CompareBuiltControllerToStaticController(Type builtControllerType, Type staticControllerType) { var comparer = new TypeComparer(new TypeComparisonFeature[] { TypeComparisonFeature.ParentType, TypeComparisonFeature.HandlerActionMethod, }, new TypeComparerOptions()); var comparisonResult = comparer.Compare(builtControllerType, staticControllerType); if (!comparisonResult.CompleteMatch) { throw new Exception(string.Format( "Dynamically created controller {0} does not match statically defined controller {1}: {2}", staticControllerType.Name, builtControllerType.Name, string.Join(" ", comparisonResult.MismatchingFeaturesResults .Select(comparedFeaturesResult => comparedFeaturesResult.Message)))); } } public static FluentActionControllerDefinition BuildAction(FluentActionBase fluentAction, ILogger logger = null) { var controllerBuilder = new FluentActionControllerDefinitionBuilder(); return controllerBuilder.Build(fluentAction, logger); } } public class TestLogger : ILogger { private readonly ITestOutputHelper TestOutputHelper; public TestLogger(ITestOutputHelper testOutputHelper) { TestOutputHelper = testOutputHelper; } public IDisposable BeginScope<TState>(TState state) { throw new NotImplementedException(); } public bool IsEnabled(LogLevel logLevel) { throw new NotImplementedException(); } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { TestOutputHelper.WriteLine(formatter(state, exception)); } } } <|start_filename|>test/ExplicitlyImpl.FluentActions.Test.UnitTests/BuilderTestsWithFormValues.cs<|end_filename|> using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using ExplicitlyImpl.FluentActions.Test.UnitTests.Controllers; using System; using System.Threading.Tasks; using Xunit; namespace ExplicitlyImpl.FluentActions.Test.UnitTests { public class BuilderTestsWithFormValues { [Fact(DisplayName = "1 form value (string), returns string")] public void FluentControllerBuilder_FluentActionUsingFormValueReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingFormValue<string>("name") .To(name => $"Hello {name}!"), typeof(ControllerWithFormValueReturnsString), new object[] { "Charlie" }); } [Fact(DisplayName = "1 form value (string), returns string async")] public void FluentControllerBuilder_FluentActionUsingFormValueReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingFormValue<string>("name") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }), typeof(ControllerWithFormValueReturnsStringAsync), new object[] { "Charlie" }); } [Fact(DisplayName = "1 form value (string) with used default value, returns string")] public void FluentControllerBuilder_FluentActionUsingFormValueWithUsedDefaultValueReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingFormValue<string>("name", "Hanzel") .To(name => $"Hello {name}!"), typeof(ControllerWithFormValueAndDefaultValueReturnsString), new object[] { Type.Missing }); } [Fact(DisplayName = "1 form value (string) with used default value, returns string async")] public void FluentControllerBuilder_FluentActionUsingFormValueWithUsedDefaultValueReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingFormValue<string>("name", "Hanzel") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }), typeof(ControllerWithFormValueAndDefaultValueReturnsStringAsync), new object[] { Type.Missing }); } [Fact(DisplayName = "1 form value (string) with unused default value, returns string")] public void FluentControllerBuilder_FluentActionUsingFormValueWithUnusedDefaultValueReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingFormValue<string>("name", "Hanzel") .To(name => $"Hello {name}!"), typeof(ControllerWithFormValueAndDefaultValueReturnsString), new object[] { "Charlie" }); } [Fact(DisplayName = "1 form value (string) with unused default value, returns string async")] public void FluentControllerBuilder_FluentActionUsingFormValueWithUnusedDefaultValueReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingFormValue<string>("name", "Hanzel") .To(async name => { await Task.Delay(1); return $"Hello {name}!"; }), typeof(ControllerWithFormValueAndDefaultValueReturnsStringAsync), new object[] { "Charlie" }); } [Fact(DisplayName = "2 form values (string, identical), returns string")] public void FluentControllerBuilder_FluentActionUsingTwoIdenticalFormValuesReturnsString() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingFormValue<string>("name") .UsingFormValue<string>("name") .To((name1, name2) => $"Hello {name1}! I said hello {name2}!"), typeof(ControllerWithTwoIdenticalFormValuesReturnsString), new object[] { "Charlie" }); } [Fact(DisplayName = "2 form values (string, identical), returns string async")] public void FluentControllerBuilder_FluentActionUsingTwoIdenticalFormValuesReturnsStringAsync() { BuilderTestUtils.BuildActionAndCompareToStaticActionWithResult( new FluentAction("/route/url", HttpMethod.Get) .UsingFormValue<string>("name") .UsingFormValue<string>("name") .To(async (name1, name2) => { await Task.Delay(1); return $"Hello {name1}! I said hello {name2}!"; }), typeof(ControllerWithTwoIdenticalFormValuesReturnsStringAsync), new object[] { "Charlie" }); } } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/FluentActionControllerDefinitionBuilder.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. using ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core.Builder; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions { public class FluentActionControllerDefinitionBuilder { private const string ActionName = "HandlerAction"; public FluentActionControllerDefinition Build(FluentActionBase fluentAction, ILogger logger = null) { if (fluentAction == null) { throw new ArgumentNullException(nameof(fluentAction)); } var validationResult = ValidateFluentActionForBuilding(fluentAction); if (!validationResult.Valid) { throw new FluentActionValidationException($"Could not validate fluent action {fluentAction}: {validationResult}"); } if (fluentAction.Definition.IsMapRoute) { var handler = fluentAction.Definition.Handlers.First(); if (handler.Expression == null) { throw new ArgumentException( $"Missing action expression for {fluentAction}."); } if (!(handler.Expression.Body is MethodCallExpression)) { throw new ArgumentException( $"Expression for {fluentAction} must be a single method call expression."); } var method = ((MethodCallExpression)handler.Expression.Body).Method; var controllerTypeInfo = method.DeclaringType.GetTypeInfo(); if (!typeof(Controller).IsAssignableFrom(controllerTypeInfo.UnderlyingSystemType)) { throw new ArgumentException( $"Method call for {fluentAction} must come from a controller."); } var guid = Guid.NewGuid().ToString().Without("-"); return new FluentActionControllerDefinition() { Id = controllerTypeInfo.Name + "_" + method.Name + "_" + guid, Name = controllerTypeInfo.Name, ActionName = method.Name, FluentAction = fluentAction, TypeInfo = controllerTypeInfo }; } else { if ( ( fluentAction.Definition.GroupName != null || fluentAction.Definition.IgnoreApi == true ) && fluentAction.Definition.CustomAttributes.All(ca => ca.Type != typeof(ApiExplorerSettingsAttribute)) ) { var nonNullableProperties = new Dictionary<string, object>() { { "GroupName", fluentAction.Definition.GroupName }, { "IgnoreApi", fluentAction.Definition.IgnoreApi }, } .Where(pair => pair.Value != null) .ToList(); var apiExplorerSettingsAttributeType = typeof(ApiExplorerSettingsAttribute); fluentAction.Definition.CustomAttributes.Add(new FluentActionCustomAttribute { Type = apiExplorerSettingsAttributeType, Constructor = apiExplorerSettingsAttributeType.GetConstructor(new Type[0]), ConstructorArgs = new object[0], NamedProperties = nonNullableProperties.Select(p => apiExplorerSettingsAttributeType.GetProperty(p.Key)).ToArray(), PropertyValues = nonNullableProperties.Select(p => p.Value).ToArray(), NamedFields = new FieldInfo[0], FieldValues = new object[0], }); } try { var controllerTypeInfo = DefineControllerType(fluentAction.Definition, logger); return new FluentActionControllerDefinition() { Id = controllerTypeInfo.Name, Name = controllerTypeInfo.Name, ActionName = ActionName, FluentAction = fluentAction, TypeInfo = controllerTypeInfo }; } catch (Exception buildException) { throw new Exception($"Could not build controller type for {fluentAction}: {buildException.Message}", buildException); } } } private FluentActionValidationResult ValidateFluentActionForBuilding(FluentActionBase fluentAction) { if (fluentAction == null) { throw new ArgumentNullException(nameof(fluentAction)); } var validationResult = new FluentActionValidationResult { Valid = true, ValidationErrorMessages = new List<string>() }; if (fluentAction.Definition == null) { validationResult.AddValidationError($"{nameof(fluentAction.Definition)} is null."); return validationResult; } if (fluentAction.Definition.Handlers == null) { validationResult.AddValidationError($"{nameof(fluentAction.Definition.Handlers)} is null."); return validationResult; } var handlers = fluentAction.Definition.Handlers; if (!handlers.Any()) { validationResult.AddValidationError("At least one handler is required."); } foreach (var handlerWithNoReturnType in handlers.Where(handler => handler.Type != FluentActionHandlerType.Action && handler.ReturnType == null)) { validationResult.AddValidationError("Missing return type for handler."); } if (handlers.Any() && handlers.Last().Type == FluentActionHandlerType.Action) { validationResult.AddValidationError("Cannot end a fluent action with a Do statement."); } return validationResult; } public class FluentActionValidationResult { public FluentActionValidationResult() { ValidationErrorMessages = new List<string>(); } public bool Valid { get; set; } public IList<string> ValidationErrorMessages { get; set; } public void AddValidationError(string errorMessage) { Valid = false; ValidationErrorMessages.Add(errorMessage); } public override string ToString() { return Valid ? "This fluent action is valid" : string.Join(Environment.NewLine, ValidationErrorMessages); } } private static TypeInfo DefineControllerType( FluentActionDefinition fluentActionDefinition, ILogger logger = null) { if (fluentActionDefinition == null) { throw new ArgumentNullException(nameof(fluentActionDefinition)); } var guid = Guid.NewGuid().ToString().Replace("-", ""); var typeName = $"FluentAction{guid}Controller"; var controllerTypeBuilder = ControllerTypeBuilder.Create( "FluentActionAssembly", "FluentActionModule", typeName, fluentActionDefinition.ParentType); foreach (var customAttributeOnClass in fluentActionDefinition.CustomAttributesOnClass) { controllerTypeBuilder.SetCustomAttribute( customAttributeOnClass.Constructor, customAttributeOnClass.ConstructorArgs, customAttributeOnClass.NamedProperties, customAttributeOnClass.PropertyValues, customAttributeOnClass.NamedFields, customAttributeOnClass.FieldValues ); } ControllerMethodBuilder controllerMethodBuilder; if (AsyncStateMachineBuilderIsNeeded(fluentActionDefinition)) { controllerMethodBuilder = new ControllerMethodBuilderForFluentActionAsync(fluentActionDefinition, logger); } else { controllerMethodBuilder = new ControllerMethodBuilderForFluentAction(fluentActionDefinition); } controllerTypeBuilder.BuildMethod(ActionName, controllerMethodBuilder); return controllerTypeBuilder.CreateTypeInfo(); } public static bool AsyncStateMachineBuilderIsNeeded(FluentActionDefinition fluentActionDefinition) { // An AsyncStateMachineBuilder is not needed when there is only one handler invoking an async func return fluentActionDefinition.IsAsync && (fluentActionDefinition.Handlers.Count() > 1 || (fluentActionDefinition.Handlers.Count() == 1 && fluentActionDefinition.Handlers.First().Type != FluentActionHandlerType.Func)); } } } <|start_filename|>src/ExplicitlyImpl.AspNetCore.Mvc.FluentActions.Core/UsingDefinitions/UsingPropertyDefinition.cs<|end_filename|> // Licensed under the MIT License. See LICENSE file in the root of the solution for license information. namespace ExplicitlyImpl.AspNetCore.Mvc.FluentActions { public class FluentActionUsingPropertyDefinition : FluentActionUsingDefinition { public string PropertyName { get; set; } } } <|start_filename|>samples/MvcTemplate/Startup.cs<|end_filename|> using System; using System.Diagnostics; using ExplicitlyImpl.AspNetCore.Mvc.FluentActions; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using MvcTemplate.Models; namespace MvcTemplate { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().AddFluentActions(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.EnvironmentName == "Development") { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseCookiePolicy(); app.UseRouting(); app.UseFluentActions(actions => { actions .RouteGet("/") .ToView("~/Views/Home/Index.cshtml"); actions .RouteGet("/Home/Privacy") .ToView("~/Views/Home/Privacy.cshtml"); actions .RouteGet("/Home/Error") .WithCustomAttribute<ResponseCacheAttribute>( new Type[0], new object[0], new string[] { "Duration", "Location", "NoStore" }, new object[] { 0, ResponseCacheLocation.None, true } ) .UsingHttpContext() .To(httpContext => new ErrorViewModel { RequestId = Activity.Current?.Id ?? httpContext.TraceIdentifier }) .ToView("~/Views/Shared/Error.cshtml"); }); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } }
ExplicitlyImplicit/AspNetCore.Mvc.FluentActions
<|start_filename|>command_test.go<|end_filename|> package ipmsg import "testing" func TestMode(t *testing.T) { entry := BR_ENTRY if BR_ENTRY != entry.Mode() { t.Errorf("entry.Mode() contains not only mode part") } entry.SetOpt(SECRET) //fmt.Printf("entry %#08x\n", entry) //fmt.Printf("entry.Mode() %#08x\n", entry.Mode()) if BR_ENTRY != entry.Mode() { t.Errorf("entry.Mode() contains not only mode part") } } func TestModeName(t *testing.T) { entry := BR_ENTRY name := entry.ModeName() if "BR_ENTRY" != name { t.Errorf("entry.ModeName() is not 'BR_ENTRY'") } } func TestGet(t *testing.T) { entry := BR_ENTRY if entry.Get(BR_EXIT) { t.Errorf("BR_ENTRY contains BR_EXIT") } if !entry.Get(BR_ENTRY) { t.Errorf("BR_ENTRY does not contains BR_ENTRY") } } func TestSetOpt(t *testing.T) { entry := BR_ENTRY if entry.Get(SECRET) { t.Errorf("BR_ENTRY does contains SECRET before set it up") } //fmt.Printf("entry %#08x\n", entry) //fmt.Printf("SECRET %#08x\n", SECRET) entry.SetOpt(SECRET) //fmt.Printf("entry %#08x\n", entry) // output as hex digit like 'entry 0x00000001' // 'SECRET 0x00000200' // 'entry 0x00000201' if !entry.Get(BR_ENTRY) { t.Errorf("BR_ENTRY does not contains BR_ENTRY") } if !entry.Get(SECRET) { t.Errorf("BR_ENTRY does not contains SECRET after set it up") } } <|start_filename|>clientdata_test.go<|end_filename|> package ipmsg import ( "net" "testing" ) func TestParse(t *testing.T) { addr := new(net.UDPAddr) client := NewClientData("", addr) //client.Parse("1:2:user:host:3:4") client.Parse("1:2:user:host:3:nick\x00group\x00") if client.Version != 1 { t.Errorf("client.Version should be 1 but '%v'", client.Version) } if client.PacketNum != 2 { t.Errorf("client.PacketNum should be 2 but '%v'", client.PacketNum) } if client.Nick != "nick" { t.Errorf("client.Nick should be 'nick' but '%v'", client.Nick) } if client.Group != "group" { t.Errorf("client.Group should be 'group' but '%v'", client.Group) } if client.NickName() != "nick@group" { t.Errorf("client.NickName() should be 'nick@group' but '%v'", client.NickName) } } <|start_filename|>clientdata.go<|end_filename|> package ipmsg import ( "fmt" "net" "strconv" "strings" "time" ) type ClientData struct { Version int PacketNum int User string Host string Command Command Option string Nick string Group string Addr *net.UDPAddr ListAddr string Time time.Time PubKey string Encrypt bool Attach bool } func NewClientData(msg string, addr *net.UDPAddr) *ClientData { clientdata := &ClientData{ Addr: addr, } if msg != "" { clientdata.Parse(msg) } return clientdata } func (c *ClientData) String() string { str := fmt.Sprintf("%d:%d:%s:%s:%d:%s", c.Version, c.PacketNum, c.User, c.Host, c.Command, c.Option, ) return str } func (c *ClientData) Parse(msg string) { //pp.Println("msg=", msg) s := strings.SplitN(msg, ":", 6) //pp.Println(s) c.Version, _ = strconv.Atoi(s[0]) c.PacketNum, _ = strconv.Atoi(s[1]) c.User = s[2] c.Host = s[3] cmd, _ := strconv.Atoi(s[4]) c.Command = Command(cmd) c.Option = s[5] c.Time = time.Now() //pp.Println(c) c.UpdateNick() } func (c *ClientData) UpdateNick() { msg := c.Command mode := msg.Mode() if mode == BR_ENTRY || mode == ANSENTRY { if strings.Contains(c.Option, "\x00") { s := strings.SplitN(c.Option, "\x00", 2) c.Nick = s[0] c.Group = strings.Trim(s[1], "\x00") } if msg.Get(ENCRYPT) { c.Encrypt = true } } } func (c ClientData) NickName() string { nick := "noname" if c.Nick != "" { nick = c.Nick } else if c.User != "" { nick = c.User } group := "nogroup" if c.Group != "" { group = c.Group } else if c.Host != "" { group = c.Host } return fmt.Sprintf("%s@%s", nick, group) } func (c ClientData) Key() string { return fmt.Sprintf("%s@%s", c.User, c.Addr.String()) } <|start_filename|>eventhandler_test.go<|end_filename|> package ipmsg import ( "fmt" "testing" ) func func_BR_ENTRY(cd *ClientData, ipmsg *IPMSG) error { ipmsg.SendMSG(cd.Addr, ipmsg.Myinfo(), ANSENTRY) return nil } func func_SENDMSG(cd *ClientData, ipmsg *IPMSG) error { err := fmt.Errorf("DUMMY error") return err } func TestEventHander(t *testing.T) { conf := NewIPMSGConf() ipmsg, err := NewIPMSG(conf) if err != nil { t.Errorf("ipmsg error is not nil '%v'", err) } defer ipmsg.Close() addr, err := ipmsg.UDPAddr() if err != nil { t.Errorf("failed to resolve to UDP '%v'", err) } ev := NewEventHandler() ev.Regist(BR_ENTRY, func_BR_ENTRY) ev.Regist(SENDMSG, func_SENDMSG) clientdata := ipmsg.BuildData(addr, "hogehoge", BR_ENTRY) err = ev.Run(clientdata, ipmsg) if err != nil { t.Errorf("ev.Run(BR_ENTRY) failed with '%v'", err) } clientdata = ipmsg.BuildData(addr, "hogehoge", BR_EXIT) err = ev.Run(clientdata, ipmsg) if err != nil { t.Errorf("ev.Run(BR_EXIT) is not defined and should not fail") } clientdata = ipmsg.BuildData(addr, "hogehoge", SENDMSG) err = ev.Run(clientdata, ipmsg) if err == nil { t.Errorf("ev.Run(SENDMSG) should fail") } } func TestAddEventHandler(t *testing.T) { conf := NewIPMSGConf() laddr, err := getv4loopback() if err != nil { t.Errorf("loopback not found '%v'", err) } conf.Local = laddr ipmsg, err := NewIPMSG(conf) if err != nil { t.Errorf("ipmsg error is not nil '%v'", err) } defer ipmsg.Close() ev := NewEventHandler() ev.Regist(BR_ENTRY, func_BR_ENTRY) ev.String = "TestAddEventHandler" ipmsg.AddEventHandler(ev) addr, err := ipmsg.UDPAddr() if err != nil { t.Errorf("ipmsg.UDPAddr() has err '%v'", err) } err = ipmsg.SendMSG(addr, "TestAddEventHandler", BR_ENTRY) if err != nil { t.Errorf("ipmsg.SendMSG() has err '%v'", err) } recv, err := ipmsg.RecvMSG() if err != nil { t.Errorf("ipmsg.RecvMSG() has err '%v'", err) } if recv == nil { t.Errorf("recv is nil") } } <|start_filename|>command.go<|end_filename|> package ipmsg import "fmt" type Command int const ( // COMMAND NOOPERATION Command = 0x00000000 BR_ENTRY Command = 0x00000001 BR_EXIT Command = 0x00000002 ANSENTRY Command = 0x00000003 BR_ABSENCE Command = 0x00000004 BR_ISGETLIST Command = 0x00000010 OKGETLIST Command = 0x00000011 GETLIST Command = 0x00000012 ANSLIST Command = 0x00000013 BR_ISGETLIST2 Command = 0x00000018 SENDMSG Command = 0x00000020 RECVMSG Command = 0x00000021 READMSG Command = 0x00000030 DELMSG Command = 0x00000031 ANSREADMSG Command = 0x00000032 GETINFO Command = 0x00000040 SENDINFO Command = 0x00000041 GETABSENCEINFO Command = 0x00000050 SENDABSENCEINFO Command = 0x00000051 GETFILEDAT Command = 0x00000060 RELEASEFIL Command = 0x00000061 GETDIRFILE Command = 0x00000062 GETPUBKEY Command = 0x00000072 ANSPUBKEY Command = 0x00000073 // MODE MODE Command = 0x000000ff // OPTION //ABSENCE Command = 0x00000100 //SERVER Command = 0x00000200 //DIALUP Command = 0x00010000 SENDCHECK Command = 0x00000100 SECRET Command = 0x00000200 BROADCAST Command = 0x00000400 MULTICAST Command = 0x00000800 NOPOPUP Command = 0x00001000 AUTORET Command = 0x00002000 RETRY Command = 0x00004000 PASSWORD Command = <PASSWORD> NOLOG Command = 0x00020000 NEWMUTI Command = 0x00040000 NOADDLIST Command = 0x00080000 READCHECK Command = 0x00100000 FILEATTACH Command = 0x00200000 ENCRYPT Command = 0x00400000 ) func (msg Command) Mode() Command { if 0 == msg { return 0 } return msg & MODE } func (msg Command) ModeName() string { mode := msg.Mode() str := fmt.Sprint(mode) return str } func (msg Command) Get(flg Command) bool { return msg&flg != 0 } func (msg *Command) SetOpt(flg Command) { *msg |= flg } <|start_filename|>ipmsg.go<|end_filename|> package ipmsg import ( "bytes" "errors" "fmt" "net" "time" ) type IPMSG struct { ClientData ClientData Conn *net.UDPConn Conf *IPMSGConfig Handlers []*EventHandler PacketNum int } type IPMSGConfig struct { NickName string GroupName string UserName string HostName string Port int Local string } const ( DefaultPort int = 2425 Buflen int = 65535 ) func NewIPMSGConf() *IPMSGConfig { conf := &IPMSGConfig{ Port: DefaultPort, } return conf } func NewIPMSG(conf *IPMSGConfig) (*IPMSG, error) { ipmsg := &IPMSG{ PacketNum: 0, } ipmsg.Conf = conf // UDP server service := fmt.Sprintf("%v:%d", conf.Local, conf.Port) //fmt.Println("service =", service) udpAddr, err := net.ResolveUDPAddr("udp", service) if err != nil { return ipmsg, err } conn, err := net.ListenUDP("udp", udpAddr) if err != nil { return ipmsg, err } ipmsg.Conn = conn return ipmsg, err } func (ipmsg *IPMSG) Close() error { conn := ipmsg.Conn if conn == nil { err := errors.New("Conn is not defined") return err } err := conn.Close() return err } func (ipmsg *IPMSG) BuildData(addr *net.UDPAddr, msg string, cmd Command) *ClientData { conf := ipmsg.Conf clientdata := NewClientData("", addr) clientdata.Version = 1 clientdata.PacketNum = ipmsg.GetNewPacketNum() clientdata.User = conf.UserName clientdata.Host = conf.HostName clientdata.Command = cmd clientdata.Option = msg return clientdata } func (ipmsg *IPMSG) SendMSG(addr *net.UDPAddr, msg string, cmd Command) error { clientdata := ipmsg.BuildData(addr, msg, cmd) conn := ipmsg.Conn _, err := conn.WriteToUDP([]byte(clientdata.String()), addr) if err != nil { return err } return nil } func (ipmsg *IPMSG) RecvMSG() (*ClientData, error) { var buf [Buflen]byte conn := ipmsg.Conn _, addr, err := conn.ReadFromUDP(buf[0:]) if err != nil { return nil, err } trimmed := bytes.Trim(buf[:], "\x00") clientdata := NewClientData(string(trimmed[:]), addr) handlers := ipmsg.Handlers for _, v := range handlers { err := v.Run(clientdata, ipmsg) if err != nil { return clientdata, err } } return clientdata, nil } // convert net.Addr to net.UDPAddr func (ipmsg *IPMSG) UDPAddr() (*net.UDPAddr, error) { conn := ipmsg.Conn if conn == nil { err := errors.New("Conn is not defined") return nil, err } addr := conn.LocalAddr() network := addr.Network() str := addr.String() //fmt.Println("str =", str) udpAddr, err := net.ResolveUDPAddr(network, str) return udpAddr, err } func (ipmsg *IPMSG) AddEventHandler(ev *EventHandler) { sl := ipmsg.Handlers sl = append(sl, ev) ipmsg.Handlers = sl } func (ipmsg *IPMSG) GetNewPacketNum() int { ipmsg.PacketNum++ return int(time.Now().Unix()) + ipmsg.PacketNum } func (ipmsg *IPMSG) Myinfo() string { conf := ipmsg.Conf return fmt.Sprintf("%v\x00%v\x00", conf.NickName, conf.GroupName) } <|start_filename|>command_string.go<|end_filename|> // generated by stringer -type Command command.go; DO NOT EDIT package ipmsg import "fmt" const _Command_name = "NOOPERATIONBR_ENTRYBR_EXITANSENTRYBR_ABSENCEBR_ISGETLISTOKGETLISTGETLISTANSLISTBR_ISGETLIST2SENDMSGRECVMSGREADMSGDELMSGANSREADMSGGETINFOSENDINFOGETABSENCEINFOSENDABSENCEINFOGETFILEDATRELEASEFILGETDIRFILEGETPUBKEYANSPUBKEYMODESENDCHECKSECRETBROADCASTMULTICASTNOPOPUPAUTORETRETRYPASSWORDNOLOGNEWMUTINOADDLISTREADCHECKFILEATTACHENCRYPT" var _Command_map = map[Command]string{ 0: _Command_name[0:11], 1: _Command_name[11:19], 2: _Command_name[19:26], 3: _Command_name[26:34], 4: _Command_name[34:44], 16: _Command_name[44:56], 17: _Command_name[56:65], 18: _Command_name[65:72], 19: _Command_name[72:79], 24: _Command_name[79:92], 32: _Command_name[92:99], 33: _Command_name[99:106], 48: _Command_name[106:113], 49: _Command_name[113:119], 50: _Command_name[119:129], 64: _Command_name[129:136], 65: _Command_name[136:144], 80: _Command_name[144:158], 81: _Command_name[158:173], 96: _Command_name[173:183], 97: _Command_name[183:193], 98: _Command_name[193:203], 114: _Command_name[203:212], 115: _Command_name[212:221], 255: _Command_name[221:225], 256: _Command_name[225:234], 512: _Command_name[234:240], 1024: _Command_name[240:249], 2048: _Command_name[249:258], 4096: _Command_name[258:265], 8192: _Command_name[265:272], 16384: _Command_name[272:277], 32768: _Command_name[277:285], 131072: _Command_name[285:290], 262144: _Command_name[290:297], 524288: _Command_name[297:306], 1048576: _Command_name[306:315], 2097152: _Command_name[315:325], 4194304: _Command_name[325:332], } func (i Command) String() string { if str, ok := _Command_map[i]; ok { return str } return fmt.Sprintf("Command(%d)", i) } <|start_filename|>eventhandler.go<|end_filename|> package ipmsg import "fmt" type EvFunc func(cd *ClientData, ipmsg *IPMSG) error type EventHandler struct { String string Handlers map[Command]EvFunc Debug bool } func NewEventHandler() *EventHandler { ev := &EventHandler{ Handlers: make(map[Command]EvFunc), } return ev } func (ev *EventHandler) Regist(cmd Command, evfunc EvFunc) { handlers := ev.Handlers handlers[cmd] = evfunc } func (ev *EventHandler) Run(cd *ClientData, ipmsg *IPMSG) error { if ev.Debug { ev.RunDebug(cd) } cmd := cd.Command.Mode() evfunc := ev.Handlers[cmd] if evfunc == nil { // just do nothing when handler is undefined return nil } else { return (evfunc(cd, ipmsg)) } } func (ev *EventHandler) RunDebug(cd *ClientData) { cmdstr := cd.Command.Mode().String() fmt.Println("EventHandler.RunDebug cmdstr=", cmdstr) fmt.Println("EventHandler.RunDebug key=", cd.Key()) } //func (ev EventHandler) Run(cd *ClientData, ipmsg *IPMSG) error { // cmdstr := cd.Command.String() // v := reflect.ValueOf(&ev) // method := v.MethodByName(cmdstr) // if !method.IsValid() { // err := fmt.Errorf("method for Command(%v) not defined", cmdstr) // return err // } // in := []reflect.Value{reflect.ValueOf(cd), reflect.ValueOf(ipmsg)} // err := method.Call(in)[0].Interface() // // XXX only works if you sure about the return value is always type(error) // if err == nil { // return nil // } // return err.(error) // //reflect.ValueOf(&ev).MethodByName(cmdstr).Call(in) //} // //func (ev *EventHandler) BR_ENTRY(cd *ClientData, ipmsg *IPMSG) error { // ipmsg.SendMSG(cd.Addr, ipmsg.Myinfo(), ANSENTRY) // return nil //} <|start_filename|>ipmsg_test.go<|end_filename|> package ipmsg import ( "errors" "net" "testing" ) func TestGetNewPackNum(t *testing.T) { conf := NewIPMSGConf() ipmsg, err := NewIPMSG(conf) if err != nil { t.Errorf("ipmsg error is not nil '%v'", err) } defer ipmsg.Close() if 0 != ipmsg.PacketNum { t.Errorf("ipmsg.PacketNum should be 0 but '%v'", ipmsg.PacketNum) } num := ipmsg.GetNewPacketNum() if num == 0 { t.Errorf("ipmsg.GetNewPacketNum returns 0") } if 1 != ipmsg.PacketNum { t.Errorf("ipmsg.PacketNum should be 1 but '%v'", ipmsg.PacketNum) } } func getv4loopback() (string, error) { ifaces, err := net.Interfaces() if err != nil { return "", err } for _, iface := range ifaces { if iface.Flags&net.FlagLoopback != 0 { addrs, err := iface.Addrs() if err != nil { return "", err } for _, addr := range addrs { var ip net.IP switch v := addr.(type) { case *net.IPNet: ip = v.IP case *net.IPAddr: ip = v.IP } ip = ip.To4() if ip == nil { continue } if ip.IsLoopback() { return ip.String(), nil } } } } return "", errors.New("you do not have loopback?") } func TestNewIPMSG(t *testing.T) { conf := NewIPMSGConf() conf.NickName = "testuser" conf.GroupName = "testgroup" conf.UserName = "testuser" conf.HostName = "testhost" laddr, err := getv4loopback() if err != nil { t.Errorf("loopback not found '%v'", err) } conf.Local = laddr client, err := NewIPMSG(conf) if err != nil { t.Errorf("client error is not nil '%v'", err) } defer client.Close() serverConf := NewIPMSGConf() serverConf.Port = 12425 serverConf.Local = laddr server, err := NewIPMSG(serverConf) if err != nil { t.Errorf("server error is not nil '%v'", err) } defer server.Close() saddr, err := server.UDPAddr() if err != nil { t.Errorf("failed to resolve to UDP '%v'", err) } // client sends message to server testmsg := "hogehoge" err = client.SendMSG(saddr, testmsg, BR_ENTRY) if err != nil { t.Errorf("client.SendMSG return error '%v'", err) } // server receives message from client received, err := server.RecvMSG() //pp.Println("received = ", received) if err != nil { t.Errorf("server.RecvMSG return error '%v'", err) } if testmsg != received.Option { //if testmsg != received { t.Errorf("received is not much to sent msg") } //pp.Println("received = ", received) }
FlowingSPDG/go-ipmsg
<|start_filename|>src/store/store.cpp<|end_filename|> // Copyright (c) 2018-present Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <store.h> #include <boost/filesystem.hpp> #include <sys/vfs.h> #include <boost/lexical_cast.hpp> #include <boost/scoped_array.hpp> #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> #include <gflags/gflags.h> #include "rocksdb/utilities/memory_util.h" #include "mut_table_key.h" #include "closure.h" #include "my_raft_log_storage.h" #include "log_entry_reader.h" #include "rocksdb/cache.h" #include "rocksdb/utilities/write_batch_with_index.h" #include "concurrency.h" #include "mut_table_key.h" #include "my_raft_log_storage.h" //#include <jemalloc/jemalloc.h> namespace baikaldb { DECLARE_int64(store_heart_beat_interval_us); DECLARE_int32(balance_periodicity); DECLARE_string(stable_uri); DECLARE_string(snapshot_uri); DEFINE_int64(reverse_merge_interval_us, 2 * 1000 * 1000, "reverse_merge_interval(2 s)"); DEFINE_int64(ttl_remove_interval_s, 24 * 3600, "ttl_remove_interval_s(24h)"); DEFINE_int64(delay_remove_region_interval_s, 600, "delay_remove_region_interval"); //DEFINE_int32(update_status_interval_us, 2 * 1000 * 1000, "update_status_interval(2 s)"); DEFINE_int32(store_port, 8110, "Server port"); DEFINE_string(db_path, "./rocks_db", "rocksdb path"); DEFINE_string(resource_tag, "", "resource tag"); DEFINE_int32(update_used_size_interval_us, 10 * 1000 * 1000, "update used size interval (10 s)"); DEFINE_int32(init_region_concurrency, 10, "init region concurrency when start"); DEFINE_int32(split_threshold , 150, "split_threshold, defalut: 150% * region_size / 100"); DEFINE_int64(min_split_lines, 200000, "min_split_lines, protected when wrong param put in table"); DEFINE_int64(flush_region_interval_us, 10 * 60 * 1000 * 1000LL, "flush region interval, defalut(10 min)"); DEFINE_int64(transaction_clear_interval_ms, 5000LL, "transaction clear interval, defalut(5s)"); DEFINE_int64(binlog_timeout_check_ms, 10 * 1000LL, "binlog timeout check interval, defalut(10s)"); DEFINE_int64(binlog_fake_ms, 30 * 1000LL, "fake binlog interval, defalut(30s)"); DECLARE_int64(flush_memtable_interval_us); DEFINE_int32(max_split_concurrency, 2, "max split region concurrency, default:2"); DEFINE_int64(none_region_merge_interval_us, 5 * 60 * 1000 * 1000LL, "none region merge interval, defalut(5 min)"); DEFINE_int64(region_delay_remove_timeout_s, 3600 * 24LL, "region_delay_remove_time_s, defalut(1d)"); DEFINE_bool(use_approximate_size_to_split, false, "if approximate_size > 512M, then split"); DEFINE_int64(gen_tso_interval_us, 500 * 1000LL, "gen_tso_interval_us, defalut(500ms)"); DEFINE_int64(gen_tso_count, 100, "gen_tso_count, defalut(500)"); DEFINE_int64(rocks_cf_flush_remove_range_times, 10, "rocks_cf_flush_remove_range_times, defalut(10)"); DEFINE_int64(rocks_force_flush_max_wals, 100, "rocks_force_flush_max_wals, defalut(100)"); Store::~Store() { bthread_mutex_destroy(&_param_mutex); } int Store::init_before_listen(std::vector<std::int64_t>& init_region_ids) { butil::EndPoint addr; addr.ip = butil::my_ip(); addr.port = FLAGS_store_port; _address = endpoint2str(addr).c_str(); if (_meta_server_interact.init() != 0) { DB_FATAL("meta server interact init fail"); return -1; } if (_tso_server_interact.init() != 0) { DB_FATAL("tso server interact init fail"); return -1; } int ret = get_physical_room(_address, _physical_room); if (ret < 0) { DB_FATAL("get physical room fail"); return -1; } boost::trim(FLAGS_resource_tag); _resource_tag = FLAGS_resource_tag; // init rocksdb handler _rocksdb = RocksWrapper::get_instance(); if (!_rocksdb) { DB_FATAL("create rocksdb handler failed"); return -1; } int32_t res = _rocksdb->init(FLAGS_db_path); if (res != 0) { DB_FATAL("rocksdb init failed: code:%d", res); return -1; } // init val _factory = SchemaFactory::get_instance(); std::vector<rocksdb::Transaction*> recovered_txns; _rocksdb->get_db()->GetAllPreparedTransactions(&recovered_txns); if (recovered_txns.empty()) { DB_WARNING("has no prepared transcation"); _has_prepared_tran = false; } for (auto txn : recovered_txns) { std::string txn_name = txn->GetName().c_str(); std::vector<std::string> split_vec; boost::split(split_vec, txn_name, boost::is_any_of("_")); int64_t region_id = boost::lexical_cast<int64_t>(split_vec[0]); uint64_t txn_id = boost::lexical_cast<uint64_t>(split_vec[1]); prepared_txns[region_id].insert(txn_id); DB_WARNING("rollback transaction, txn: %s, region_id: %ld, txn_id: %lu", txn->GetName().c_str(), region_id, txn_id); txn->Rollback(); delete txn; } recovered_txns.clear(); _meta_writer = MetaWriter::get_instance(); _meta_writer->init(_rocksdb, _rocksdb->get_meta_info_handle()); LogEntryReader* reader = LogEntryReader::get_instance(); reader->init(_rocksdb, _rocksdb->get_raft_log_handle()); pb::StoreHeartBeatRequest request; pb::StoreHeartBeatResponse response; //1、构造心跳请求, 重启时的心跳包除了实例信息外,其他都为空 construct_heart_beat_request(request); DB_WARNING("heart beat request:%s when init store", request.ShortDebugString().c_str()); TimeCost step_time_cost; //2、发送请求 if (_meta_server_interact.send_request("store_heartbeat", request, response) == 0) { DB_WARNING("heart beat response:%s when init store", response.ShortDebugString().c_str()); //同步处理心跳, 重启拉到的第一个心跳包只有schema信息 _factory->update_tables_double_buffer_sync(response.schema_change_info()); } else { DB_FATAL("send heart beat request to meta server fail"); return -1; } int64_t heartbeat_process_time = step_time_cost.get_time(); step_time_cost.reset(); DB_WARNING("get schema info from meta server success"); //系统重启之前有哪些reigon std::vector<pb::RegionInfo> region_infos; ret = _meta_writer->parse_region_infos(region_infos); if (ret < 0) { DB_FATAL("read region_infos from rocksdb fail"); return ret; } for (auto& region_info : region_infos) { DB_WARNING("region_info:%s when init store", region_info.ShortDebugString().c_str()); int64_t region_id = region_info.region_id(); if (region_info.version() == 0) { DB_WARNING("region_id: %ld version is 0, dropped. region_info: %s", region_id, region_info.ShortDebugString().c_str() ); RegionControl::clear_all_infos_for_region(region_id); continue; } //construct region braft::GroupId groupId(std::string("region_") + boost::lexical_cast<std::string>(region_id)); butil::EndPoint addr; str2endpoint(_address.c_str(), &addr); braft::PeerId peerId(addr, 0); //重启的region初始化时peer要为空 region_info.clear_peers(); SmartRegion region(new(std::nothrow) Region(_rocksdb, _factory, _address, groupId, peerId, region_info, region_id)); if (region == NULL) { DB_FATAL("new region fail. mem accolate fail. region_info:%s", region_info.ShortDebugString().c_str()); return -1; } //重启的region跟新建的region或者正常运行情况下的region有两点区别 //1、重启region的on_snapshot_load不受并发数的限制 //2、重启region的on_snapshot_load不加载sst文件 region->set_restart(true); set_region(region); init_region_ids.push_back(region_id); } int64_t new_region_process_time = step_time_cost.get_time(); ret = _meta_writer->parse_doing_snapshot(doing_snapshot_regions); if (ret < 0) { DB_FATAL("read doing snapshot regions from rocksdb fail"); return ret; } else { for (auto region_id : doing_snapshot_regions) { DB_WARNING("region_id: %ld is doing snapshot load when store stop", region_id); } } start_db_statistics(); DB_WARNING("store init_before_listen success heartbeat_process_time:%ld new_region_process_time:%ld", heartbeat_process_time, new_region_process_time); return 0; } int Store::init_after_listen(const std::vector<int64_t>& init_region_ids) { //开始上报心跳线程 _heart_beat_bth.run([this]() {heart_beat_thread();}); TimeCost step_time_cost; ConcurrencyBthread init_bth(FLAGS_init_region_concurrency); //从本地的rocksdb中恢复该机器上有哪些实例 for (auto& region_id : init_region_ids) { auto init_call = [this, region_id]() { SmartRegion region = get_region(region_id); if (region == NULL) { DB_FATAL("no region is store, region_id: %ld", region_id); return; } //region raft node init int ret = region->init(false, 0); if (ret < 0) { DB_FATAL("region init fail when store init, region_id: %ld", region_id); return; } }; init_bth.run(init_call); } init_bth.join(); _split_check_bth.run([this]() {whether_split_thread();}); _merge_bth.run([this]() {reverse_merge_thread();}); _ttl_bth.run([this]() {ttl_remove_thread();}); _delay_remove_region_bth.run([this]() {delay_remove_region_thread();}); _flush_bth.run([this]() {flush_memtable_thread();}); _snapshot_bth.run([this]() {snapshot_thread();}); _txn_clear_bth.run([this]() {txn_clear_thread();}); _binlog_timeout_check_bth.run([this]() {binlog_timeout_check_thread();}); _binlog_fake_bth.run([this]() {binlog_fake_thread();}); _has_prepared_tran = true; prepared_txns.clear(); doing_snapshot_regions.clear(); DB_WARNING("store init_after_listen success, init success init_region_time:%ld", step_time_cost.get_time()); return 0; } void Store::init_region(google::protobuf::RpcController* controller, const pb::InitRegion* request, pb::StoreRes* response, google::protobuf::Closure* done) { TimeCost time_cost; brpc::ClosureGuard done_guard(done); brpc::Controller* cntl =static_cast<brpc::Controller*>(controller); if (!_factory) { cntl->SetFailed(EINVAL, "record encoder not set"); return; } if (_shutdown) { DB_WARNING("store has entered shutdown"); response->set_errcode(pb::INPUT_PARAM_ERROR); response->set_errmsg("store has shutdown"); return; } uint64_t log_id = 0; if (cntl->has_log_id()) { log_id = cntl->log_id(); } const pb::RegionInfo& region_info = request->region_info(); int64_t table_id = region_info.table_id(); int64_t region_id = region_info.region_id(); const auto& remote_side_tmp = butil::endpoint2str(cntl->remote_side()); const char* remote_side = remote_side_tmp.c_str(); //只限制addpeer if (_rocksdb->is_any_stall() && request->snapshot_times() == 0) { DB_WARNING("addpeer rocksdb is stall, log_id%ld, remote_side:%s", log_id, remote_side); response->set_errcode(pb::CANNOT_ADD_PEER); response->set_errmsg("rocksdb is stall"); return; } //新增table信息 if (!_factory->exist_tableid(table_id)) { if (request->has_schema_info()) { update_schema_info(request->schema_info()); } else { DB_FATAL("table info missing when add region, table_id:%lu, region_id: %ld, log_id:%lu", table_id, region_info.region_id(), log_id); response->set_errcode(pb::INPUT_PARAM_ERROR); response->set_errmsg("table info is missing when add region"); return; } } auto orgin_region = get_region(region_id); // 已经软删,遇到需要新建就马上删除让位 if (orgin_region != nullptr && orgin_region->removed()) { drop_region_from_store(region_id, false); } orgin_region = get_region(region_id); if (orgin_region != nullptr) { //自动化处理,直接删除这个region DB_FATAL("region id has existed when add region, region_id: %ld, log_id:%lu, remote_side:%s", region_id, log_id, remote_side); response->set_errcode(pb::REGION_ALREADY_EXIST); response->set_errmsg("region id has existed and drop fail when init region"); return; } //construct region braft::GroupId groupId(std::string("region_") + boost::lexical_cast<std::string>(region_id)); butil::EndPoint addr; if (str2endpoint(_address.c_str(), &addr) != 0) { DB_FATAL("address:%s transfer to endpoint fail", _address.c_str()); response->set_errcode(pb::INTERNAL_ERROR); response->set_errmsg("address is illegal"); return; } braft::PeerId peerId(addr, 0); SmartRegion region(new(std::nothrow) Region(_rocksdb, _factory, _address, groupId, peerId, request->region_info(), region_id)); if (region == NULL) { DB_FATAL("new region fail. mem accolate fail. logid:%lu", log_id); response->set_errcode(pb::INTERNAL_ERROR); response->set_errmsg("new region fail"); return; } DB_WARNING("new region_info:%s. logid:%lu remote_side: %s", request->ShortDebugString().c_str(), log_id, remote_side); //写内存 set_region(region); //region raft node init Concurrency::get_instance()->init_region_concurrency.increase_wait(); int ret = region->init(true, request->snapshot_times()); Concurrency::get_instance()->init_region_concurrency.decrease_broadcast(); if (ret < 0) { //删除该region相关的全部信息 RegionControl::clear_all_infos_for_region(region_id); erase_region(region_id); DB_FATAL("region init fail when add region, region_id: %ld, log_id:%lu", region_id, log_id); response->set_errcode(pb::INTERNAL_ERROR); response->set_errmsg("region init fail when add region"); return; } response->set_errcode(pb::SUCCESS); response->set_errmsg("add region success"); if (request->region_info().version() == 0) { Bthread bth(&BTHREAD_ATTR_SMALL); std::function<void()> check_region_legal_fun = [this, region_id] () { check_region_legal_complete(region_id);}; bth.run(check_region_legal_fun); DB_WARNING("init region verison is 0, should check region legal. region_id: %ld, log_id: %lu", region_id, log_id); } DB_WARNING("init region sucess, region_id: %ld, log_id:%lu, time_cost:%ld remote_side: %s", region_id, log_id, time_cost.get_time(), remote_side); } void Store::region_raft_control(google::protobuf::RpcController* controller, const pb::RaftControlRequest* request, pb::RaftControlResponse* response, google::protobuf::Closure* done) { brpc::ClosureGuard done_guard(done); brpc::Controller* cntl = static_cast<brpc::Controller*>(controller); uint64_t log_id = 0; if (cntl->has_log_id()) { log_id = cntl->log_id(); } response->set_region_id(request->region_id()); SmartRegion region = get_region(request->region_id()); if (region == NULL) { response->set_region_id(request->region_id()); response->set_errcode(pb::INPUT_PARAM_ERROR); response->set_errmsg("region_id not exist in store"); DB_FATAL("region id:%lu not exist in store, logid:%lu", request->region_id(), log_id); return; } region->raft_control(controller, request, response, done_guard.release()); } void Store::health_check(google::protobuf::RpcController* controller, const pb::HealthCheck* request, pb::StoreRes* response, google::protobuf::Closure* done) { brpc::ClosureGuard done_guard(done); response->set_errcode(pb::SUCCESS); } void Store::query(google::protobuf::RpcController* controller, const pb::StoreReq* request, pb::StoreRes* response, google::protobuf::Closure* done) { bthread_usleep(20); brpc::ClosureGuard done_guard(done); brpc::Controller* cntl = static_cast<brpc::Controller*>(controller); uint64_t log_id = 0; const auto& remote_side_tmp = butil::endpoint2str(cntl->remote_side()); const char* remote_side = remote_side_tmp.c_str(); if (cntl->has_log_id()) { log_id = cntl->log_id(); } //DB_WARNING("region_id: %ld before get_region, logid:%lu, remote_side: %s", request->region_id(), log_id, remote_side); SmartRegion region = get_region(request->region_id()); if (region == nullptr || region->removed()) { response->set_errcode(pb::REGION_NOT_EXIST); response->set_errmsg("region_id not exist in store"); DB_FATAL("region_id: %ld not exist in store, logid:%lu, remote_side: %s", request->region_id(), log_id, remote_side); return; } region->query(controller, request, response, done_guard.release()); } void Store::query_binlog(google::protobuf::RpcController* controller, const pb::StoreReq* request, pb::StoreRes* response, google::protobuf::Closure* done) { bthread_usleep(20); brpc::ClosureGuard done_guard(done); brpc::Controller* cntl = static_cast<brpc::Controller*>(controller); uint64_t log_id = 0; const auto& remote_side_tmp = butil::endpoint2str(cntl->remote_side()); const char* remote_side = remote_side_tmp.c_str(); if (cntl->has_log_id()) { log_id = cntl->log_id(); } //DB_WARNING("region_id: %ld before get_region, logid:%lu, remote_side: %s", request->region_id(), log_id, remote_side); SmartRegion region = get_region(request->region_id()); if (region == nullptr || region->removed()) { response->set_errcode(pb::REGION_NOT_EXIST); response->set_errmsg("region_id not exist in store"); DB_WARNING("region_id: %ld not exist in store, logid:%lu, remote_side: %s", request->region_id(), log_id, remote_side); return; } region->query_binlog(controller, request, response, done_guard.release()); } void Store::remove_region(google::protobuf::RpcController* controller, const pb::RemoveRegion* request, pb::StoreRes* response, google::protobuf::Closure* done) { brpc::ClosureGuard done_guard(done); brpc::Controller* cntl = static_cast<brpc::Controller*>(controller); const auto& remote_side_tmp = butil::endpoint2str(cntl->remote_side()); const char* remote_side = remote_side_tmp.c_str(); DB_WARNING("receive remove region request, remote_side:%s, request:%s", butil::endpoint2str(cntl->remote_side()).c_str(), request->ShortDebugString().c_str()); if (_shutdown) { DB_WARNING("store has entered shutdown"); response->set_errcode(pb::INPUT_PARAM_ERROR); response->set_errmsg("store has shutdown"); return; } if (!request->has_force() || request->force() != true) { DB_WARNING("drop region fail, input param error, region_id: %ld", request->region_id()); response->set_errcode(pb::INPUT_PARAM_ERROR); response->set_errmsg("input param error"); return; } DB_WARNING("call remove region_id: %ld, need_delay_drop:%d", request->region_id(), request->need_delay_drop()); drop_region_from_store(request->region_id(), request->need_delay_drop()); response->set_errcode(pb::SUCCESS); } void Store::restore_region(google::protobuf::RpcController* controller, const baikaldb::pb::RegionIds* request, pb::StoreRes* response, google::protobuf::Closure* done) { brpc::ClosureGuard done_guard(done); response->set_errcode(pb::SUCCESS); response->set_errmsg("success"); TimeCost cost; auto call = [](SmartRegion region) { // 需要等table info才能init成功 region->wait_table_info(); // 恢复相当于重启region region->set_restart(true); region->init(false, 0); region->set_removed(false); DB_WARNING("restore region_id: %ld success ", region->get_region_id()); }; if (request->region_ids_size() == 0) { traverse_copy_region_map([request, call](const SmartRegion& region) { if (region->removed()) { if (!request->has_table_id()) { call(region); } else if (request->table_id() == region->get_table_id()) { call(region); } } }); } else { for (auto region_id : request->region_ids()) { auto region = get_region(region_id); if (region != nullptr && region->removed()) { call(region); } } } DB_WARNING("restore region success cost:%ld", cost.get_time()); } void Store::add_peer(google::protobuf::RpcController* controller, const pb::AddPeer* request, pb::StoreRes* response, google::protobuf::Closure* done) { brpc::ClosureGuard done_guard(done); response->set_errcode(pb::SUCCESS); response->set_errmsg("success"); if (_shutdown) { DB_WARNING("store has entered shutdown"); response->set_errcode(pb::INPUT_PARAM_ERROR); response->set_errmsg("store has shutdown"); return; } SmartRegion region = get_region(request->region_id()); if (region == nullptr || region->removed()) { DB_FATAL("region_id: %ld not exist, may be removed", request->region_id()); response->set_errcode(pb::REGION_NOT_EXIST); response->set_errmsg("region not exist"); return; } region->add_peer(request, response, done_guard.release()); } void Store::get_applied_index(google::protobuf::RpcController* controller, const baikaldb::pb::GetAppliedIndex* request, pb::StoreRes* response, google::protobuf::Closure* done) { brpc::ClosureGuard done_guard(done); response->set_errcode(pb::SUCCESS); response->set_errmsg("success"); SmartRegion region = get_region(request->region_id()); if (region == nullptr) { DB_FATAL("region_id: %ld not exist, may be removed", request->region_id()); response->set_errcode(pb::REGION_NOT_EXIST); response->set_errmsg("region not exist"); return; } response->set_region_status(region->region_status()); response->set_applied_index(region->get_log_index()); response->mutable_region_raft_stat()->set_applied_index(region->get_log_index()); response->mutable_region_raft_stat()->set_snapshot_data_size(region->snapshot_data_size()); response->mutable_region_raft_stat()->set_snapshot_meta_size(region->snapshot_meta_size()); response->set_leader(butil::endpoint2str(region->get_leader()).c_str()); } void Store::compact_region(google::protobuf::RpcController* controller, const baikaldb::pb::RegionIds* request, pb::StoreRes* response, google::protobuf::Closure* done) { brpc::ClosureGuard done_guard(done); response->set_errcode(pb::SUCCESS); response->set_errmsg("success"); TimeCost cost; if (request->region_ids_size() == 0) { auto cf = _rocksdb->get_data_handle(); if (request->compact_raft_log()) { cf = _rocksdb->get_raft_log_handle(); } else if (request->has_compact_type()) { auto type = request->compact_type(); if (type == 1) { // data_cf cf = _rocksdb->get_data_handle(); } else if (type == 2) { // meta_cf cf = _rocksdb->get_meta_info_handle(); } else { // raft_log_cf cf = _rocksdb->get_raft_log_handle(); } } rocksdb::CompactRangeOptions compact_options; compact_options.exclusive_manual_compaction = false; auto res = _rocksdb->compact_range(compact_options, cf, nullptr, nullptr); if (!res.ok()) { DB_WARNING("compact_range error: code=%d, msg=%s", res.code(), res.ToString().c_str()); } } else { for (auto region_id : request->region_ids()) { RegionControl::compact_data(region_id); } } DB_WARNING("compact_db cost:%ld", cost.get_time()); } void Store::snapshot_region(google::protobuf::RpcController* controller, const baikaldb::pb::RegionIds* request, pb::StoreRes* response, google::protobuf::Closure* done) { brpc::ClosureGuard done_guard(done); response->set_errcode(pb::SUCCESS); response->set_errmsg("success"); std::vector<int64_t> region_ids; if (request->region_ids_size() == 0) { traverse_region_map([&region_ids](const SmartRegion& region) { region_ids.push_back(region->get_region_id()); }); } else { for (auto region_id : request->region_ids()) { region_ids.push_back(region_id); } } auto snapshot_fun = [this, region_ids]() { for (auto& region_id: region_ids) { SmartRegion region = get_region(region_id); if (region == nullptr) { DB_FATAL("region_id: %ld not exist, may be removed", region_id); } else { region->do_snapshot(); } } DB_WARNING("all region sync_do_snapshot finish"); }; Bthread bth(&BTHREAD_ATTR_SMALL); bth.run(snapshot_fun); } void Store::query_region(google::protobuf::RpcController* controller, const baikaldb::pb::RegionIds* request, pb::StoreRes* response, google::protobuf::Closure* done) { brpc::ClosureGuard done_guard(done); response->set_errcode(pb::SUCCESS); response->set_errmsg("success"); std::map<int64_t, std::string> id_leader_map; response->set_leader(_address); if (request->region_ids_size() == 0) { traverse_region_map([&id_leader_map](const SmartRegion& region) { id_leader_map[region->get_region_id()] = butil::endpoint2str(region->get_leader()).c_str(); }); for (auto& id_pair : id_leader_map) { auto ptr_region_leader = response->add_region_leaders(); ptr_region_leader->set_region_id(id_pair.first); ptr_region_leader->set_leader(id_pair.second); } response->set_region_count(response->region_leaders_size()); return; } for (auto region_id : request->region_ids()) { SmartRegion region = get_region(region_id); if (region == nullptr) { DB_FATAL("region_id: %ld not exist, may be removed", region_id); } else { auto ptr_region_info = response->add_regions(); region->copy_region(ptr_region_info); ptr_region_info->set_leader(butil::endpoint2str(region->get_leader()).c_str()); ptr_region_info->set_log_index(region->get_log_index()); } } response->set_region_count(response->regions_size()); } void Store::query_illegal_region(google::protobuf::RpcController* controller, const baikaldb::pb::RegionIds* request, pb::StoreRes* response, google::protobuf::Closure* done) { brpc::ClosureGuard done_guard(done); response->set_errcode(pb::SUCCESS); response->set_errmsg("success"); std::map<int64_t, std::string> id_leader_map; response->set_leader(_address); if (request->region_ids_size() == 0) { traverse_region_map([&id_leader_map](const SmartRegion& region) { if (region->get_leader().ip == butil::IP_ANY) { id_leader_map[region->get_region_id()] = butil::endpoint2str(region->get_leader()).c_str(); } }); for (auto& id_pair : id_leader_map) { auto ptr_region_leader = response->add_region_leaders(); ptr_region_leader->set_region_id(id_pair.first); ptr_region_leader->set_leader(id_pair.second); } response->set_region_count(response->region_leaders_size()); return; } for (auto region_id : request->region_ids()) { SmartRegion region = get_region(region_id); if (region == nullptr) { DB_FATAL("region_id: %ld not exist, may be removed", region_id); } else { if (region->get_leader().ip == butil::IP_ANY) { auto ptr_region_info = response->add_regions(); region->copy_region(ptr_region_info); ptr_region_info->set_leader(butil::endpoint2str(region->get_leader()).c_str()); } } } response->set_region_count(response->regions_size()); } //store上报心跳到meta_server void Store::heart_beat_thread() { //static int64_t count = 0; while (!_shutdown) { send_heart_beat(); bthread_usleep_fast_shutdown(FLAGS_store_heart_beat_interval_us, _shutdown); } } void Store::send_heart_beat() { pb::StoreHeartBeatRequest request; pb::StoreHeartBeatResponse response; //1、构造心跳请求 heart_beat_count << 1; construct_heart_beat_request(request); print_heartbeat_info(request); //2、发送请求 if (_meta_server_interact.send_request("store_heartbeat", request, response) != 0) { DB_WARNING("send heart beat request to meta server fail"); } else { //处理心跳 process_heart_beat_response(response); } _last_heart_time.reset(); heart_beat_count << -1; DB_WARNING("heart beat"); } void Store::reverse_merge_thread() { while (!_shutdown) { TimeCost cost; traverse_copy_region_map([](const SmartRegion& region) { if (!region->is_binlog_region()) { region->reverse_merge(); } }); bthread_usleep_fast_shutdown(FLAGS_reverse_merge_interval_us, _shutdown); } } void Store::ttl_remove_thread() { while (!_shutdown) { bthread_usleep_fast_shutdown(FLAGS_ttl_remove_interval_s * 1000 * 1000, _shutdown); if (_shutdown) { return; } traverse_copy_region_map([](const SmartRegion& region) { region->ttl_remove_expired_data(); }); } } void Store::delay_remove_region_thread() { while (!_shutdown) { bthread_usleep_fast_shutdown(FLAGS_delay_remove_region_interval_s * 1000 * 1000, _shutdown); if (_shutdown) { return; } traverse_copy_region_map([this](const SmartRegion& region) { if (region->removed() && //加个随机数,删除均匀些 region->removed_time_cost() > (FLAGS_region_delay_remove_timeout_s + (int64_t)(butil::fast_rand() % FLAGS_region_delay_remove_timeout_s)) * 1000 * 1000LL) { region->shutdown(); region->join(); int64_t drop_region_id = region->get_region_id(); DB_WARNING("region node remove permanently, region_id: %ld", drop_region_id); RegionControl::clear_all_infos_for_region(drop_region_id); erase_region(drop_region_id); } }); } } void Store::flush_memtable_thread() { static bvar::Status<uint64_t> rocksdb_num_snapshots("rocksdb_num_snapshots", 0); static bvar::Status<int64_t> rocksdb_snapshot_difftime("rocksdb_snapshot_difftime", 0); static bvar::Status<uint64_t> rocksdb_num_wals("rocksdb_num_wals", 0); uint64_t last_file_number = 0; while (!_shutdown) { bthread_usleep_fast_shutdown(FLAGS_flush_memtable_interval_us, _shutdown); if (_shutdown) { return; } uint64_t num_snapshots = 0; _rocksdb->get_db()->GetAggregatedIntProperty("rocksdb.num-snapshots", &num_snapshots); rocksdb_num_snapshots.set_value(num_snapshots); uint64_t snapshot_time = 0; _rocksdb->get_db()->GetAggregatedIntProperty("rocksdb.oldest-snapshot-time", &snapshot_time); if (snapshot_time > 0) { rocksdb_snapshot_difftime.set_value((int64_t)time(NULL) - (int64_t)snapshot_time); } rocksdb::VectorLogPtr vec; _rocksdb->get_db()->GetSortedWalFiles(vec); rocksdb_num_wals.set_value(vec.size()); // wal 个数超过阈值100强制flush所有cf bool force_flush = vec.size() > FLAGS_rocks_force_flush_max_wals ? true : false; int64_t raft_count = RocksWrapper::raft_cf_remove_range_count.load(); int64_t data_count = RocksWrapper::data_cf_remove_range_count.load(); int64_t mata_count = RocksWrapper::mata_cf_remove_range_count.load(); if (force_flush || raft_count > FLAGS_rocks_cf_flush_remove_range_times) { RocksWrapper::raft_cf_remove_range_count = 0; rocksdb::FlushOptions flush_options; auto status = _rocksdb->flush(flush_options, _rocksdb->get_raft_log_handle()); if (!status.ok()) { DB_WARNING("flush log_cf to rocksdb fail, err_msg:%s", status.ToString().c_str()); } } if (force_flush || data_count > FLAGS_rocks_cf_flush_remove_range_times) { RocksWrapper::data_cf_remove_range_count = 0; rocksdb::FlushOptions flush_options; auto status = _rocksdb->flush(flush_options, _rocksdb->get_data_handle()); if (!status.ok()) { DB_WARNING("flush data to rocksdb fail, err_msg:%s", status.ToString().c_str()); } } //last_file_number发生变化,data cf有新的flush数据需要flush meta,gc wal if (force_flush || mata_count > FLAGS_rocks_cf_flush_remove_range_times || last_file_number != _rocksdb->flush_file_number()) { last_file_number = _rocksdb->flush_file_number(); RocksWrapper::mata_cf_remove_range_count = 0; rocksdb::FlushOptions flush_options; auto status = _rocksdb->flush(flush_options, _rocksdb->get_meta_info_handle()); if (!status.ok()) { DB_WARNING("flush mata to rocksdb fail, err_msg:%s", status.ToString().c_str()); } } /* status = _rocksdb->flush(flush_options, _rocksdb->get_data_handle()); if (!status.ok()) { DB_WARNING("flush data to rocksdb fail, err_msg:%s", status.ToString().c_str()); } status = _rocksdb->flush(flush_options, _rocksdb->get_raft_log_handle()); if (!status.ok()) { DB_WARNING("flush log_cf to rocksdb fail, err_msg:%s", status.ToString().c_str()); } status = _rocksdb->flush(flush_options, _rocksdb->get_bin_log_handle()); if (!status.ok()) { DB_WARNING("flush bin_log_cf to rocksdb fail, err_msg:%s", status.ToString().c_str()); } */ } } void Store::snapshot_thread() { BthreadCond concurrency_cond(-5); // -n就是并发跑n个bthread while (!_shutdown) { traverse_copy_region_map([&concurrency_cond](const SmartRegion& region) { concurrency_cond.increase_wait(); SnapshotClosure* done = new SnapshotClosure(concurrency_cond, region.get()); // 每个region自己会控制是否做snapshot region->snapshot(done); }); bthread_usleep_fast_shutdown(10 * 1000 * 1000, _shutdown); } // 等待全部snapshot都结束 concurrency_cond.wait(-5); } void Store::txn_clear_thread() { while (!_shutdown) { traverse_copy_region_map([](const SmartRegion& region) { // clear prepared and expired transactions region->clear_transactions(); }); bthread_usleep_fast_shutdown(FLAGS_transaction_clear_interval_ms * 1000, _shutdown); } } void Store::binlog_timeout_check_thread() { while (!_shutdown) { traverse_copy_region_map([this](const SmartRegion& region) { if (region->is_binlog_region()) { int64_t ts = get_tso(); if (ts < 0) { return; } region->binlog_timeout_check(ts); } }); bthread_usleep_fast_shutdown(FLAGS_binlog_timeout_check_ms * 1000, _shutdown); } } void Store::binlog_fake_thread() { while (!_shutdown) { BthreadCond cond(-40); traverse_copy_region_map([this, &cond](const SmartRegion& region) { if (region->is_binlog_region() && region->is_leader()) { int64_t ts = get_tso(); if (ts < 0) { return; } region->binlog_fake(ts, cond); } }); cond.wait(-40); bthread_usleep_fast_shutdown(FLAGS_binlog_fake_ms * 1000, _shutdown); } } int64_t Store::get_tso() { _get_tso_cond.increase_wait(); ON_SCOPE_EXIT(([this]() { _get_tso_cond.decrease_broadcast(); })); if (tso_physical != 0 && tso_logical != 0 && tso_count > 0 && gen_tso_time.get_time() < FLAGS_gen_tso_interval_us) { return (tso_physical << tso::logical_bits) + tso_logical + FLAGS_gen_tso_count - (tso_count--); } pb::TsoRequest request; pb::TsoResponse response; request.set_op_type(pb::OP_GEN_TSO); request.set_count(FLAGS_gen_tso_count); //发送请求,收到响应 if (_tso_server_interact.send_request("tso_service", request, response) == 0) { //处理响应 if (response.errcode() != pb::SUCCESS) { DB_FATAL("store get tso fail request:%s, response:%s", request.ShortDebugString().c_str(), response.ShortDebugString().c_str()); return -1; } DB_WARNING("store get tso request:%s, response:%s", request.ShortDebugString().c_str(), response.ShortDebugString().c_str()); } else { DB_WARNING("store get tso request:%s, response:%s", request.ShortDebugString().c_str(), response.ShortDebugString().c_str()); return -1; } gen_tso_time.reset(); tso_count = FLAGS_gen_tso_count; tso_physical = response.start_timestamp().physical(); tso_logical = response.start_timestamp().logical(); return (tso_physical << tso::logical_bits) + tso_logical + FLAGS_gen_tso_count - (tso_count--); } int64_t Store::get_last_commit_ts() { pb::TsoRequest request; pb::TsoResponse response; request.set_op_type(pb::OP_GEN_TSO); request.set_count(1); //发送请求,收到响应 if (_tso_server_interact.send_request("tso_service", request, response) == 0) { //处理响应 if (response.errcode() != pb::SUCCESS) { DB_FATAL("store get tso fail request:%s, response:%s", request.ShortDebugString().c_str(), response.ShortDebugString().c_str()); return -1; } DB_WARNING("store get tso request:%s, response:%s", request.ShortDebugString().c_str(), response.ShortDebugString().c_str()); } else { DB_WARNING("store get tso request:%s, response:%s", request.ShortDebugString().c_str(), response.ShortDebugString().c_str()); return -1; } gen_tso_time.reset(); auto& tso = response.start_timestamp(); int64_t timestamp = (tso.physical() << tso::logical_bits) + tso.logical(); return timestamp; } void Store::process_merge_request(int64_t table_id, int64_t region_id) { //请求meta查询空region的下一个region //构造请求 pb::MetaManagerRequest request; pb::MetaManagerResponse response; SmartRegion ptr_region = get_region(region_id); if (ptr_region == NULL) { return; } request.set_op_type(pb::OP_MERGE_REGION); pb::RegionMergeRequest* region_merge = request.mutable_region_merge(); region_merge->set_src_region_id(region_id); region_merge->set_src_start_key(ptr_region->get_start_key()); region_merge->set_src_end_key(ptr_region->get_end_key()); region_merge->set_table_id(table_id); //发送请求,收到响应 if (_meta_server_interact.send_request("meta_manager", request, response) == 0) { //处理响应 if (response.errcode() != pb::SUCCESS) { DB_FATAL("store process merge fail request:%s, response:%s", request.ShortDebugString().c_str(), response.ShortDebugString().c_str()); return; } SmartRegion region = get_region(region_id); if (region == NULL) { DB_FATAL("region id:%ld has been deleted", region_id); return; } DB_WARNING("store process merge request:%s, response:%s", request.ShortDebugString().c_str(), response.ShortDebugString().c_str()); region->start_process_merge(response.merge_response()); } else { DB_WARNING("store process merge request:%s, response:%s", request.ShortDebugString().c_str(), response.ShortDebugString().c_str()); DB_FATAL("send merge request to metaserver fail"); } } void Store::process_split_request(int64_t table_id, int64_t region_id, bool tail_split, std::string split_key) { ++_split_num; //构造请求 pb::MetaManagerRequest request; pb::MetaManagerResponse response; request.set_op_type(pb::OP_SPLIT_REGION); pb::RegionSplitRequest* region_split = request.mutable_region_split(); region_split->set_region_id(region_id); region_split->set_split_key(split_key); region_split->set_new_instance(_address); region_split->set_resource_tag(_resource_tag); region_split->set_table_id(table_id); if (tail_split) { region_split->set_tail_split(true); } //发送请求,收到响应 if (_meta_server_interact.send_request("meta_manager", request, response) == 0) { //处理响应 SmartRegion region = get_region(region_id); if (region == NULL) { DB_FATAL("region id:%ld has been deleted", region_id); sub_split_num(); return; } DB_WARNING("store process split request:%s, response:%s", request.ShortDebugString().c_str(), response.ShortDebugString().c_str()); region->start_process_split(response.split_response(), tail_split, split_key); } else { sub_split_num(); DB_WARNING("store process split request:%s, response:%s", request.ShortDebugString().c_str(), response.ShortDebugString().c_str()); DB_FATAL("send split request to metaserver fail"); } } void Store::reset_region_status(int64_t region_id) { SmartRegion region = get_region(region_id); if (region == NULL) { DB_FATAL("region id not existed region_id: %ld", region_id); return; } DB_WARNING("region status was set in store, region_id: %ld", region_id); region->reset_region_status(); } int64_t Store::get_split_index_for_region(int64_t region_id) { SmartRegion region = get_region(region_id); if (region == NULL) { DB_WARNING("region id not existed region_id: %ld", region_id); return INT64_MAX; } return region->get_split_index(); } void Store::set_can_add_peer_for_region(int64_t region_id) { SmartRegion region = get_region(region_id); if (region == NULL) { DB_FATAL("region id not existed region_id: %ld", region_id); return; } region->set_can_add_peer(); } void Store::print_properties(const std::string& name) { auto db = _rocksdb->get_db(); uint64_t value_data = 0; uint64_t value_log = 0; db->GetIntProperty(_rocksdb->get_data_handle(), name, &value_data); db->GetIntProperty(_rocksdb->get_raft_log_handle(), name, &value_log); SELF_TRACE("db_property: %s, data_cf:%lu, log_cf:%lu", name.c_str(), value_data, value_log); } void Store::monitor_memory() { /* std::vector<rocksdb::DB*> dbs; std::unordered_set<const rocksdb::Cache*> cache_set; std::map<rocksdb::MemoryUtil::UsageType, uint64_t> usage_by_type; auto db = _rocksdb->get_db(); dbs.push_back(db); // GetCachePointers(db, cache_set); // DB_WARNING("cache_set size: %lu", cache_set.size()); cache_set.insert(_rocksdb->get_cache()); rocksdb::MemoryUtil::GetApproximateMemoryUsageByType(dbs, cache_set, &usage_by_type); for (auto kv : usage_by_type) { SELF_TRACE("momery type: %d, size: %lu, %lu", kv.first, kv.second, _rocksdb->get_cache()->GetPinnedUsage()); } */ } void Store::whether_split_thread() { static int64_t count = 0; (void)count; while (!_shutdown) { std::vector<int64_t> region_ids; traverse_region_map([&region_ids](const SmartRegion& region) { region_ids.push_back(region->get_region_id()); }); boost::scoped_array<uint64_t> region_sizes(new(std::nothrow)uint64_t[region_ids.size()]); int ret = get_used_size_per_region(region_ids, region_sizes.get()); if (ret != 0) { DB_WARNING("get used size per region fail"); return; } for (size_t i = 0; i < region_ids.size(); ++i) { SmartRegion ptr_region = get_region(region_ids[i]); if (ptr_region == NULL) { continue; } if (ptr_region->is_binlog_region()) { continue; } if (ptr_region->removed()) { DB_WARNING("region_id: %ld has be removed", region_ids[i]); continue; } //分区region,不分裂、不merge //if (ptr_region->get_partition_num() > 1) { // DB_NOTICE("partition region %ld not split.", region_ids[i]); // continue; //} //设置计算存储分离开关 ptr_region->set_separate_switch(_factory->get_separate_switch(ptr_region->get_table_id())); //update region_used_size ptr_region->set_used_size(region_sizes[i]); //判断是否需要分裂,分裂的标准是used_size > 1.5 * region_capacity int64_t region_capacity = 10000000; int ret = _factory->get_region_capacity(ptr_region->get_global_index_id(), region_capacity); if (ret != 0) { DB_FATAL("table info not exist, region_id: %ld", region_ids[i]); continue; } region_capacity = std::max(FLAGS_min_split_lines, region_capacity); //DB_WARNING("region_id: %ld, split_capacity: %ld", region_ids[i], region_capacity); std::string split_key; //如果是尾部分 if (ptr_region->is_leader() && ptr_region->get_status() == pb::IDLE && _split_num.load() < FLAGS_max_split_concurrency) { if (ptr_region->is_tail() && ptr_region->get_num_table_lines() >= region_capacity) { process_split_request(ptr_region->get_global_index_id(), region_ids[i], true, split_key); continue; } else if (!ptr_region->is_tail() && ptr_region->get_num_table_lines() >= FLAGS_split_threshold * region_capacity / 100) { if (0 != ptr_region->get_split_key(split_key)) { DB_WARNING("get_split_key failed: region=%ld", region_ids[i]); continue; } process_split_request(ptr_region->get_global_index_id(), region_ids[i], false, split_key); continue; } else if (ptr_region->can_use_approximate_split()) { DB_WARNING("start split by approx size:%ld region_id: %ld num_table_lines:%ld", region_sizes[i], region_ids[i], ptr_region->get_num_table_lines()); //split或add peer后,预估的空间有段时间不够准确 //由于已经有num_table_lines判断,region_sizes判断不需要太及时 //TODO split可以根据前后版本的大小进一步预估,add peer可以根据发来的sst预估 if (ptr_region->is_tail()) { process_split_request(ptr_region->get_global_index_id(), region_ids[i], true, split_key); continue; } else { if (0 != ptr_region->get_split_key(split_key)) { DB_WARNING("get_split_key failed: region=%ld", region_ids[i]); continue; } process_split_request(ptr_region->get_global_index_id(), region_ids[i], false, split_key); continue; } } } if (!_factory->get_merge_switch(ptr_region->get_table_id())) { continue; } //简化特殊处理,首尾region不merge if (ptr_region->is_tail() || ptr_region->is_head()) { continue; } //空region超过两个心跳周期之后触发删除,主从均执行 if (ptr_region->empty()) { if (ptr_region->get_status() == pb::IDLE && ptr_region->get_timecost() > FLAGS_store_heart_beat_interval_us * 2) { //删除region DB_WARNING("region:%ld has been merged, drop it", region_ids[i]); //空region通过心跳上报,由meta触发删除,不在此进行 //drop_region_from_store(region_ids[i]); } continue; } //region无数据,超过5min触发回收 if (ptr_region->is_leader() && ptr_region->get_num_table_lines() == 0 && ptr_region->get_status() == pb::IDLE) { if (ptr_region->get_log_index() != ptr_region->get_log_index_lastcycle()) { ptr_region->reset_log_index_lastcycle(); DB_WARNING("region:%ld is none, log_index:%ld reset time", region_ids[i], ptr_region->get_log_index()); continue; } if (ptr_region->get_log_index() == ptr_region->get_log_index_lastcycle() && ptr_region->get_lastcycle_timecost() > FLAGS_none_region_merge_interval_us) { DB_WARNING("region:%ld is none, log_index:%ld, process merge", region_ids[i], ptr_region->get_log_index()); process_merge_request(ptr_region->get_global_index_id(), region_ids[i]); continue; } } } SELF_TRACE("upate used size count:%ld", ++count); bthread_usleep_fast_shutdown(FLAGS_update_used_size_interval_us, _shutdown); } } void Store::start_db_statistics() { Bthread bth(&BTHREAD_ATTR_SMALL); std::function<void()> dump_options = [this] () { while (!_shutdown) { TimeCost cost; auto db_options = get_db()->get_db_options(); std::string str = db_options.statistics->ToString(); std::vector<std::string> items; boost::split(items, str, boost::is_any_of("\n")); for (auto& item : items) { (void)item; SELF_TRACE("statistics: %s", item.c_str()); } monitor_memory(); print_properties("rocksdb.num-immutable-mem-table"); print_properties("rocksdb.mem-table-flush-pending"); print_properties("rocksdb.compaction-pending"); print_properties("rocksdb.cur-size-active-mem-table"); print_properties("rocksdb.cur-size-all-mem-tables"); print_properties("rocksdb.size-all-mem-tables"); print_properties("rocksdb.estimate-table-readers-mem"); print_properties("rocksdb.num-snapshots"); print_properties("rocksdb.oldest-snapshot-time"); print_properties("rocksdb.is-write-stopped"); print_properties("rocksdb.num-live-versions"); print_properties("rocksdb.estimate-pending-compaction-bytes"); SELF_TRACE("get properties cost: %ld", cost.get_time()); bthread_usleep(10 * 1000 * 1000); } }; bth.run(dump_options); } int Store::get_used_size_per_region(const std::vector<int64_t>& region_ids, uint64_t* region_sizes) { std::vector<rocksdb::Range> ranges; std::vector<uint64_t> approx_sizes; for (size_t i = 0; i < region_ids.size(); ++i) { auto region = get_region(region_ids[i]); if (region == NULL) { DB_WARNING("region_id: %ld not exist", region_ids[i]); region_sizes[i] = 0; continue; } region_sizes[i] = region->get_approx_size(); if (region_sizes[i] == UINT64_MAX) { ranges.emplace_back(region->get_rocksdb_range()); approx_sizes.emplace_back(UINT64_MAX); } } auto data_cf = _rocksdb->get_data_handle(); if (nullptr == data_cf) { return -1; } if (!ranges.empty() && approx_sizes.size() == ranges.size()) { _rocksdb->get_db()->GetApproximateSizes(data_cf, &ranges[0], ranges.size(), &approx_sizes[0], uint8_t(3)); size_t idx = 0; for (size_t i = 0; i < region_ids.size(); ++i) { if (region_sizes[i] == UINT64_MAX && idx < approx_sizes.size()) { auto region = get_region(region_ids[i]); if (region == NULL) { DB_WARNING("region_id: %ld not exist", region_ids[i]); region_sizes[i] = 0; continue; } region_sizes[i] = approx_sizes[idx++]; region->set_approx_size(region_sizes[i]); DB_NOTICE("region_id: %ld, size:%lu region_num_line:%ld", region_ids[i], region_sizes[i], region->get_num_table_lines()); } } } return 0; } void Store::update_schema_info(const pb::SchemaInfo& request) { //锁住的是update_table和table_info_mapping, table_info锁的位置不能改 _factory->update_table(request); } void Store::check_region_legal_complete(int64_t region_id) { DB_WARNING("start to check whether split or add peer complete, region_id: %ld", region_id); auto region = get_region(region_id); if (region == NULL) { DB_WARNING("region_id: %ld not exist", region_id); return; } //检查并且置为失败 if (region->check_region_legal_complete()) { DB_WARNING("split or add_peer complete. region_id: %ld", region_id); } else { DB_WARNING("split or add_peer not complete, timeout. region_id: %ld", region_id); drop_region_from_store(region_id, false); } } void Store::construct_heart_beat_request(pb::StoreHeartBeatRequest& request) { static int64_t count = 0; request.set_need_leader_balance(false); ++count; bool need_peer_balance = false; if (count % FLAGS_balance_periodicity == 0) { request.set_need_leader_balance(true); } // init_before_listen时会上报一次心跳 // 重启后第二次心跳或长时间心跳未上报时上报peer信息,保证无效region尽快shutdown if (count == 2 || _last_heart_time.get_time() > FLAGS_store_heart_beat_interval_us * 4) { need_peer_balance = true; } if (count % FLAGS_balance_periodicity == (FLAGS_balance_periodicity / 2)) { request.set_need_peer_balance(true); need_peer_balance = true; } //构造instance信息 pb::InstanceInfo* instance_info = request.mutable_instance_info(); instance_info->set_address(_address); instance_info->set_physical_room(_physical_room); instance_info->set_resource_tag(_resource_tag); // 读取硬盘参数 struct statfs sfs; statfs(FLAGS_db_path.c_str(), &sfs); int64_t disk_capacity = sfs.f_blocks * sfs.f_bsize; int64_t left_size = sfs.f_bavail * sfs.f_bsize; _disk_total.set_value(disk_capacity); _disk_used.set_value(disk_capacity - left_size); instance_info->set_capacity(disk_capacity); instance_info->set_used_size(disk_capacity - left_size); #ifdef BAIKALDB_REVISION instance_info->set_version(BAIKALDB_REVISION); #endif //构造schema version信息 std::unordered_map<int64_t, int64_t> table_id_version_map; _factory->get_all_table_version(table_id_version_map); for (auto table_info : table_id_version_map) { pb::SchemaHeartBeat* schema = request.add_schema_infos(); schema->set_table_id(table_info.first); schema->set_version(table_info.second); } //记录正在doing的table_id,所有region不上报ddlwork进展 std::set<int64_t> ddl_wait_doing_table_ids; traverse_copy_region_map([&ddl_wait_doing_table_ids](const SmartRegion& region) { if (region->is_wait_ddl()) { ddl_wait_doing_table_ids.insert(region->get_global_index_id()); } }); //构造所有region的version信息 traverse_copy_region_map([&request, need_peer_balance, &ddl_wait_doing_table_ids](const SmartRegion& region) { region->construct_heart_beat_request(request, need_peer_balance, ddl_wait_doing_table_ids); }); } void Store::process_heart_beat_response(const pb::StoreHeartBeatResponse& response) { { BAIDU_SCOPED_LOCK(_param_mutex); for (auto& param : response.instance_params()) { for (auto& item : param.params()) { _param_map[item.key()] = item.value(); } } // 更新到qos param for (auto& iter : _param_map) { update_param(iter.first, iter.second); } } for (auto& schema_info : response.schema_change_info()) { update_schema_info(schema_info); } for (auto& add_peer_request : response.add_peers()) { SmartRegion region = get_region(add_peer_request.region_id()); if (region == NULL) { DB_FATAL("region_id: %ld not exist, may be removed", add_peer_request.region_id()); continue; } region->add_peer(add_peer_request, region, _add_peer_queue); } std::unordered_map<int64_t, int64_t> table_trans_leader_count; for (int i = 0; i < response.trans_leader_table_id_size(); ++i) { table_trans_leader_count[response.trans_leader_table_id(i)] = response.trans_leader_count(i); } for (auto& transfer_leader_request : response.trans_leader()) { if (!transfer_leader_request.has_table_id()) { SmartRegion region = get_region(transfer_leader_request.region_id()); if (region == NULL) { DB_FATAL("region_id: %ld not exist, may be removed", transfer_leader_request.region_id()); continue; } region->transfer_leader(transfer_leader_request, region, _transfer_leader_queue); } } for (auto& transfer_leader_request : response.trans_leader()) { if (!transfer_leader_request.has_table_id()) { continue; } int64_t table_id = transfer_leader_request.table_id(); if (table_trans_leader_count[table_id] <= 0) { continue; } SmartRegion region = get_region(transfer_leader_request.region_id()); if (region == NULL) { DB_FATAL("region_id: %ld not exist, may be removed", transfer_leader_request.region_id()); continue; } auto ret = region->transfer_leader(transfer_leader_request, region, _transfer_leader_queue); if (ret == 0) { table_trans_leader_count[table_id]--; } } const auto& delete_region_ids = response.delete_region_ids(); auto remove_func = [this, delete_region_ids]() { //删除region数据,该region已不在raft组内 for (auto& delete_region_id : delete_region_ids) { if (_shutdown) { return; } DB_WARNING("receive delete region response from meta server heart beat, delete_region_id:%ld", delete_region_id); drop_region_from_store(delete_region_id, true); } }; _remove_region_queue.run(remove_func); std::set<int64_t> ddlwork_table_ids; for (auto& ddlwork_info : response.ddlwork_infos()) { ddlwork_table_ids.insert(ddlwork_info.table_id()); traverse_copy_region_map([&ddlwork_info](const SmartRegion& region) { if (region->get_global_index_id() == ddlwork_info.table_id()) { DB_DEBUG("DDL_LOG region_id [%ld] table_id: %ld start ddl work.", region->get_region_id(), ddlwork_info.table_id()); region->ddlwork_process(ddlwork_info); } }); } traverse_copy_region_map([&ddlwork_table_ids](const SmartRegion& region) { region->ddlwork_finish_check_process(ddlwork_table_ids); }); } int Store::drop_region_from_store(int64_t drop_region_id, bool need_delay_drop) { SmartRegion region = get_region(drop_region_id); if (region == nullptr) { DB_FATAL("region_id: %ld not exist, may be removed", drop_region_id); return -1; } // 防止一直更新时间导致物理删不掉 if (!region->removed()) { region->shutdown(); region->join(); region->set_removed(true); DB_WARNING("region node close for removed, region_id: %ld", drop_region_id); } if (!need_delay_drop) { RegionControl::clear_all_infos_for_region(drop_region_id); erase_region(drop_region_id); } DB_WARNING("region node removed, region_id: %ld, need_delay_drop:%d", drop_region_id, need_delay_drop); return 0; } void Store::print_heartbeat_info(const pb::StoreHeartBeatRequest& request) { SELF_TRACE("heart beat request(instance_info):%s, need_leader_balance: %d, need_peer_balance: %d", request.instance_info().ShortDebugString().c_str(), request.need_leader_balance(), request.need_peer_balance()); std::string str_schema; for (auto& schema_info : request.schema_infos()) { str_schema += schema_info.ShortDebugString() + ", "; } SELF_TRACE("heart beat request(schema_infos):%s", str_schema.c_str()); int count = 0; std::string str_leader; for (auto& leader_region : request.leader_regions()) { str_leader += leader_region.ShortDebugString() + ", "; ++count; if (count % 10 == 0) { SELF_TRACE("heart beat request(leader_regions):%s", str_leader.c_str()); str_leader.clear(); } } if (!str_leader.empty()) { SELF_TRACE("heart beat request(leader_regions):%s", str_leader.c_str()); } count = 0; std::string str_peer; for (auto& peer_info : request.peer_infos()) { str_peer += peer_info.ShortDebugString() + ", "; ++count; if (count % 10 == 0) { SELF_TRACE("heart beat request(peer_infos):%s", str_peer.c_str()); str_peer.clear(); } } if (!str_peer.empty()) { SELF_TRACE("heart beat request(peer_infos):%s", str_peer.c_str()); } } void Store::backup_region(google::protobuf::RpcController* controller, const pb::BackUpReq* request, pb::BackUpRes* response, google::protobuf::Closure* done) { auto backup_type = SstBackupType::UNKNOWN_BACKUP; brpc::ClosureGuard done_guard(done); brpc::Controller* cntl =static_cast<brpc::Controller*>(controller); const std::string& req_info = cntl->http_request().unresolved_path(); DB_NOTICE("backup request[%s]", req_info.c_str()); std::vector<std::string> request_vec; boost::split(request_vec, req_info, boost::is_any_of("/")); if (request_vec.size() < 3) { DB_WARNING("backup request info error[%s]", req_info.c_str()); cntl->http_response().set_status_code(brpc::HTTP_STATUS_INTERNAL_SERVER_ERROR); return; } if (request_vec[2] == "data") { backup_type = SstBackupType::DATA_BACKUP; } else { DB_WARNING("noknown backup request [%s].", request_vec[2].c_str()); cntl->http_response().set_status_code(brpc::HTTP_STATUS_INTERNAL_SERVER_ERROR); return; } int64_t region_id = -1; try { region_id = std::stol(request_vec[1]); } catch (std::exception& exp) { DB_WARNING("backup parse region id exp[%s]", exp.what()); cntl->http_response().set_status_code(brpc::HTTP_STATUS_INTERNAL_SERVER_ERROR); return; } SmartRegion region = get_region(region_id); if (region == nullptr) { DB_WARNING("backup no region in store, region_id: %ld", region_id); cntl->http_response().set_status_code(brpc::HTTP_STATUS_INTERNAL_SERVER_ERROR); return; } //request_vec[3]=="1",表示需要ingest最新的sst. bool ingest_store_latest_sst = request_vec.size() > 3 && request_vec[3] == "1"; if (request_vec[0] == "download") { DB_NOTICE("backup download sst region[%ld]", region_id); region->process_download_sst(cntl, request_vec, backup_type); } else if (request_vec[0] == "upload") { DB_NOTICE("backup upload sst region[%ld]", region_id); region->process_upload_sst(cntl, ingest_store_latest_sst); } } void Store::backup(google::protobuf::RpcController* controller, const pb::BackupRequest* request, pb::BackupResponse* response, google::protobuf::Closure* done) { brpc::ClosureGuard done_guard(done); brpc::Controller* cntl = static_cast<brpc::Controller*>(controller); int64_t region_id = request->region_id(); SmartRegion region = get_region(region_id); if (region == nullptr) { DB_WARNING("backup no region in store, region_id: %ld", region_id); return; } if (request->backup_op() == pb::BACKUP_DOWNLOAD) { DB_NOTICE("backup download sst region[%ld]", region_id); region->process_download_sst_streaming(cntl, request, response); } else if (request->backup_op() == pb::BACKUP_UPLOAD) { DB_NOTICE("backup upload sst region[%ld]", region_id); region->process_upload_sst_streaming(cntl, request->ingest_store_latest_sst(), request, response); } else { DB_WARNING("unknown sst backup streaming op."); } } } //namespace <|start_filename|>src/logical_plan/delete_planner.cpp<|end_filename|> // Copyright (c) 2018-present Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "delete_planner.h" #include "meta_server_interact.hpp" #include <gflags/gflags.h> #include "network_socket.h" namespace baikaldb { DEFINE_bool(delete_all_to_truncate, false, "delete from xxx; treat as truncate"); int DeletePlanner::plan() { if (_ctx->stmt_type == parser::NT_TRUNCATE) { if (_ctx->client_conn->txn_id != 0) { if (_ctx->stat_info.error_code == ER_ERROR_FIRST) { _ctx->stat_info.error_code = ER_NOT_ALLOWED_COMMAND; _ctx->stat_info.error_msg.str("not allowed truncate in transaction"); } DB_FATAL("not allowed truncate table in txn connection txn_id:%lu", _ctx->client_conn->txn_id); return -1; } _truncate_stmt = (parser::TruncateStmt*)(_ctx->stmt); if (0 != parse_db_tables(_truncate_stmt->table_name)) { DB_WARNING("get truncate_table plan failed"); return -1; } create_packet_node(pb::OP_TRUNCATE_TABLE); if (0 != create_truncate_node()) { DB_WARNING("get truncate_table plan failed"); return -1; } if (0 != reset_auto_incr_id()) { return -1; } return 0; } _delete_stmt = (parser::DeleteStmt*)(_ctx->stmt); if (!_delete_stmt) { return -1; } if (_delete_stmt->delete_table_list.size() != 0) { DB_WARNING("unsupport multi table delete"); return -1; } if (_delete_stmt->from_table->node_type != parser::NT_TABLE) { DB_WARNING("unsupport multi table delete"); return -1; } if (0 != parse_db_tables((parser::TableName*)_delete_stmt->from_table)) { return -1; } // delete from xxx; => truncate table xxx; if (FLAGS_delete_all_to_truncate && _delete_stmt->where == nullptr && _delete_stmt->limit == nullptr) { create_packet_node(pb::OP_TRUNCATE_TABLE); if (0 != create_truncate_node()) { DB_WARNING("get truncate_table plan failed"); return -1; } if (0 != reset_auto_incr_id()) { return -1; } return 0; } if (0 != parse_where()) { return -1; } if (0 != parse_orderby()) { return -1; } if (0 != parse_limit()) { return -1; } create_packet_node(pb::OP_DELETE); if (0 != create_delete_node()) { return -1; } if (0 != create_sort_node()) { return -1; } if (0 != create_filter_node(_where_filters, pb::WHERE_FILTER_NODE)) { return -1; } create_scan_tuple_descs(); create_order_by_tuple_desc(); if (0 != create_scan_nodes()) { return -1; } ScanTupleInfo& info = _plan_table_ctx->table_tuple_mapping[try_to_lower(_current_tables[0])]; int64_t table_id = info.table_id; _ctx->prepared_table_id = table_id; if (!_ctx->is_prepared) { set_dml_txn_state(table_id); } set_socket_txn_tid_set(); return 0; } int DeletePlanner::create_delete_node() { if (_current_tables.size() != 1 || _plan_table_ctx->table_tuple_mapping.count(try_to_lower(_current_tables[0])) == 0) { DB_WARNING("invalid sql format: %s", _ctx->sql.c_str()); return -1; } if (_apply_root != nullptr) { DB_WARNING("not support correlation subquery sql format: %s", _ctx->sql.c_str()); return -1; } ScanTupleInfo& info = _plan_table_ctx->table_tuple_mapping[try_to_lower(_current_tables[0])]; int64_t table_id = info.table_id; pb::PlanNode* delete_node = _ctx->add_plan_node(); delete_node->set_node_type(pb::DELETE_NODE); delete_node->set_limit(-1); delete_node->set_is_explain(_ctx->is_explain); delete_node->set_num_children(1); //TODO pb::DerivePlanNode* derive = delete_node->mutable_derive_node(); pb::DeleteNode* _delete = derive->mutable_delete_node(); _delete->set_table_id(table_id); auto pk = _factory->get_index_info_ptr(table_id); if (pk == nullptr) { DB_WARNING("no pk found with id: %ld", table_id); return -1; } for (auto& field : pk->fields) { auto& slot = get_scan_ref_slot(_current_tables[0], table_id, field.id, field.type); _delete->add_primary_slots()->CopyFrom(slot); } return 0; } int DeletePlanner::create_truncate_node() { if (_plan_table_ctx->table_tuple_mapping.size() != 1) { DB_WARNING("invalid sql format: %s", _ctx->sql.c_str()); return -1; } auto iter = _plan_table_ctx->table_tuple_mapping.begin(); pb::PlanNode* truncate_node = _ctx->add_plan_node(); truncate_node->set_node_type(pb::TRUNCATE_NODE); truncate_node->set_limit(-1); truncate_node->set_num_children(0); //TODO pb::DerivePlanNode* derive = truncate_node->mutable_derive_node(); pb::TruncateNode* _truncate = derive->mutable_truncate_node(); _truncate->set_table_id(iter->second.table_id); return 0; } int DeletePlanner::reset_auto_incr_id() { auto iter = _plan_table_ctx->table_tuple_mapping.begin(); int64_t table_id = iter->second.table_id; SchemaFactory* schema_factory = SchemaFactory::get_instance(); auto table_info_ptr = schema_factory->get_table_info_ptr(table_id); if (table_info_ptr == nullptr || table_info_ptr->auto_inc_field_id == -1) { return 0; } pb::MetaManagerRequest request; request.set_op_type(pb::OP_UPDATE_FOR_AUTO_INCREMENT); auto auto_increment_ptr = request.mutable_auto_increment(); auto_increment_ptr->set_table_id(table_id); auto_increment_ptr->set_force(true); auto_increment_ptr->set_start_id(0); pb::MetaManagerResponse response; if (MetaServerInteract::get_instance()->send_request("meta_manager", request, response) != 0) { if (response.errcode() != pb::SUCCESS && _ctx->stat_info.error_code == ER_ERROR_FIRST) { _ctx->stat_info.error_code = ER_TABLE_CANT_HANDLE_AUTO_INCREMENT; _ctx->stat_info.error_msg.str("reset auto increment failed"); } DB_WARNING("send_request fail"); return -1; } return 0; } int DeletePlanner::parse_where() { if (_delete_stmt->where == nullptr) { return 0; } if (0 != flatten_filter(_delete_stmt->where, _where_filters, CreateExprOptions())) { DB_WARNING("flatten_filter failed"); return -1; } return 0; } int DeletePlanner::parse_orderby() { if (_delete_stmt != nullptr && _delete_stmt->order != nullptr) { DB_WARNING("delete does not support orderby"); return -1; } return 0; } int DeletePlanner::parse_limit() { if (_delete_stmt->limit != nullptr) { _ctx->stat_info.error_code = ER_SYNTAX_ERROR; _ctx->stat_info.error_msg << "syntax error! delete does not support limit"; return -1; } // parser::LimitClause* limit = _delete_stmt->limit; // if (limit->offset != nullptr && 0 != create_expr_tree(limit->offset, _limit_offset)) { // DB_WARNING("create limit offset expr failed"); // return -1; // } // if (limit->count != nullptr && 0 != create_expr_tree(limit->count, _limit_count)) { // DB_WARNING("create limit offset expr failed"); // return -1; // } return 0; } } //namespace baikaldb <|start_filename|>include/expr/internal_functions.h<|end_filename|> // Copyright (c) 2018-present Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <vector> #include "expr_value.h" namespace baikaldb { //number functions ExprValue round(const std::vector<ExprValue>& input); ExprValue floor(const std::vector<ExprValue>& input); ExprValue ceil(const std::vector<ExprValue>& input); ExprValue abs(const std::vector<ExprValue>& input); ExprValue sqrt(const std::vector<ExprValue>& input); ExprValue mod(const std::vector<ExprValue>& input); ExprValue rand(const std::vector<ExprValue>& input); ExprValue sign(const std::vector<ExprValue>& input); ExprValue sin(const std::vector<ExprValue>& input); ExprValue asin(const std::vector<ExprValue>& input); ExprValue cos(const std::vector<ExprValue>& input); ExprValue acos(const std::vector<ExprValue>& input); ExprValue tan(const std::vector<ExprValue>& input); ExprValue cot(const std::vector<ExprValue>& input); ExprValue atan(const std::vector<ExprValue>& input); ExprValue ln(const std::vector<ExprValue>& input); ExprValue log(const std::vector<ExprValue>& input); ExprValue pi(const std::vector<ExprValue>& input); ExprValue greatest(const std::vector<ExprValue>& input); ExprValue least(const std::vector<ExprValue>& input); ExprValue pow(const std::vector<ExprValue>& input); //string functions ExprValue length(const std::vector<ExprValue>& input); ExprValue bit_length(const std::vector<ExprValue>& input); ExprValue lower(const std::vector<ExprValue>& input); ExprValue lower_gbk(const std::vector<ExprValue>& input); ExprValue upper(const std::vector<ExprValue>& input); ExprValue concat(const std::vector<ExprValue>& input); ExprValue substr(const std::vector<ExprValue>& input); ExprValue left(const std::vector<ExprValue>& input); ExprValue right(const std::vector<ExprValue>& input); ExprValue trim(const std::vector<ExprValue>& input); ExprValue ltrim(const std::vector<ExprValue>& input); ExprValue rtrim(const std::vector<ExprValue>& input); ExprValue concat_ws(const std::vector<ExprValue>& input); ExprValue ascii(const std::vector<ExprValue>& input); ExprValue strcmp(const std::vector<ExprValue>& input); ExprValue insert(const std::vector<ExprValue>& input); ExprValue replace(const std::vector<ExprValue>& input); ExprValue repeat(const std::vector<ExprValue>& input); ExprValue reverse(const std::vector<ExprValue>& input); ExprValue locate(const std::vector<ExprValue>& input); // datetime functions ExprValue unix_timestamp(const std::vector<ExprValue>& input); ExprValue from_unixtime(const std::vector<ExprValue>& input); ExprValue now(const std::vector<ExprValue>& input); ExprValue utc_timestamp(const std::vector<ExprValue>& input); ExprValue date_format(const std::vector<ExprValue>& input); ExprValue timediff(const std::vector<ExprValue>& input); ExprValue timestampdiff(const std::vector<ExprValue>& input); ExprValue curdate(const std::vector<ExprValue>& input); ExprValue current_date(const std::vector<ExprValue>& input); ExprValue curtime(const std::vector<ExprValue>& input); ExprValue current_time(const std::vector<ExprValue>& input); ExprValue current_timestamp(const std::vector<ExprValue>& input); ExprValue day(const std::vector<ExprValue>& input); ExprValue dayname(const std::vector<ExprValue>& input); ExprValue dayofweek(const std::vector<ExprValue>& input); ExprValue dayofmonth(const std::vector<ExprValue>& input); ExprValue dayofyear(const std::vector<ExprValue>& input); ExprValue month(const std::vector<ExprValue>& input); ExprValue monthname(const std::vector<ExprValue>& input); ExprValue year(const std::vector<ExprValue>& input); ExprValue week(const std::vector<ExprValue>& input); ExprValue time_to_sec(const std::vector<ExprValue>& input); ExprValue sec_to_time(const std::vector<ExprValue>& input); ExprValue datediff(const std::vector<ExprValue>& input); ExprValue date_add(const std::vector<ExprValue>& input); ExprValue date_sub(const std::vector<ExprValue>& input); ExprValue weekday(const std::vector<ExprValue>& input); ExprValue extract(const std::vector<ExprValue>& input); // hll functions ExprValue hll_add(const std::vector<ExprValue>& input); ExprValue hll_merge(const std::vector<ExprValue>& input); ExprValue hll_estimate(const std::vector<ExprValue>& input); ExprValue hll_init(const std::vector<ExprValue>& input); // case when functions ExprValue case_when(const std::vector<ExprValue>& input); ExprValue case_expr_when(const std::vector<ExprValue>& input); ExprValue if_(const std::vector<ExprValue>& input); ExprValue ifnull(const std::vector<ExprValue>& input); ExprValue nullif(const std::vector<ExprValue>& input); // MurmurHash sign ExprValue murmur_hash(const std::vector<ExprValue>& input); // Encryption and Compression Functions ExprValue md5(const std::vector<ExprValue>& input); ExprValue sha1(const std::vector<ExprValue>& input); ExprValue sha(const std::vector<ExprValue>& input); // Roaring bitmap functions ExprValue rb_build(const std::vector<ExprValue>& input); ExprValue rb_and(const std::vector<ExprValue>& input); //ExprValue rb_and_cardinality(const std::vector<ExprValue>& input); ExprValue rb_or(const std::vector<ExprValue>& input); //ExprValue rb_or_cardinality(const std::vector<ExprValue>& input); ExprValue rb_xor(const std::vector<ExprValue>& input); //ExprValue rb_xor_cardinality(const std::vector<ExprValue>& input); ExprValue rb_andnot(const std::vector<ExprValue>& input); //ExprValue rb_andnot_cardinality(const std::vector<ExprValue>& input); ExprValue rb_cardinality(const std::vector<ExprValue>& input); ExprValue rb_empty(const std::vector<ExprValue>& input); ExprValue rb_equals(const std::vector<ExprValue>& input); //ExprValue rb_not_equals(const std::vector<ExprValue>& input); ExprValue rb_intersect(const std::vector<ExprValue>& input); ExprValue rb_contains(const std::vector<ExprValue>& input); ExprValue rb_contains_range(const std::vector<ExprValue>& input); ExprValue rb_add(const std::vector<ExprValue>& input); ExprValue rb_add_range(const std::vector<ExprValue>& input); ExprValue rb_remove(const std::vector<ExprValue>& input); ExprValue rb_remove_range(const std::vector<ExprValue>& input); ExprValue rb_flip(const std::vector<ExprValue>& input); ExprValue rb_flip_range(const std::vector<ExprValue>& input); ExprValue rb_minimum(const std::vector<ExprValue>& input); ExprValue rb_maximum(const std::vector<ExprValue>& input); ExprValue rb_rank(const std::vector<ExprValue>& input); ExprValue rb_jaccard_index(const std::vector<ExprValue>& input); ExprValue tdigest_build(const std::vector<ExprValue>& input); ExprValue tdigest_add(const std::vector<ExprValue>& input); ExprValue tdigest_percentile(const std::vector<ExprValue>& input); ExprValue tdigest_location(const std::vector<ExprValue>& input); // other ExprValue version(const std::vector<ExprValue>& input); ExprValue last_insert_id(const std::vector<ExprValue>& input); } /* vim: set ts=4 sw=4 sts=4 tw=100 */ <|start_filename|>include/raft/rocksdb_file_system_adaptor.h<|end_filename|> // Copyright (c) 2018-present Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <map> #ifdef BAIDU_INTERNAL #include <raft/file_system_adaptor.h> #else #include <braft/file_system_adaptor.h> #endif #include "rocks_wrapper.h" #include "sst_file_writer.h" namespace baikaldb { const std::string SNAPSHOT_DATA_FILE = "region_data_snapshot.sst"; const std::string SNAPSHOT_META_FILE = "region_meta_snapshot.sst"; const std::string SNAPSHOT_DATA_FILE_WITH_SLASH = "/" + SNAPSHOT_DATA_FILE; const std::string SNAPSHOT_META_FILE_WITH_SLASH = "/" + SNAPSHOT_META_FILE; const size_t SST_FILE_LENGTH = 128 * 1024 * 1024; class RocksdbFileSystemAdaptor; class Region; typedef std::shared_ptr<Region> SmartRegion; struct IteratorContext { bool reading = false; std::unique_ptr<rocksdb::Iterator> iter; std::string prefix; std::string upper_bound; rocksdb::Slice upper_bound_slice; bool is_meta_sst = false; int64_t offset = 0; bool done = false; }; struct SnapshotContext { SnapshotContext() : snapshot(RocksWrapper::get_instance()->get_snapshot()) {} ~SnapshotContext() { if (data_context != nullptr) { delete data_context; } if (meta_context != nullptr) { delete meta_context; } if (snapshot != nullptr) { RocksWrapper::get_instance()->relase_snapshot(snapshot); } } const rocksdb::Snapshot* snapshot = nullptr; IteratorContext* data_context = nullptr; IteratorContext* meta_context = nullptr; int64_t data_index = 0; bool need_copy_data = true; }; typedef std::shared_ptr<SnapshotContext> SnapshotContextPtr; class PosixDirReader : public braft::DirReader { friend class RocksdbFileSystemAdaptor; public: virtual ~PosixDirReader() {} virtual bool is_valid() const override; virtual bool next() override; virtual const char* name() const override; protected: PosixDirReader(const std::string& path) : _dir_reader(path.c_str()) {} private: butil::DirReaderPosix _dir_reader; }; //从rocksdb中读取region的全量信息,包括两部分data 和 meta 信息 class RocksdbReaderAdaptor : public braft::FileAdaptor { friend class RocksdbFileSystemAdaptor; public: virtual ~RocksdbReaderAdaptor(); virtual ssize_t read(butil::IOPortal* portal, off_t offset, size_t size) override; virtual ssize_t size() override; virtual bool close() override; void open() { _closed = false; } virtual ssize_t write(const butil::IOBuf& data, off_t offset) override; virtual bool sync() override; protected: RocksdbReaderAdaptor(int64_t region_id, const std::string& path, RocksdbFileSystemAdaptor* rs, SnapshotContextPtr context, bool is_meta_reader); private: //把rocksdb的key 和 value 串行化到iobuf中,通过rpc发送到接受peer int64_t serialize_to_iobuf(butil::IOPortal* portal, const rocksdb::Slice& key) { if (portal != nullptr) { portal->append((void*)&key.size_, sizeof(size_t)); portal->append((void*)key.data_, key.size_); } return sizeof(size_t) + key.size_; } private: int64_t _region_id; std::string _path; RocksdbFileSystemAdaptor* _rs = nullptr; SnapshotContextPtr _context = nullptr; bool _is_meta_reader = false; bool _closed = true; size_t _num_lines = 0; butil::IOPortal _last_package; off_t _last_offset = 0; }; class SstWriterAdaptor : public braft::FileAdaptor { friend class RocksdbFileSystemAdaptor; public: virtual ~SstWriterAdaptor(); int open(); virtual ssize_t write(const butil::IOBuf& data, off_t offset) override; virtual bool close() override; virtual ssize_t read(butil::IOPortal* portal, off_t offset, size_t size) override; virtual ssize_t size() override; virtual bool sync() override; protected: SstWriterAdaptor(int64_t region_id, const std::string& path, const rocksdb::Options& option); private: bool finish_sst(); int iobuf_to_sst(butil::IOBuf data); int64_t _region_id; SmartRegion _region_ptr; std::string _path; int _sst_idx = 0; size_t _count = 0; size_t _data_size = 0; bool _closed = true; bool _is_meta = false; std::unique_ptr<SstFileWriter> _writer; }; class PosixFileAdaptor : public braft::FileAdaptor { friend class RocksdbFileSystemAdaptor; public: virtual ~PosixFileAdaptor(); int open(int oflag); virtual ssize_t write(const butil::IOBuf& data, off_t offset) override; virtual ssize_t read(butil::IOPortal* portal, off_t offset, size_t size) override; virtual ssize_t size() override; virtual bool sync() override; virtual bool close() override; protected: PosixFileAdaptor(const std::string& p) : _path(p), _fd(-1) {} private: std::string _path; int _fd; }; class RocksdbFileSystemAdaptor : public braft::FileSystemAdaptor { public: RocksdbFileSystemAdaptor(int64_t region_id); virtual ~RocksdbFileSystemAdaptor(); virtual bool delete_file(const std::string& path, bool recursive) override; virtual bool rename(const std::string& old_path, const std::string& new_path) override; virtual bool link(const std::string& old_path, const std::string& new_path) override; virtual bool create_directory(const std::string& path, butil::File::Error* error, bool create_parent_directories) override; virtual bool path_exists(const std::string& path) override; virtual bool directory_exists(const std::string& path) override; virtual braft::DirReader* directory_reader(const std::string& path) override; virtual braft::FileAdaptor* open(const std::string& path, int oflag, const ::google::protobuf::Message* file_meta, butil::File::Error* e) override; virtual bool open_snapshot(const std::string& snapshot_path) override; virtual void close_snapshot(const std::string& snapshot_path) override; void close(const std::string& path); private: braft::FileAdaptor* open_reader_adaptor(const std::string& path, int oflag, const ::google::protobuf::Message* file_meta, butil::File::Error* e); braft::FileAdaptor* open_writer_adaptor(const std::string& path, int oflag, const ::google::protobuf::Message* file_meta, butil::File::Error* e); SnapshotContextPtr get_snapshot(const std::string& path); private: int64_t _region_id; bthread::Mutex _snapshot_mutex; bthread::Mutex _open_reader_adaptor_mutex; BthreadCond _mutil_snapshot_cond; typedef std::map<std::string, std::pair<SnapshotContextPtr, int64_t>> SnapshotMap; SnapshotMap _snapshots; }; } //namespace raft /* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */ <|start_filename|>src/common/common.cpp<|end_filename|> // Copyright (c) 2018-present Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "common.h" #include <unordered_map> #include <cstdlib> #include <cctype> #include <sstream> #ifdef BAIDU_INTERNAL #include <pb_to_json.h> #include <json_to_pb.h> #else #include <json2pb/pb_to_json.h> #include <json2pb/json_to_pb.h> #endif #include "rocksdb/slice.h" #include <boost/algorithm/string.hpp> #include <google/protobuf/descriptor.pb.h> #include "rocksdb/slice.h" #include "expr_value.h" using google::protobuf::FieldDescriptorProto; namespace baikaldb { DEFINE_int32(raft_write_concurrency, 40, "raft_write concurrency, default:40"); DEFINE_int32(service_write_concurrency, 40, "service_write concurrency, default:40"); DEFINE_int32(service_lock_concurrency, 40, "service_lock_concurrency, Deprecated"); DEFINE_int32(snapshot_load_num, 4, "snapshot load concurrency, default 4"); DEFINE_int32(ddl_work_concurrency, 10, "ddlwork concurrency, default:10"); DEFINE_int32(baikal_heartbeat_concurrency, 10, "baikal heartbeat concurrency, default:10"); DEFINE_int64(incremental_info_gc_time, 600 * 1000 * 1000, "time interval to clear incremental info"); DECLARE_string(default_physical_room); DEFINE_bool(enable_debug, false, "open DB_DEBUG log"); DEFINE_bool(enable_self_trace, true, "open SELF_TRACE log"); DEFINE_bool(servitysinglelog, true, "diff servity message in seperate logfile"); DEFINE_int32(baikal_heartbeat_interval_us, 10 * 1000 * 1000, "baikal_heartbeat_interval(us)"); DEFINE_bool(schema_ignore_case, false, "whether ignore case when match db/table name"); DEFINE_bool(disambiguate_select_name, false, "whether use the first when select name is ambiguous, default false"); int64_t timestamp_diff(timeval _start, timeval _end) { return (_end.tv_sec - _start.tv_sec) * 1000000 + (_end.tv_usec-_start.tv_usec); //macro second } std::string pb2json(const google::protobuf::Message& message) { std::string json; std::string error; #ifdef BAIDU_INTERNAL if (ProtoMessageToJson(message, &json, &error)) { #else if (json2pb::ProtoMessageToJson(message, &json, &error)) { #endif return json; } return error; } std::string json2pb(const std::string& json, google::protobuf::Message* message) { std::string error; #ifdef BAIDU_INTERNAL if (JsonToProtoMessage(json, message, &error)) { #else if (json2pb::JsonToProtoMessage(json, message, &error)) { #endif return ""; } return error; } // STMPS_SUCCESS, // STMPS_FAIL, // STMPS_NEED_RESIZE SerializeStatus to_string (int32_t number, char *buf, size_t size, size_t& len) { if (number == 0U) { len = 1; if (size < 1) { return STMPS_NEED_RESIZE; } buf[0] = '0'; return STMPS_SUCCESS; } if (number == INT32_MIN) { len = 11; if (size < len) { return STMPS_NEED_RESIZE; } memcpy(buf, "-2147483648", len); return STMPS_SUCCESS; } len = 0; bool negtive = false; if (number < 0) { number = -number; negtive = true; len++; } int32_t n = number; while (n > 0) { n /= 10; len++; } if (len > size) { return STMPS_NEED_RESIZE; } if (negtive) { buf[0] = '-'; } int length = len; while (number > 0) { buf[--length] = '0' + (number % 10); number /= 10; } return STMPS_SUCCESS; } std::string to_string(int32_t number) { char buffer[16]; size_t len = 0; SerializeStatus ret = to_string(number, buffer, 16, len); if (ret == STMPS_SUCCESS) { buffer[len] = '\0'; return std::string(buffer); } return ""; } SerializeStatus to_string (uint32_t number, char *buf, size_t size, size_t& len) { if (number == 0U) { len = 1; if (size < len) { return STMPS_NEED_RESIZE; } buf[0] = '0'; return STMPS_SUCCESS; } len = 0; uint32_t n = number; while (n > 0) { n /= 10; len++; } if (len > size) { return STMPS_NEED_RESIZE; } int length = len; while (number > 0) { buf[--length] = '0' + (number % 10); number /= 10; } return STMPS_SUCCESS; } std::string to_string(uint32_t number) { char buffer[16]; size_t len = 0; SerializeStatus ret = to_string(number, buffer, 16, len); if (ret == STMPS_SUCCESS) { buffer[len] = '\0'; return std::string(buffer); } return ""; } SerializeStatus to_string (int64_t number, char *buf, size_t size, size_t& len) { if (number == 0UL) { len = 1; if (size < len) { return STMPS_NEED_RESIZE; } buf[0] = '0'; return STMPS_SUCCESS; } if (number == INT64_MIN) { len = 20; if (size < len) { return STMPS_NEED_RESIZE; } memcpy(buf, "-9223372036854775808", len); return STMPS_SUCCESS; } len = 0; bool negtive = false; if (number < 0) { number = -number; negtive = true; len++; } int64_t n = number; while (n > 0) { n /= 10; len++; } if (len > size) { return STMPS_NEED_RESIZE; } if (negtive) { buf[0] = '-'; } int length = len; while (number > 0) { buf[--length] = '0' + (number % 10); number /= 10; } return STMPS_SUCCESS; } std::string to_string(int64_t number) { char buffer[32]; size_t len = 0; SerializeStatus ret = to_string(number, buffer, 32, len); if (ret == STMPS_SUCCESS) { buffer[len] = '\0'; return std::string(buffer); } return ""; } SerializeStatus to_string (uint64_t number, char *buf, size_t size, size_t& len) { if (number == 0UL) { len = 1; if (size < len) { return STMPS_NEED_RESIZE; } buf[0] = '0'; return STMPS_SUCCESS; } len = 0; uint64_t n = number; while (n > 0) { n /= 10; len++; } if (len > size) { return STMPS_NEED_RESIZE; } int length = len; while (number > 0) { buf[--length] = '0' + (number % 10); number /= 10; } return STMPS_SUCCESS; } std::string to_string(uint64_t number) { char buffer[32]; size_t len = 0; SerializeStatus ret = to_string(number, buffer, 32, len); if (ret == STMPS_SUCCESS) { buffer[len] = '\0'; return std::string(buffer); } return ""; } std::string remove_quote(const char* str, char quote) { uint32_t len = strlen(str); if (len > 2 && str[0] == quote && str[len-1] == quote) { return std::string(str + 1, len - 2); } else { return std::string(str); } } std::string str_to_hex(const std::string& str) { return rocksdb::Slice(str).ToString(true); } bool is_digits(const std::string& str) { return std::all_of(str.begin(), str.end(), ::isdigit); } void stripslashes(std::string& str, bool is_gbk) { size_t slow = 0; size_t fast = 0; bool has_slash = false; static std::unordered_map<char, char> trans_map = { {'\\', '\\'}, {'\"', '\"'}, {'\'', '\''}, {'r', '\r'}, {'t', '\t'}, {'n', '\n'}, {'b', '\b'}, {'Z', '\x1A'}, }; while (fast < str.size()) { if (has_slash) { if (trans_map.count(str[fast]) == 1) { str[slow++] = trans_map[str[fast++]]; } else if (str[fast] == '%' || str[fast] == '_') { // like中的特殊符号,需要补全'\' str[slow++] = '\\'; str[slow++] = str[fast++]; } has_slash = false; } else { if (str[fast] == '\\') { has_slash = true; fast++; } else if (is_gbk && (str[fast] & 0x80) != 0) { //gbk中文字符处理 str[slow++] = str[fast++]; if (fast >= str.size()) { // 去除最后半个gbk中文 //--slow; break; } str[slow++] = str[fast++]; } else { str[slow++] = str[fast++]; } } } str.resize(slow); } void update_op_version(pb::SchemaConf* p_conf, const std::string& desc) { auto version = p_conf->has_op_version() ? p_conf->op_version() : 0; p_conf->set_op_version(version + 1); p_conf->set_op_desc(desc); } void update_schema_conf_common(const std::string& table_name, const pb::SchemaConf& schema_conf, pb::SchemaConf* p_conf) { const google::protobuf::Reflection* src_reflection = schema_conf.GetReflection(); //const google::protobuf::Descriptor* src_descriptor = schema_conf.GetDescriptor(); const google::protobuf::Reflection* dst_reflection = p_conf->GetReflection(); const google::protobuf::Descriptor* dst_descriptor = p_conf->GetDescriptor(); const google::protobuf::FieldDescriptor* src_field = nullptr; const google::protobuf::FieldDescriptor* dst_field = nullptr; std::vector<const google::protobuf::FieldDescriptor*> src_field_list; src_reflection->ListFields(schema_conf, &src_field_list); for (int i = 0; i < (int)src_field_list.size(); ++i) { src_field = src_field_list[i]; if (src_field == nullptr) { continue; } dst_field = dst_descriptor->FindFieldByName(src_field->name()); if (dst_field == nullptr) { continue; } if (src_field->cpp_type() != dst_field->cpp_type()) { continue; } auto type = src_field->cpp_type(); switch (type) { case google::protobuf::FieldDescriptor::CPPTYPE_INT32: { auto src_value = src_reflection->GetInt32(schema_conf, src_field); dst_reflection->SetInt32(p_conf, dst_field, src_value); } break; case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: { auto src_value = src_reflection->GetUInt32(schema_conf, src_field); dst_reflection->SetUInt32(p_conf, dst_field, src_value); } break; case google::protobuf::FieldDescriptor::CPPTYPE_INT64: { auto src_value = src_reflection->GetInt64(schema_conf, src_field); dst_reflection->SetInt64(p_conf, dst_field, src_value); } break; case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: { auto src_value = src_reflection->GetUInt64(schema_conf, src_field); dst_reflection->SetUInt64(p_conf, dst_field, src_value); } break; case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: { auto src_value = src_reflection->GetFloat(schema_conf, src_field); dst_reflection->SetFloat(p_conf, dst_field, src_value); } break; case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: { auto src_value = src_reflection->GetDouble(schema_conf, src_field); dst_reflection->SetDouble(p_conf, dst_field, src_value); } break; case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: { auto src_value = src_reflection->GetBool(schema_conf, src_field); dst_reflection->SetBool(p_conf, dst_field, src_value); } break; case google::protobuf::FieldDescriptor::CPPTYPE_STRING: { auto src_value = src_reflection->GetString(schema_conf, src_field); dst_reflection->SetString(p_conf, dst_field, src_value); } break; case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: { auto src_value = src_reflection->GetEnum(schema_conf, src_field); dst_reflection->SetEnum(p_conf, dst_field, src_value); } break; default: { break; } } } DB_WARNING("%s schema conf UPDATE TO : %s", table_name.c_str(), schema_conf.ShortDebugString().c_str()); } int primitive_to_proto_type(pb::PrimitiveType type) { using google::protobuf::FieldDescriptorProto; static std::unordered_map<int32_t, int32_t> _mysql_pb_type_mapping = { { pb::INT8, FieldDescriptorProto::TYPE_SINT32 }, { pb::INT16, FieldDescriptorProto::TYPE_SINT32 }, { pb::INT32, FieldDescriptorProto::TYPE_SINT32 }, { pb::INT64, FieldDescriptorProto::TYPE_SINT64 }, { pb::UINT8, FieldDescriptorProto::TYPE_UINT32 }, { pb::UINT16, FieldDescriptorProto::TYPE_UINT32 }, { pb::UINT32, FieldDescriptorProto::TYPE_UINT32 }, { pb::UINT64, FieldDescriptorProto::TYPE_UINT64 }, { pb::FLOAT, FieldDescriptorProto::TYPE_FLOAT }, { pb::DOUBLE, FieldDescriptorProto::TYPE_DOUBLE }, { pb::STRING, FieldDescriptorProto::TYPE_BYTES }, { pb::DATETIME, FieldDescriptorProto::TYPE_FIXED64}, { pb::TIMESTAMP, FieldDescriptorProto::TYPE_FIXED32}, { pb::DATE, FieldDescriptorProto::TYPE_FIXED32}, { pb::TIME, FieldDescriptorProto::TYPE_SFIXED32}, { pb::HLL, FieldDescriptorProto::TYPE_BYTES}, { pb::BOOL, FieldDescriptorProto::TYPE_BOOL}, { pb::BITMAP, FieldDescriptorProto::TYPE_BYTES}, { pb::TDIGEST, FieldDescriptorProto::TYPE_BYTES} }; if (_mysql_pb_type_mapping.count(type) == 0) { DB_WARNING("mysql_type %d not supported.", type); return -1; } return _mysql_pb_type_mapping[type]; } int get_physical_room(const std::string& ip_and_port_str, std::string& physical_room) { #ifdef BAIDU_INTERNAL butil::EndPoint point; int ret = butil::str2endpoint(ip_and_port_str.c_str(), &point); if (ret != 0) { DB_WARNING("instance:%s to endpoint fail, ret:%d", ip_and_port_str.c_str(), ret); return ret; } std::string host; ret = butil::endpoint2hostname(point, &host); if (ret != 0) { DB_WARNING("endpoint to hostname fail, ret:%d", ret); return ret; } DB_DEBUG("host:%s", host.c_str()); auto begin = host.find("."); auto end = host.find(":"); if (begin == std::string::npos) { DB_WARNING("host:%s to physical room fail", host.c_str()); return -1; } if (end == std::string::npos) { end = host.size(); } physical_room = std::string(host, begin + 1, end - begin -1); return 0; #else physical_room = FLAGS_default_physical_room; return 0; #endif } int get_instance_from_bns(int* ret, const std::string& bns_name, std::vector<std::string>& instances, bool need_alive) { #ifdef BAIDU_INTERNAL instances.clear(); BnsInput input; BnsOutput output; input.set_service_name(bns_name); input.set_type(0); *ret = webfoot::get_instance_by_service(input, &output); // bns service not exist if (*ret == webfoot::WEBFOOT_RET_SUCCESS || *ret == webfoot::WEBFOOT_SERVICE_BEYOND_THRSHOLD) { for (int i = 0; i < output.instance_size(); ++i) { if (output.instance(i).status() == 0 || !need_alive) { instances.push_back(output.instance(i).host_ip() + ":" + boost::lexical_cast<std::string>(output.instance(i).port())); } } return 0; } DB_WARNING("get instance from service fail, bns_name:%s, ret:%d", bns_name.c_str(), *ret); return -1; #else return -1; #endif } static unsigned char to_hex(unsigned char x) { return x > 9 ? x + 55 : x + 48; } static unsigned char from_hex(unsigned char x) { unsigned char y = '\0'; if (x >= 'A' && x <= 'Z') { y = x - 'A' + 10; } else if (x >= 'a' && x <= 'z') { y = x - 'a' + 10; } else if (x >= '0' && x <= '9') { y = x - '0'; } return y; } std::string url_decode(const std::string& str) { std::string strTemp = ""; size_t length = str.length(); for (size_t i = 0; i < length; i++) { if (str[i] == '+') { strTemp += ' '; } else if (str[i] == '%') { unsigned char high = from_hex((unsigned char)str[++i]); unsigned char low = from_hex((unsigned char)str[++i]); strTemp += high * 16 + low; } else strTemp += str[i]; } return strTemp; } std::vector<std::string> string_split(const std::string &s, char delim) { std::stringstream ss(s); std::string item; std::vector<std::string> elems; while (std::getline(ss, item, delim)) { elems.emplace_back(item); // elems.push_back(std::move(item)); } return elems; } bool ends_with(const std::string &str, const std::string &ending) { if (str.length() < ending.length()) { return false; } return str.compare(str.length() - ending.length(), ending.length(), ending) == 0; } std::string string_trim(std::string& str) { size_t first = str.find_first_not_of(' '); if (first == std::string::npos) return ""; size_t last = str.find_last_not_of(' '); return str.substr(first, (last-first+1)); } const std::string& rand_peer(pb::RegionInfo& info) { if (info.peers_size() == 0) { return info.leader(); } uint32_t i = butil::fast_rand() % info.peers_size(); return info.peers(i); } void other_peer_to_leader(pb::RegionInfo& info) { auto peer = rand_peer(info); if (peer != info.leader()) { info.set_leader(peer); return; } for (auto& peer : info.peers()) { if (peer != info.leader()) { info.set_leader(peer); break; } } } std::string url_encode(const std::string& str) { std::string strTemp = ""; size_t length = str.length(); for (size_t i = 0; i < length; i++) { if (isalnum((unsigned char)str[i]) || (str[i] == '-') || (str[i] == '_') || (str[i] == '.') || (str[i] == '~')) { strTemp += str[i]; } else if (str[i] == ' ') { strTemp += "+"; } else { strTemp += '%'; strTemp += to_hex((unsigned char)str[i] >> 4); strTemp += to_hex((unsigned char)str[i] % 16); } } return strTemp; } } // baikaldb <|start_filename|>include/engine/split_compaction_filter.h<|end_filename|> // Copyright (c) 2018-present Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <rocksdb/compaction_filter.h> #include <bthread/mutex.h> #include "key_encoder.h" #include "type_utils.h" #include "schema_factory.h" #include "transaction.h" namespace baikaldb { DECLARE_int32(rocks_binlog_ttl_days); class SplitCompactionFilter : public rocksdb::CompactionFilter { typedef butil::FlatMap<int64_t, std::string*> KeyMap; typedef DoubleBuffer<KeyMap> DoubleBufKey; typedef std::unordered_set<int64_t> BinlogSet; typedef butil::DoublyBufferedData<BinlogSet> DoubleBufBinlog; public: static SplitCompactionFilter* get_instance() { static SplitCompactionFilter _instance; return &_instance; } ~SplitCompactionFilter() { } const char* Name() const override { return "SplitCompactionFilter"; } // The compaction process invokes this method for kv that is being compacted. // A return value of false indicates that the kv should be preserved // a return value of true indicates that this key-value should be removed from the // output of the compaction. bool Filter(int /*level*/, const rocksdb::Slice& key, const rocksdb::Slice& value, std::string* /*new_value*/, bool* /*value_changed*/) const override { static int prefix_len = sizeof(int64_t) * 2; if ((int)key.size() < prefix_len) { return false; } TableKey table_key(key); int64_t region_id = table_key.extract_i64(0); std::string* end_key = get_end_key(region_id); if (end_key == nullptr || end_key->empty()) { return false; } if (is_binlog_region(region_id)) { static int64_t ttl_ms = FLAGS_rocks_binlog_ttl_days * 24 * 60 * 60 * 1000; rocksdb::Slice pure_key(key); pure_key.remove_prefix(2 * sizeof(int64_t)); int64_t commit_tso = ttl_decode(pure_key); int64_t expire_ts_ms = (commit_tso >> tso::logical_bits) + ttl_ms; int64_t current_ts_ms = tso::clock_realtime_ms(); // DB_WARNING("binglog compaction filter, region_id: %ld, ttl_tso: %ld, commit_tso: %ld, expire_tso: %ld, current_tso: %ld", // region_id, ttl_ms, commit_tso, expire_ts_ms, current_ts_ms); if (current_ts_ms > expire_ts_ms) { return true; } return false; } int64_t index_id = table_key.extract_i64(sizeof(int64_t)); // cstore, primary column key format: index_id = table_id(32byte) + field_id(32byte) if ((index_id & SIGN_MASK_32) != 0) { index_id = index_id >> 32; } auto index_info = _factory->get_split_index_info(index_id); if (index_info == nullptr) { return false; } //int ret1 = 0; int ret2 = 0; if (index_info->type == pb::I_PRIMARY || index_info->is_global) { ret2 = end_key->compare(0, std::string::npos, key.data() + prefix_len, key.size() - prefix_len); // DB_WARNING("split compaction filter, region_id: %ld, index_id: %ld, end_key: %s, key: %s, ret: %d", // region_id, index_id, rocksdb::Slice(end_key).ToString(true).c_str(), // key.ToString(true).c_str(), ret2); return (ret2 <= 0); } else if (index_info->type == pb::I_UNIQ || index_info->type == pb::I_KEY) { auto pk_info = _factory->get_split_index_info(index_info->pk); if (pk_info == nullptr) { return false; } rocksdb::Slice key_slice(key); key_slice.remove_prefix(sizeof(int64_t) * 2); return !Transaction::fits_region_range(key_slice, value, nullptr, end_key, *pk_info, *index_info); } return false; } void set_end_key(int64_t region_id, const std::string& end_key) { std::string* old_key = get_end_key(region_id); // 已存在不更新 if (old_key != nullptr && *old_key == end_key) { return; } auto call = [region_id, end_key](KeyMap& key_map) { std::string* new_key = new std::string(end_key); key_map[region_id] = new_key; }; _range_key_map.modify(call); } std::string* get_end_key(int64_t region_id) const { auto iter = _range_key_map.read()->seek(region_id); if (iter != nullptr) { return *iter; } return nullptr; } void set_binlog_region(int64_t region_id) { auto call = [this, region_id](BinlogSet& region_id_set) -> int { region_id_set.insert(region_id); return 1; }; _binlog_region_id_set.Modify(call); } bool is_binlog_region(int64_t region_id) const { DoubleBufBinlog::ScopedPtr ptr; if (_binlog_region_id_set.Read(&ptr) == 0) { auto iter = ptr->find(region_id); if (iter != ptr->end()) { return true; } } return false; } private: SplitCompactionFilter() { _factory = SchemaFactory::get_instance(); _range_key_map.read_background()->init(12301); _range_key_map.read()->init(12301); } // region_id => end_key mutable DoubleBufKey _range_key_map; mutable DoubleBufBinlog _binlog_region_id_set; SchemaFactory* _factory; }; }//namespace /* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */ <|start_filename|>include/exec/exec_node.h<|end_filename|> // Copyright (c) 2018-present Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <vector> #include "table_record.h" #include "expr_node.h" #include "row_batch.h" #include "proto/plan.pb.h" #include "proto/meta.interface.pb.h" #include "mem_row_descriptor.h" #include "runtime_state.h" namespace baikaldb { class RuntimeState; class QueryContext; class ExecNode { public: ExecNode() { } virtual ~ExecNode() { for (auto& e : _children) { delete e; e = nullptr; } } virtual int init(const pb::PlanNode& node); /* ret: 0 - SUCCESS * -1 - ERROR * -2 - EMPTY_RESULT */ virtual int expr_optimize(QueryContext* ctx); int common_expr_optimize(std::vector<ExprNode*>* exprs); //input: 需要下推的条件 //input_exprs 既是输入参数,也是输出参数 //output:能推的条件尽量下推,不能推的条件做一个filter node, 连接到节点的上边 virtual int predicate_pushdown(std::vector<ExprNode*>& input_exprs); virtual void remove_additional_predicate(std::vector<ExprNode*>& input_exprs); void add_filter_node(const std::vector<ExprNode*>& input_exprs); void get_node(const pb::PlanNodeType node_type, std::vector<ExecNode*>& exec_nodes); ExecNode* get_node(const pb::PlanNodeType node_type); ExecNode* get_parent() { return _parent; } void join_get_scan_nodes(const pb::PlanNodeType node_type, std::vector<ExecNode*>& exec_nodes); bool need_seperate(); virtual int open(RuntimeState* state); virtual int get_next(RuntimeState* state, RowBatch* batch, bool* eos) { *eos = true; return 0; } virtual void close(RuntimeState* state) { _num_rows_returned = 0; _return_empty = false; for (auto e : _children) { e->close(state); } } virtual void reset(RuntimeState* state) { _num_rows_returned = 0; _return_empty = false; for (auto e : _children) { e->reset(state); } } virtual std::vector<ExprNode*>* mutable_conjuncts() { return NULL; } virtual void find_place_holder(std::map<int, ExprNode*>& placeholders) { for (size_t idx = 0; idx < _children.size(); ++idx) { _children[idx]->find_place_holder(placeholders); } } virtual void replace_slot_ref_to_literal(const std::set<int64_t>& sign_set, std::map<int64_t, std::vector<ExprNode*>>& literal_maps) { for (auto child : _children) { if (child->node_type() == pb::JOIN_NODE || child->node_type() == pb::APPLY_NODE) { continue; } child->replace_slot_ref_to_literal(sign_set, literal_maps); } } virtual void show_explain(std::vector<std::map<std::string, std::string>>& output) { for (auto child : _children) { child->show_explain(output); } } ExecNode* get_specified_node(const pb::PlanNodeType node_type) { if (node_type == _node_type) { return this; } for (auto child : _children) { if (child->node_type() == pb::JOIN_NODE || child->node_type() == pb::APPLY_NODE) { return nullptr; } ExecNode* exec_node = child->get_specified_node(node_type); if (exec_node != nullptr) { return exec_node; } } return nullptr; } void set_parent(ExecNode* parent_node) { _parent = parent_node; } void create_trace(); void set_trace(pb::TraceNode* trace) { _trace = trace; } pb::TraceNode* get_trace() { return _trace; } void add_child(ExecNode* exec_node) { if (exec_node == nullptr) { return ; } _children.push_back(exec_node); exec_node->set_parent(this); } void add_child(ExecNode* exec_node, size_t idx) { if (exec_node == nullptr || idx > _children.size()) { return ; } _children.insert(_children.begin() + idx, exec_node); exec_node->set_parent(this); } void clear_children() { for (auto child : _children) { if (child->_parent == this) { child->_parent = NULL; } } _children.clear(); } int replace_child(ExecNode* old_child, ExecNode* new_child) { for (auto& child : _children) { if (child == old_child) { new_child->set_parent(this); if (old_child->_parent == this) { old_child->_parent = NULL; } child = new_child; return 0; } } return -1; } size_t children_size() { return _children.size(); } ExecNode* children(size_t idx) { if (_children.size() == 0) { return nullptr; } return _children[idx]; } std::vector<ExecNode*> children() { return _children; } std::vector<ExecNode*>* mutable_children() { return &_children; } void set_return_empty() { _return_empty = true; for (auto child : _children) { child->set_return_empty(); } } bool reached_limit() { return _limit != -1 && _num_rows_returned >= _limit; } void set_limit(int64_t limit) { _limit = limit; } virtual void reset_limit(int64_t limit) { _limit = limit; for (auto child : _children) { child->reset_limit(limit); } } int64_t get_limit() { return _limit; } pb::PlanNode* mutable_pb_node() { return &_pb_node; } const pb::PlanNode& pb_node() { return _pb_node; } pb::PlanNodeType node_type() { return _node_type; } bool is_filter_node() { return _node_type == pb::TABLE_FILTER_NODE || _node_type == pb::WHERE_FILTER_NODE || _node_type == pb::HAVING_FILTER_NODE; } std::map<int64_t, pb::RegionInfo>& region_infos() { return _region_infos; } void set_region_infos(std::map<int64_t, pb::RegionInfo> region_infos) { _region_infos.swap(region_infos); } //除了表达式外大部分直接沿用保存的pb virtual void transfer_pb(int64_t region_id, pb::PlanNode* pb_node); static void create_pb_plan(int64_t region_id, pb::Plan* plan, ExecNode* root); static int create_tree(const pb::Plan& plan, ExecNode** root); static void destroy_tree(ExecNode* root) { delete root; } virtual int push_cmd_to_cache(RuntimeState* state, pb::OpType op_type, ExecNode* store_request, int seq_id); virtual int push_cmd_to_cache(RuntimeState* state, pb::OpType op_type, ExecNode* store_request); std::map<int64_t, std::vector<SmartRecord>>& get_return_records() { return _return_records; } virtual pb::LockCmdType lock_type() { return pb::LOCK_INVALID; } protected: int64_t _limit = -1; int64_t _num_rows_returned = 0; bool _is_explain = false; bool _return_empty = false; pb::PlanNodeType _node_type; std::vector<ExecNode*> _children; ExecNode* _parent = nullptr; pb::PlanNode _pb_node; std::map<int64_t, pb::RegionInfo> _region_infos; pb::TraceNode* _trace = nullptr; //返回给baikaldb的结果 std::map<int64_t, std::vector<SmartRecord>> _return_records; private: static int create_tree(const pb::Plan& plan, int* idx, ExecNode* parent, ExecNode** root); static int create_exec_node(const pb::PlanNode& node, ExecNode** exec_node); }; typedef std::shared_ptr<pb::TraceNode> SmartTrace; } /* vim: set ts=4 sw=4 sts=4 tw=100 */
BuildJet/BaikalDB
<|start_filename|>meowmeow.cpp<|end_filename|> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <chrono> #include <utility> #include "constexprhash.h" // dummy check that hashes is compile time constants void check(uint32_t h) { switch (h) { case djb2a("123456789"): case fnv1a("123456789"): case crc32("123456789"): case "123456789"_H: break; } } // regular version of murmur hash 3 namespace MurmurHash3 { constexpr uint32_t body(const uint32_t *k, size_t n, uint32_t h) { return n < 1 ? h : body(k + 1, n - 1, hmix(h, *k)); } } // namespace MurmurHash3 uint32_t murmur3(const void *p, size_t size, uint32_t seed) { using namespace MurmurHash3; uint32_t h = seed; h = body(static_cast<const uint32_t *>(p), size / 4, h); h = tail(static_cast<const char *>(p) + (size & ~3), size & 3, h); return fmix(h ^ size); } // simple hash map with linear lookup template <typename T, size_t N> struct dict { uint32_t keys[N] = {}; T values[N]; T &operator[](uint32_t key) { return setdefault(key, T()); } T &setdefault(uint32_t key, T &&defval) { auto i = key % N; for (; keys[i]; i = (i + 1) % N) if (keys[i] == key) return values[i]; keys[i] = key; return values[i] = std::move(defval); } void remove(uint32_t key) { auto i = key % N; for (; keys[i] != key; i = (i + 1) % N) if (keys[i] == 0) return; for (auto j = (i + 1) % N; keys[j]; j = (j + 1) % N) { auto k = keys[j] % N; if (i <= j ? (i >= k) || (k > j) : (i >= k) || (k > j)) { keys[i] = keys[j]; values[i] = std::move(values[j]); i = j; } } keys[i] = 0; } const T &lookup(uint32_t key, const T &defval) const { for (auto i = key % N; keys[i]; i = (i + 1) % N) if (keys[i] == key) return values[i]; return defval; } const T *find(uint32_t key) const { for (auto i = key % N; keys[i]; i = (i + 1) % N) if (keys[i] == key) return values + i; return nullptr; } }; int main(int argc, char **argv) { uint32_t seed = 0; int benchmark = 0; int hex = 0; int ch; while ((ch = getopt(argc, argv, "s:b:h")) != -1) { switch (ch) { case 's': { char *endptr; seed = strtol(optarg, &endptr, 0); if (*endptr) { fprintf(stderr, "%s: bad seed value -- %s\n", argv[0], optarg); exit(EXIT_FAILURE); } break; } case 'b': benchmark = strtol(optarg, nullptr, 0); break; case 'h': hex = 1; break; case '?': default: fprintf(stderr, "usage: %s [-s seed] [-b count] [-h] [strings ...]\n", argv[0]); exit(EXIT_FAILURE); } } if (benchmark) { size_t size = benchmark * (1 << 20); void *p = malloc(size); memset(p, rand() % 64, size); auto start = std::chrono::high_resolution_clock::now(); auto hash = murmur3(p, size, seed); auto end = std::chrono::high_resolution_clock::now(); free(p); std::chrono::duration<double> elapsed = end - start; fprintf(stderr, "benchmark hashing: %d MiB (%#.8x)\nelapsed time: %f (%.2f MiB/sec)\n", benchmark, hash, elapsed.count(), size / elapsed.count() / (1 << 20)); } dict<const char *, 1 << 16> map; for (int arg = optind; arg < argc; ++arg) { uint32_t h = murmur3(argv[arg], strlen(argv[arg]), seed); printf(hex ? "%#.8x %s\n" : "%10u %s\n", h, argv[arg]); if (map.find(h)) { if (strcmp(map[h], argv[arg])) printf("! %s %s\n", map[h], argv[arg]); continue; } map[h] = argv[arg]; } return 0; } <|start_filename|>constexprhash.h<|end_filename|> #pragma once #include <stdint.h> constexpr uint32_t djb2a(const char *s, uint32_t h = 5381) { return !*s ? h : djb2a(s + 1, 33 * h ^ (uint8_t)*s); } constexpr uint32_t fnv1a(const char *s, uint32_t h = 0x811C9DC5) { return !*s ? h : fnv1a(s + 1, (h ^ (uint8_t)*s) * 0x01000193); } constexpr uint32_t CRC32_TABLE[] = { 0x00000000, 0x1DB71064, 0x3B6E20C8, 0x26D930AC, 0x76DC4190, 0x6B6B51F4, 0x4DB26158, 0x5005713C, 0xEDB88320, 0xF00F9344, 0xD6D6A3E8, 0xCB61B38C, 0x9B64C2B0, 0x86D3D2D4, 0xA00AE278, 0xBDBDF21C}; constexpr uint32_t crc32(const char *s, uint32_t h = ~0) { #define CRC4(c, h) (CRC32_TABLE[((h) & 0xF) ^ (c)] ^ ((h) >> 4)) return !*s ? ~h : crc32(s + 1, CRC4((uint8_t)*s >> 4, CRC4((uint8_t)*s & 0xF, h))); #undef CRC4 } namespace MurmurHash3 { constexpr uint32_t rotl(uint32_t x, int8_t r) { return (x << r) | (x >> (32 - r)); } constexpr uint32_t kmix(uint32_t k) { return rotl(k * 0xCC9E2D51, 15) * 0x1B873593; } constexpr uint32_t hmix(uint32_t h, uint32_t k) { return rotl(h ^ kmix(k), 13) * 5 + 0xE6546B64; } constexpr uint32_t shlxor(uint32_t x, int8_t l) { return (x >> l) ^ x; } constexpr uint32_t fmix(uint32_t h) { return shlxor(shlxor(shlxor(h, 16) * 0x85EBCA6B, 13) * 0xC2B2AE35, 16); } constexpr uint32_t body(const char *s, size_t n, uint32_t h) { return n < 4 ? h : body(s + 4, n - 4, hmix(h, s[0] | (s[1] << 8) | (s[2] << 16) | (s[3] << 24))); } constexpr uint32_t tail(const char *s, size_t n, uint32_t h) { return h ^ kmix(n == 3 ? s[0] | (s[1] << 8) | (s[2] << 16) : n == 2 ? s[0] | (s[1] << 8) : n == 1 ? s[0] : 0); } constexpr uint32_t shash(const char *s, size_t n, uint32_t seed) { return fmix(tail(s + (n & ~3), n & 3, body(s, n, seed)) ^ n); } } // namespace MurmurHash3 constexpr uint32_t operator"" _H(const char *s, size_t size) { return MurmurHash3::shash(s, size, 0); } <|start_filename|>Makefile<|end_filename|> meowmeow: meowmeow.cpp constexprhash.h ${CXX} -std=c++11 -g -Wall -Wextra meowmeow.cpp -o meowmeow clean: rm -f meowmeow all: meowmeow
vivkin/constexprhash
<|start_filename|>src/components/HistoryItemList.js<|end_filename|> import React from 'react'; import styled from 'styled-components'; import {useOutlet} from 'reconnect.js'; import HistoryItem from './HistoryItem'; import {ScrollBarCss} from './Widgets'; function HistoryItemList(props) { const {items} = props; const [showScrollBar, setShowScrollBar] = React.useState(false); const [dimension] = useOutlet('dimension'); const itemWidth = dimension?.innerWidth > 600 ? 300 : 210; return ( <HistoryListWrapper innerWidth={(items.length + 1) * itemWidth} showScrollBar={showScrollBar} onMouseEnter={() => setShowScrollBar(true)} onMouseLeave={() => setShowScrollBar(false)}> <div className="items-wrapper"> {items.map((item, idx) => { return <HistoryItem key={idx} item={item} width={itemWidth} />; })} </div> </HistoryListWrapper> ); } const HistoryListWrapper = styled.div` overflow: auto; width: 100%; & > .items-wrapper { overflow: auto; padding: 20px 0px 36px 30px; width: ${(props) => props.innerWidth}px; display: flex; } ${ScrollBarCss}; `; export default HistoryItemList; <|start_filename|>src/components/ConfItemList.js<|end_filename|> import React from 'react'; import styled from 'styled-components'; import {navigate} from 'gatsby'; import {useOutlet} from 'reconnect.js'; import ConfItem from './ConfItem'; import {ScrollBarCss} from './Widgets'; import {useOutletSetter} from 'reconnect.js'; function ConfItemList(props) { const {items} = props; const [dimension] = useOutlet('dimension'); const [showScrollBar, setShowScrollBar] = React.useState(false); const setSelectedConf = useOutletSetter('selectedConf'); const itemWidth = dimension?.innerWidth > 600 ? 300 : 210; return ( <ListWrapper innerWidth={(items.length + 1) * itemWidth} showScrollBar={showScrollBar} onMouseEnter={() => setShowScrollBar(true)} onMouseLeave={() => setShowScrollBar(false)}> <div className="items-wrapper"> {items.map((item, idx) => ( <ConfItem key={idx} item={item} width={itemWidth} onInfoClick={(e) => { const rect = e.target.getBoundingClientRect(); setSelectedConf({ item, rect: { top: rect.top, left: rect.left, width: rect.width, height: rect.height, }, }); }} onWatchClick={() => { navigate(`/player?conf=${item.id}`); }} /> ))} </div> </ListWrapper> ); } const ListWrapper = styled.div` overflow: auto; width: 100%; & > .items-wrapper { padding: 20px 0px 36px 30px; width: ${(props) => props.innerWidth}px; display: flex; flex-wrap: nowrap; } ${ScrollBarCss} `; export default ConfItemList; <|start_filename|>src/utils/groupConfByYear.js<|end_filename|> export default function groupConfByYear(channels) { return ['2021', '2020', '2019', '2018', '2017', '2016', '2015'].map( (yearLabel) => { const items = []; for (const channel of channels) { for (const item of channel.items) { if (item.title.indexOf(yearLabel) > -1) { items.push({ channel, ...item, }); } } } return { year: yearLabel, items, }; }, ); } <|start_filename|>src/components/BannerImage.js<|end_filename|> import React from 'react'; import {useStaticQuery, graphql} from 'gatsby'; import styled from 'styled-components'; import Img from 'gatsby-image'; function BannerImage(props) { const data = useStaticQuery(graphql` query { placeholderImage: file(relativePath: {eq: "react-icon.png"}) { childImageSharp { fluid(maxWidth: 668) { ...GatsbyImageSharpFluid } } } } `); if (!data?.placeholderImage?.childImageSharp?.fluid) { return <div>Picture not found</div>; } return ( <Wrapper> <Img fluid={data.placeholderImage.childImageSharp.fluid} imgStyle={{ objectFit: 'contain', width: '100%', maxHeight: 668, animation: 'infinite-spinning 7.2s infinite', }} style={{maxHeight: 668}} /> </Wrapper> ); } const Wrapper = styled.div` @keyframes infinite-spinning { 0% { transform: rotate(0deg) scale(1); } 50% { transform: rotate(180deg) scale(1); } 100% { transform: rotate(360deg) scale(1); } } `; export default BannerImage; <|start_filename|>src/templates/FavoritePage.js<|end_filename|> import React from 'react'; import {navigate} from 'gatsby'; import styled from 'styled-components'; import {useOutlet} from 'reconnect.js'; import * as AppContext from '../AppContext'; import NavBar from '../components/NavBar'; import FavoriteItem from '../components/FavoriteItem'; function FavoritePage(props) { const app = React.useContext(AppContext.Context); const favorites = app.favoriteCache || []; const [dimension] = useOutlet('dimension'); function calcGridLayout() { if (!dimension) { return null; } const margin = 20 * 2; const gutter = 20; const width = dimension.innerWidth < 1024 ? dimension.innerWidth : 1024; let itemPerRow = 1; if (width > 720) { itemPerRow = 3; } else if (width > 400) { itemPerRow = 2; } const r = favorites.length % itemPerRow; const gridItems = r === 0 ? favorites : [ ...favorites, ...Array.from({length: itemPerRow - r}).map((_) => null), ]; return { itemPerRow, itemWidth: (width - margin - (itemPerRow - 1) * gutter) / itemPerRow, items: gridItems, }; } const gridLayout = calcGridLayout(); return ( <Wrapper> <NavBar explicitTitle="My Favorite Talks" onBackClick={() => navigate('/')} /> {gridLayout && ( <div className="content"> {gridLayout.items.map((fav, idx) => ( <FavoriteItem key={idx} item={fav} style={{width: gridLayout.itemWidth}} /> ))} </div> )} </Wrapper> ); } const Wrapper = styled.div` min-height: 100vh; background-color: #4c4c4c; & > .navbar { position: fixed; top: 0; left: 0; width: 100%; z-index: 3; } & > .content { padding: 80px 20px; min-height: 100vh; max-width: 1024px; margin: 0px auto; display: flex; justify-content: space-between; flex-wrap: wrap; } `; export default FavoritePage; <|start_filename|>scripts/snapshot.js<|end_filename|> const fs = require('fs'); const path = require('path'); const chalk = require('chalk'); const fetch = require('node-fetch'); const execa = require('execa'); const {transformConfTalkData} = require('../src/utils/transformData'); const log = console.log; const playlistPath = 'static/playlistitems'; const snapshotPath = 'static/snapshots'; function readJsonFile(filepath) { try { return JSON.parse(fs.readFileSync(filepath, 'utf-8')); } catch (ex) { log(chalk.red('ERROR: ') + 'fail to read ' + filepath); return null; } } async function fetchViewStats(videoIdList) { const apiKey = '<KEY>'; const statsResp = await fetch( `https://youtube.googleapis.com/youtube/v3/videos?part=statistics&id=${videoIdList.join( ',', )}&key=${apiKey}&maxResults=100`, { header: { 'Content-Type': 'application/json', Accept: 'application/json', }, }, ); return statsResp.json(); } async function restructureSnapshots() { const _timestamps = fs .readdirSync(snapshotPath) .filter((fname) => fname !== 'latest.json' && fname !== 'previous.json') .map((fname) => parseInt(fname.split('.')[0])) .sort() .reverse(); const [latest, ...timestamps] = _timestamps; const THRESHOLD = 7 * 24 * 3600 * 1000; let previous = null; for (const ts of timestamps) { if (latest - ts > THRESHOLD) { previous = ts; break; } } if (!previous) { previous = timestamps[timestamps.length - 1]; } await execa('cp', [ path.join(snapshotPath, `${previous}.json`), path.join(snapshotPath, `previous.json`), ]); await execa('cp', [ path.join(snapshotPath, `${latest}.json`), path.join(snapshotPath, `latest.json`), ]); } async function snapshot() { log(chalk.gray('scanning static/playlistitems') + `\n`); const playlists = fs.readdirSync(playlistPath); const snapshotJson = {}; log('total ' + chalk.gray(`total ${playlists.length}`) + ' playlists'); for (const fname of playlists) { log('processing ' + chalk.gray(fname)); const filepath = path.join(playlistPath, fname); const {items} = readJsonFile(filepath); const videoIdList = []; items.forEach((talk, idx) => { const {videoId} = talk.contentDetails; snapshotJson[videoId] = transformConfTalkData(talk, idx); videoIdList.push(videoId); }); const statsRespJson = await fetchViewStats(videoIdList); for (const item of statsRespJson.items) { snapshotJson[item.id].stats = item.statistics; } } fs.writeFileSync( path.join(snapshotPath, `${new Date().getTime()}.json`), JSON.stringify(snapshotJson, null, 2), ); await restructureSnapshots(); log(chalk.green('Done')); return true; } module.exports = { snapshot, }; <|start_filename|>gatsby-node.js<|end_filename|> const fs = require('fs'); const path = require('path'); const util = require('util'); const readFile = util.promisify(fs.readFile); const {matchConferenceByTitle} = require('./src/utils/matchConferenceByTitle'); const {transformAllChannelsData} = require('./src/utils/transformData'); const { getMostViewed, getNewReleased, getRecentViewed, } = require('./src/utils/getVideoByStat'); exports.createPages = async ({graphql, actions}) => { const {createPage} = actions; const ytChannelsNode = ( await graphql( ` query MyQuery { allFile(filter: {name: {eq: "ytChannels"}}) { edges { node { name dir relativePath } } } } `, ) ).data.allFile.edges[0].node; const ytChannels = JSON.parse( ( await readFile(path.join(ytChannelsNode.dir, ytChannelsNode.relativePath)) ).toString(), ); const confChannelMap = {}; for (const ytChannel of ytChannels) { const ytChannelPlaylist = JSON.parse( await readFile(path.join('data/playlist', ytChannel.name + '.json')), ); // every ytChannelPlaylist is a conference at a particular time, ex: "React Europe 2019", // try to find out which "conference channel" (ex: "React Europ") it belongs to for (const confEvent of ytChannelPlaylist.items) { const matched = matchConferenceByTitle({ title: confEvent.snippet.title, conferences: ytChannel.conferences, }); if (matched) { if (!confChannelMap[matched.name]) { confChannelMap[matched.name] = { name: matched.name, display: matched.display, items: [], }; } confChannelMap[matched.name].items.push(confEvent); } } } const baseContext = { ytChannels, channels: transformAllChannelsData( Object.keys(confChannelMap).map((key) => confChannelMap[key]), ), }; createPage({ path: `/`, component: path.resolve(`src/templates/LandingPage.js`), context: { ...baseContext, classicVideos: getMostViewed(10), trendingNowVideos: getRecentViewed(10), newReleasedVideos: getNewReleased(10), }, }); createPage({ path: `/player`, component: path.resolve(`src/templates/PlayerPage.js`), context: baseContext, }); createPage({ path: `/favorites`, component: path.resolve(`src/templates/FavoritePage.js`), context: baseContext, }); }; <|start_filename|>scripts/cli.js<|end_filename|> const {program} = require('commander'); const chalk = require('chalk'); const log = console.log; const fs = require('fs'); const {snapshot} = require('./snapshot'); const {fetchAllChannels} = require('./fetch-data'); program.version('0.0.1'); program .command('snapshot') .description('create snapshot for current dataset') .action(async () => { log(chalk.green('CLI command: snapshot') + `\n`); await snapshot(); }); program .command('fetch') .description('fetch data from youtube') .action(async () => { log(chalk.green('CLI command: fetch') + `\n`); await fetchAllChannels(); }); program.parse(process.argv); <|start_filename|>src/components/ConfDetail.js<|end_filename|> import React from 'react'; import styled from 'styled-components'; import {useOutlet} from 'reconnect.js'; import * as AppContext from '../AppContext'; import TalkItem from '../components/TalkItem'; const TranState = { NONE: 0, SRC: 1, DEST: 2, }; const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); function ConfDetail(props) { const [selectedConf] = useOutlet('selectedConf'); const [data, setData] = React.useState({}); const [tranState, setTranState] = React.useState(TranState.NONE); const [showDetail, setShowDetail] = React.useState(false); const [confDetail, setConfDetail] = React.useState(null); const [loadingProgress, setLoadingProgress] = React.useState(false); const app = React.useContext(AppContext.Context); React.useEffect(() => { async function animIn() { if (selectedConf) { const {rect, item} = selectedConf; const padding = 20; const destWidth = (window.innerWidth > window.innerHeight ? window.innerHeight : window.innerWidth) - 2 * padding; const destLeft = (window.innerWidth - destWidth) / 2; const destHeight = (destWidth / 16) * 9; const destTop = (window.innerHeight - destHeight) / 2; const destData = { top: destTop, left: destLeft, width: destWidth, height: destHeight, }; setData({ imgSrc: item.thumbnailStd, srcData: rect, destData, }); setTranState(TranState.SRC); await delay(50); setTranState(TranState.DEST); setLoadingProgress(true); // eslint-disable-next-line no-unused-vars const [_, resp] = await Promise.all([ delay(600), app.actions.fetchPlaylistItems(selectedConf.item.id), ]); setLoadingProgress(false); setConfDetail(resp); setShowDetail(true); } } animIn(); }, [selectedConf, app.actions]); async function animOut() { setShowDetail(false); setLoadingProgress(false); await delay(500); setTranState(TranState.SRC); await delay(300); setTranState(TranState.NONE); setConfDetail(null); } if (tranState === TranState.NONE) { return null; } function getDisplayData() { if (tranState === TranState.SRC) { return {...data.srcData, visible: true}; } else if (tranState === TranState.DEST) { return {...data.destData, visible: true}; } else { return {...data.srcData, visible: false}; } } const displayData = getDisplayData(); const conf = selectedConf?.item; return ( <Wrapper displayInfo={displayData} showDetail={showDetail} loadingProgress={loadingProgress} onClick={animOut}> <figure> <img src={data.imgSrc} alt="conference" /> <div className="spinner" /> </figure> <section> {conf && ( <> <h2>{conf.title}</h2> {(confDetail?.items || []).map((talk, idx) => ( <TalkItem key={idx} confId={conf.id} idx={idx} talk={talk} showThumbnail={false} /> ))} </> )} </section> </Wrapper> ); } const Wrapper = styled.div` position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; z-index: 100; overflow: auto; visibility: ${(props) => (props.displayInfo.visible ? 'visible' : 'none')}; pointer-events: ${(props) => (props.displayInfo.visible ? 'auto' : 'none')}; overscroll-behavior-y: none; opacity: ${(props) => (props.displayInfo.visible ? 1 : 0)}; transition: 200ms; @keyframes conf-loading { 0% { width: 0%; opacity: 0; } 100% { width: 100%; opacity: 1; } } & > figure { position: absolute; top: ${(props) => props.displayInfo.top}px; left: ${(props) => props.displayInfo.left}px; width: ${(props) => props.displayInfo.width}px; height: ${(props) => props.displayInfo.height}px; opacity: ${(props) => (props.displayInfo.visible ? 1 : 0)}; transition: 200ms; box-shadow: 0 19px 38px rgba(0, 0, 0, 0.75), 0 15px 12px rgba(0, 0, 0, 0.6); margin: 0; padding: 0; & > img { width: 100%; height: 100%; object-fit: cover; } & > .spinner { position: absolute; left: 0; bottom: 0; height: 4px; background-color: red; ${(props) => props.loadingProgress && `animation: conf-loading 600ms infinite backwards;`}; } } & > section { position: absolute; top: ${(props) => props.displayInfo.top + props.displayInfo.height}px; left: ${(props) => props.displayInfo.left}px; width: ${(props) => props.displayInfo.width}px; visibility: ${(props) => (props.showDetail ? 'visible' : 'none')}; max-height: ${(props) => (props.showDetail ? '10000px' : '0px')}; opacity: ${(props) => (props.showDetail ? 1 : 0)}; transition: 500ms; overflow: hidden; background-color: #888; color: white; padding: 0 20px; box-shadow: 0 19px 38px rgba(0, 0, 0, 0.75), 0 15px 12px rgba(0, 0, 0, 0.6); & > .talk-item { margin-bottom: 20px; } } `; export default ConfDetail; <|start_filename|>src/components/Modal.js<|end_filename|> import React, {useEffect, useState} from 'react'; import styled from 'styled-components'; import {useOutlet} from 'reconnect.js'; function Modal(props) { const [modalContent] = useOutlet('modal'); const [content, setContent] = useState(modalContent); const [visible, setVisible] = useState(false); useEffect(() => { if (modalContent) { setContent(modalContent); setVisible(true); } else { setVisible(false); } }, [modalContent]); return ( <Wrapper visible={visible}> <div className="backdrop" onClick={() => { setVisible(false); }} /> <div className="content">{content}</div> </Wrapper> ); } const Wrapper = styled.div` top: 0; left: 0; right: 0; bottom: 0; position: fixed; z-index: 1; align-items: center; justify-content: center; display: flex; visibility: ${(props) => (props.visible ? 'visible' : 'collapse')}; & > .backdrop { position: absolute; top: 0; left: 0; right: 0; bottom: 0; transition: opacity 1s ease; opacity: ${(props) => (props.visible ? 1 : 0)}; background-color: rgba(0, 0, 0, 0.7); visibility: ${(props) => (props.visible ? 'visible' : 'collapse')}; } & > .content { display: flex; align-items: center; justify-content: center; position: absolute; top: ${(props) => (props.visible ? '100px' : '0')}; transition: all 300ms ease; transform: ${(props) => props.visible ? 'translateY(0)' : 'translateY(-100%)'}; } `; export default Modal; <|start_filename|>src/templates/LandingPage.js<|end_filename|> import React from 'react'; import styled from 'styled-components'; import {useNewOutlet} from 'reconnect.js'; import * as AppContext from '../AppContext'; import * as Widgets from '../components/Widgets'; import SEO from '../components/seo'; import NavBar from '../components/NavBar'; import BannerImage from '../components/BannerImage'; import ConfItemList from '../components/ConfItemList'; import HistoryItemList from '../components/HistoryItemList'; import VideoItemList from '../components/VideoItemList'; import SelectChannelBtn from '../components/SelectChannelBtn'; import groupConfByYear from '../utils/groupConfByYear'; import ConfDetail from '../components/ConfDetail'; import WidgetWithCollapse from '../components/WidgetWithCollapse'; function LandingPage(props) { const app = React.useContext(AppContext.Context); const [selectedChannel, setSelectedChannel] = React.useState(null); const { channels, classicVideos, trendingNowVideos, newReleasedVideos, } = props.pageContext; const confById = React.useMemo( () => channels.reduce((acc, channel) => { for (const conf of channel.items) { acc[conf.id] = conf; } return acc; }, {}), [channels], ); const confListByYear = groupConfByYear( selectedChannel ? [selectedChannel] : channels, ); const recentWatchedConfs = Object.keys(app.watchHistoryCache) .map((k) => ({ conf: confById[k], ...app.watchHistoryCache[k], })) .sort((a, b) => b.timestamp - a.timestamp); useNewOutlet('selectedConf', null); return ( <> <SEO title="React Conferences" /> <Wrapper> <div style={{position: 'relative'}}> <BannerImage /> <NavBar selectedChannel={selectedChannel} setSelectedChannel={setSelectedChannel} /> </div> <div className="content"> {newReleasedVideos.length > 0 && !selectedChannel && ( <div className="new-release"> <Widgets.FlexRow> <Label>New Releases</Label> <Badge>New Releases Videos</Badge> </Widgets.FlexRow> <VideoItemList items={newReleasedVideos} /> </div> )} {trendingNowVideos.length > 0 && !selectedChannel && ( <div className="trending-now"> <Widgets.FlexRow> <Label>Trending Now</Label> <Badge>Most Populars Videos</Badge> </Widgets.FlexRow> <VideoItemList items={trendingNowVideos} /> </div> )} {recentWatchedConfs.length > 0 && !selectedChannel && ( <div className="recent-watched" style={{backgroundColor: '#2e2e2e'}}> <Widgets.FlexRow> <Label>Keep Watching</Label> </Widgets.FlexRow> <HistoryItemList items={recentWatchedConfs} /> </div> )} {confListByYear.map((confList, idx) => { if (!confList.items?.length) { return null; } return ( <div key={idx} style={{backgroundColor: '#212121'}}> <Widgets.FlexRow> <Label>{confList.year}</Label> <Badge>{confList.items.length}</Badge> </Widgets.FlexRow> <ConfItemList items={confList.items} /> </div> ); })} {classicVideos.length > 0 && !selectedChannel && ( <div className="classic"> <Widgets.FlexRow> <Label>Classic</Label> <Badge>Most Cumulative Views</Badge> </Widgets.FlexRow> <VideoItemList items={classicVideos} /> </div> )} </div> <ConfDetail /> </Wrapper> <SelectChannelBtn channels={channels} selectedChannel={selectedChannel} setSelectedChannel={setSelectedChannel} /> <WidgetWithCollapse /> </> ); } const Label = styled.div` color: white; font-size: 22px; font-family: Roboto; font-style: italic; letter-spacing: 1px; margin: 16px 10px 0px 30px; `; const Badge = styled(Widgets.Badge)` margin-top: 8px; `; const Wrapper = styled.div` min-height: 100vh; background-color: #383838; & > .navbar { position: fixed; top: 0; left: 0; width: 100%; z-index: 3; } & > .content { padding: 20px 0px 20px 0px; transform: translateY(-160px); } @media only screen and (max-width: 600px) { & > .content { transform: translateY(-90px); } } `; export default LandingPage; <|start_filename|>src/components/TalkItem.js<|end_filename|> import React from 'react'; import styled from 'styled-components'; import {navigate} from 'gatsby'; import * as Widgets from './Widgets'; import * as AppContext from '../AppContext'; import ProgressBar from './ProgressBar'; import { CheckBox, CheckBoxOutlineBlank, PlayCircleOutline, } from '@styled-icons/material'; import {Heart, HeartFill} from '@styled-icons/octicons'; import useFavoriteState from '../hooks/useFavoriteState'; function TalkItem(props) { const {confId, talk, idx, currIdx, onItemClick, showThumbnail = true} = props; const largeThumbnail = showThumbnail; const app = React.useContext(AppContext.Context); const videoId = talk.videoId; const progress = app.videoProgressCache[videoId]; const duration = app.videoDurationCache[videoId]; const finished = app.videoFinishedCache[videoId]; const {isInFavorite, toggleFavoriteState} = useFavoriteState({ confId, talkIdx: idx, }); const isPlaying = idx !== undefined && idx === currIdx; const percentage = (duration && 100 * (progress / duration)) || 0; return ( <TalkItemWrapper largeThumbnail={largeThumbnail}> {largeThumbnail && ( <Figure style={{width: '100%'}}> <img src={talk.thumbnail} alt="snapshot for the talk" /> </Figure> )} <div className={'description'}> {!largeThumbnail && ( <Figure style={{ width: 112, height: 70, margin: '10px 0 10px 10px', paddingBottom: 0, }}> <img src={talk.thumbnail} alt="snapshot for the talk" /> </Figure> )} <div style={{padding: 10, flex: 1}}> <div style={{display: 'flex', alignItems: 'center'}}> {isPlaying && ( <Label style={{background: 'green'}}>Now Playing</Label> )} {finished && <Label style={{background: 'grey'}}>Finished</Label>} </div> <div style={{fontSize: 16}}>{talk.title}</div> </div> </div> <Widgets.FlexRow style={{justifyContent: 'flex-end'}}> <Widgets.Button type="text" onClick={(evt) => { evt.stopPropagation(); if (onItemClick) { onItemClick({talk, idx}); } else { navigate(`/player?conf=${confId}&idx=${idx}`); } }}> <PlayCircleOutline size={28} color={'red'} /> </Widgets.Button> <Widgets.Button type="text" onClick={(evt) => { evt.stopPropagation(); toggleFavoriteState({ title: talk.title, thumbnail: talk.thumbnail, }); }}> {isInFavorite ? ( <HeartFill size={24} color={'red'} /> ) : ( <Heart size={24} color={'red'} /> )} </Widgets.Button> <Widgets.Button type="text" onClick={(evt) => { evt.stopPropagation(); app.actions.setVideoFinished(videoId, finished ? false : true); }}> {finished ? ( <CheckBox size={26} color={'red'} /> ) : ( <CheckBoxOutlineBlank size={26} color={'red'} /> )} </Widgets.Button> </Widgets.FlexRow> {idx !== undefined && <Idx>{idx + 1}</Idx>} <ProgressBar percentage={finished ? 100 : percentage} /> </TalkItemWrapper> ); } const TalkItemWrapper = styled.div` margin-bottom: 10px; position: relative; overflow: visible; background-color: white; & > .description { width: 100%; font-size: 14px; font-family: Roboto; display: flex; color: black; } `; const Label = styled.label` font-size: 11px; color: white; border-radius: 4px; padding: 4px 8px; margin: 0 6px 8px 0; `; const Figure = styled.figure` margin: 0; padding: 0; position: relative; background-color: #ccc; width: 100%; padding-bottom: 56.25%; & > img { position: absolute; left: 0; top: 0; width: 100%; height: 100%; object-fit: cover; } `; const Idx = styled.div` position: absolute; top: 0; left: 0; width: 30px; height: 30px; line-height: 30px; text-align: center; background-color: #61dafb; color: black; `; export default TalkItem; <|start_filename|>src/components/WidgetWithCollapse.js<|end_filename|> import styled from 'styled-components'; import React, {useContext, useMemo, useState} from 'react'; import { BookHeart, ChevronDown, ChevronUp, SearchAlt, } from '@styled-icons/boxicons-regular'; import {LogoGithub} from '@styled-icons/ionicons-solid'; import {Context} from '../AppContext'; import Search from './Search'; import {navigate} from '../../.cache/gatsby-browser-entry'; const WidgetWithCollapse = (props) => { const app = useContext(Context); const [isOpen, setIsOpen] = useState(false); const options = useMemo(() => { return [ { icon: isOpen ? ( <ChevronDown color="white" size={26} /> ) : ( <ChevronUp color="white" size={26} /> ), onClick: (e) => { e.stopPropagation(); setIsOpen((prev) => !prev); }, }, { icon: <LogoGithub color="white" size={26} />, onClick: (e) => { e.stopPropagation(); window.open('https://github.com/revtel/reactconf-tv'); }, }, { icon: <SearchAlt color="white" size={26} />, onClick: (e) => { e.stopPropagation(); app.actions.setModal(<Search />); }, }, { icon: <BookHeart color="white" size={26} />, onClick: async (e) => { e.stopPropagation(); await navigate('/favorites'); }, }, ]; }, [app.actions, isOpen]); return ( <Wrapper isOpen={isOpen}> {options.map((opt, idx) => ( <div key={idx} className="option" onClick={opt.onClick} style={{bottom: idx * 60}}> {opt.icon} </div> ))} </Wrapper> ); }; const Wrapper = styled.div` width: 60px; background-color: #4f77e2; height: ${(props) => `calc(60px * ${props.isOpen ? 4 : 1})`}; border-radius: ${(props) => `calc(60px * ${props.isOpen ? 4 : 1} / 2)`}; box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23); cursor: pointer; display: flex; flex-direction: column; align-items: center; justify-content: center; position: fixed; right: 32px; bottom: 112px; overflow-y: hidden; transition: all 300ms ease-in-out; & > .option { height: 60px; width: 60px; border-radius: 30px; display: flex; align-items: center; justify-content: center; position: absolute; bottom: 0; } @media screen and (min-width: 996px) { display: none; } `; export default WidgetWithCollapse; <|start_filename|>src/utils/transformData.js<|end_filename|> // This file has been included both in build time and runtime. // So we avoid using syntax such as optional channing, and export it with commonjs convention function transformAllChannelsData(channels) { return channels.map((ch) => { return { name: ch.name, display: ch.display, items: ch.items.map((confEvent) => { return { id: confEvent.id, title: confEvent.snippet.title, thumbnail: confEvent.snippet.thumbnails.medium && confEvent.snippet.thumbnails.medium.url, thumbnailStd: confEvent.snippet.thumbnails.standard && confEvent.snippet.thumbnails.standard.url, totalCount: confEvent.contentDetails.itemCount, description: confEvent.snippet.description, publishedAt: confEvent.snippet.publishedAt, channelId: confEvent.snippet.channelId, channelTitle: confEvent.snippet.channelTitle, }; }), }; }); } function transformConfEventData(confEvent) { return { ...confEvent, items: confEvent.items.map(transformConfTalkData), }; } function transformConfTalkData(talk, idx) { return { idx, videoId: talk.snippet.resourceId.videoId, title: talk.snippet.title, thumbnail: talk.snippet.thumbnails.standard && talk.snippet.thumbnails.standard.url, description: talk.snippet.description, publishedAt: talk.snippet.publishedAt, channelId: talk.snippet.channelId, channelTitle: talk.snippet.channelTitle, playlistId: talk.snippet.playlistId, }; } module.exports = { transformAllChannelsData, transformConfEventData, transformConfTalkData, }; <|start_filename|>src/utils/matchConferenceByTitle.js<|end_filename|> function matchConferenceByTitle({title, conferences}) { for (const conf of conferences) { for (const filter of conf.filters) { if (title.indexOf(filter) > -1) { return conf; } } } return null; } module.exports = { matchConferenceByTitle, }; <|start_filename|>__tests__/transformData.js<|end_filename|> import { transformAllChannelsData, transformConfEventData, } from '../src/utils/transformData'; describe('transformData', () => { test('transformAllChannelsData', () => { expect(transformAllChannelsData(testChannelsData)).toEqual([ { name: 'test-conf', display: 'Test Conf', items: [ { id: 'PLPxbbTqCLbGHPxZpw4xj_Wwg8-fdNxJRh', title: 'React Conf 2019', thumbnail: 'https://i.ytimg.com/vi/QnZHO7QvjaM/mqdefault.jpg', thumbnailStd: 'https://i.ytimg.com/vi/QnZHO7QvjaM/sddefault.jpg', totalCount: 27, description: '', publishedAt: '2019-10-31T01:42:43Z', channelId: 'UCz5vTaEhvh7dOHEyd1efcaQ', channelTitle: 'React Conf', }, ], }, ]); }); test('transformConfEventData', () => { expect(transformConfEventData(testConfEventData).items).toEqual([ { idx: 0, videoId: 'WjJdaDXN5Vs', title: '<NAME> - Evolving the Visual Programming Environment with React at react-europe 2016', thumbnail: 'https://i.ytimg.com/vi/WjJdaDXN5Vs/sddefault.jpg', description: 'Tools shape our thinking. The "React Way" of thinking has already found many applications beyond building user interfaces. Particularly, React\'s functional, component-based design makes it an ideal candidate for building a better Visual Programming Environment. We\'ll examine how to overcome challenges such as lack of standardized APIs and limits of composition, and show how we can drastically improve the way humans create digital artifacts today.', publishedAt: '2016-06-05T09:44:59Z', channelId: 'UCorlLn2oZfgOJ-FUcF2eZ1A', channelTitle: 'ReactEurope', playlistId: 'PLCC436JpVnK0LTDKW3O_BGTZnrZ8dBAof', }, ]); }); }); const testChannelsData = [ { name: 'test-conf', display: 'Test Conf', items: [ { kind: 'youtube#playlist', etag: 'COaHLf9_ZEYF3nuqye2__5-EdR8', id: 'PLPxbbTqCLbGHPxZpw4xj_Wwg8-fdNxJRh', snippet: { publishedAt: '2019-10-31T01:42:43Z', channelId: 'UCz5vTaEhvh7dOHEyd1efcaQ', title: 'React Conf 2019', description: '', thumbnails: { default: { url: 'https://i.ytimg.com/vi/QnZHO7QvjaM/default.jpg', width: 120, height: 90, }, medium: { url: 'https://i.ytimg.com/vi/QnZHO7QvjaM/mqdefault.jpg', width: 320, height: 180, }, high: { url: 'https://i.ytimg.com/vi/QnZHO7QvjaM/hqdefault.jpg', width: 480, height: 360, }, standard: { url: 'https://i.ytimg.com/vi/QnZHO7QvjaM/sddefault.jpg', width: 640, height: 480, }, maxres: { url: 'https://i.ytimg.com/vi/QnZHO7QvjaM/maxresdefault.jpg', width: 1280, height: 720, }, }, channelTitle: 'React Conf', }, contentDetails: { itemCount: 27, }, }, ], }, ]; const testConfEventData = { items: [ { id: 'UExDQzQzNkpwVm5LM<KEY>', snippet: { publishedAt: '2016-06-05T09:44:59Z', channelId: 'UCorlLn2oZfgOJ-FUcF2eZ1A', title: '<NAME> - Evolving the Visual Programming Environment with React at react-europe 2016', description: 'Tools shape our thinking. The "React Way" of thinking has already found many applications beyond building user interfaces. Particularly, React\'s functional, component-based design makes it an ideal candidate for building a better Visual Programming Environment. We\'ll examine how to overcome challenges such as lack of standardized APIs and limits of composition, and show how we can drastically improve the way humans create digital artifacts today.', thumbnails: { default: { url: 'https://i.ytimg.com/vi/WjJdaDXN5Vs/default.jpg', width: 120, height: 90, }, medium: { url: 'https://i.ytimg.com/vi/WjJdaDXN5Vs/mqdefault.jpg', width: 320, height: 180, }, high: { url: 'https://i.ytimg.com/vi/WjJdaDXN5Vs/hqdefault.jpg', width: 480, height: 360, }, standard: { url: 'https://i.ytimg.com/vi/WjJdaDXN5Vs/sddefault.jpg', width: 640, height: 480, }, maxres: { url: 'https://i.ytimg.com/vi/WjJdaDXN5Vs/maxresdefault.jpg', width: 1280, height: 720, }, }, channelTitle: 'ReactEurope', playlistId: 'PLCC436JpVnK0LTDKW3O_BGTZnrZ8dBAof', position: 0, resourceId: { kind: 'youtube#video', videoId: 'WjJdaDXN5Vs', }, }, contentDetails: { videoId: 'WjJdaDXN5Vs', videoPublishedAt: '2016-06-06T08:13:50Z', }, }, ], }; <|start_filename|>src/components/ActivityIndicator.js<|end_filename|> import React from 'react'; import styled from 'styled-components'; import {useOutlet} from 'reconnect.js'; function ActivityIndicator(props) { const [visible] = useOutlet('spinner'); return ( <> <Wrapper visible={visible}> <img className="spinner" src="/images/react-icon.png" alt="react-icon" /> </Wrapper> <Backdrop visible={visible} /> </> ); } const CoverAll = styled.div` position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; pointer-events: ${(props) => (props.visible ? 'auto' : 'none')}; `; const Wrapper = styled(CoverAll)` z-index: 2; display: flex; align-items: center; justify-content: center; background-color: transparent; @keyframes infinite-spinning { 0% { transform: rotate(0deg) scale(1); } 50% { transform: rotate(360deg) scale(1.2); } 100% { transform: rotate(720deg) scale(1); } } & > .spinner { width: 60px; height: 60px; border-radius: 50%; display: flex; align-items: center; justify-content: center; background-color: white; transition: 200ms; opacity: ${(props) => (props.visible ? 1 : 0)}; animation: infinite-spinning 1.2s infinite; object-fit: contain; } `; const Backdrop = styled(CoverAll)` z-index: 1; transition: 200ms; background-color: ${(props) => props.visible ? 'rgba(0,0,0,0.5)' : 'transparent'}; `; export default ActivityIndicator; <|start_filename|>src/components/HistoryItem.js<|end_filename|> import React from 'react'; import {navigate} from 'gatsby'; import styled from 'styled-components'; import {PlayArrow} from '@styled-icons/material'; import * as Widgets from './Widgets'; import {useOutletSetter} from 'reconnect.js'; function HistoryItem(props) { const {item, width} = props; const imgRef = React.useRef(); const setSelectedConf = useOutletSetter('selectedConf'); function onInfoClick() { const rect = imgRef.current.getBoundingClientRect(); setSelectedConf({ item: { ...item.conf, thumbnailStd: item.talkThumbnail ? item.talkThumbnail : item.conf.thumbnail, }, rect: { top: rect.top, left: rect.left, width: rect.width, height: rect.height, }, }); } function onWatchClick() { navigate(`/player?conf=${item.conf.id}&idx=${item.talkIdx}`); } return ( <Wrapper style={{width}}> <div className="img-wrapper"> <img ref={imgRef} src={item.talkThumbnail ? item.talkThumbnail : item.conf.thumbnail} alt="conference snapshot" /> <div className="gradient" /> <button className="play" onClick={onWatchClick}> <PlayArrow size={50} color="red" style={{padding: 0}} /> </button> </div> <div className="content"> <div className="title"> <div>{item.conf.title}</div> <div> <span style={{fontSize: 20, fontWeight: 'bold'}}> {item.talkIdx + 1} </span> <span>{` / ${item.conf.totalCount}`}</span> </div> </div> <Widgets.Button onClick={onInfoClick} style={{width: '100%'}}> {`SEE ALL ${item.conf.totalCount} TALKS`} </Widgets.Button> </div> </Wrapper> ); } const Wrapper = styled.div` border-radius: 4px; background-color: #ddd; margin-right: 20px; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24); overflow: hidden; & > .img-wrapper { width: 100%; padding-bottom: 56.25%; position: relative; background-color: #ccc; & > img { position: absolute; left: 0; top: 0; width: 100%; height: 100%; object-fit: cover; } & > button.play { position: absolute; overflow: hidden; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: rgba(0, 0, 0, 0.3); border: 4px solid red; border-radius: 50%; cursor: pointer; outline: none; padding: 0; &:active { transform: translate(-50%, -50%) scale(1.1); } } & > .gradient { position: absolute; bottom: 0px; left: 0px; padding: 10px; width: 100%; height: 50%; background: linear-gradient(rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.9)); } } & > .content { padding: 10px; background-color: rgba(0, 0, 0, 0.9); & > .title { height: 90px; color: white; text-align: center; font-family: Roboto; letter-spacing: 1px; } } `; export default HistoryItem; <|start_filename|>src/components/VideoItemList.js<|end_filename|> import React from 'react'; import styled from 'styled-components'; import {navigate} from 'gatsby'; import {useOutlet} from 'reconnect.js'; import VideoItem from './VideoItem'; import {ScrollBarCss} from './Widgets'; function VideoItemList(props) { const {items} = props; const [showScrollBar, setShowScrollBar] = React.useState(false); const [dimension] = useOutlet('dimension'); const itemWidth = dimension?.innerWidth > 600 ? 300 : 210; return ( <VideoItemListWrapper innerWidth={(items.length + 1) * itemWidth} showScrollBar={showScrollBar} onMouseEnter={() => setShowScrollBar(true)} onMouseLeave={() => setShowScrollBar(false)}> <div className="items-wrapper"> {items.map((item, idx) => { return ( <div className="item" key={idx}> <VideoItem key={idx} item={item} width={itemWidth} onWatchClick={() => { navigate(`/player?conf=${item.playlistId}&idx=${item.idx}`); }} /> <div className="rank">{idx + 1}</div> </div> ); })} </div> </VideoItemListWrapper> ); } const VideoItemListWrapper = styled.div` overflow: auto; width: 100%; & > .items-wrapper { padding: 20px 0px 36px 30px; width: ${(props) => props.innerWidth}px; display: flex; & > .item { position: relative; & > .rank { position: absolute; bottom: -25px; right: 10px; color: white; font-size: 72px; font-style: italic; text-shadow: 3px 3px 5px #000; } } } ${ScrollBarCss}; `; export default VideoItemList; <|start_filename|>src/components/Toast.js<|end_filename|> import React from 'react'; import styled from 'styled-components'; import {useOutlet} from 'reconnect.js'; function Toast(props) { const [toastContent, setToastContent] = useOutlet('toast'); React.useEffect(() => { if (toastContent) { setTimeout(() => { setToastContent(null); }, 3000); } }, [toastContent, setToastContent]); return <ToastWrapper visible={toastContent}>{toastContent}</ToastWrapper>; } const ToastWrapper = styled.div` position: fixed; color: white; padding: 22px 85px; border-radius: 8px; background-color: #424a55; z-index: 30; transform: translateX(-50%); left: 50vw; bottom: ${(props) => (props.visible ? 100 : -100)}px; opacity: ${(props) => (props.visible ? 1 : 0)}; transition: 300ms; `; export default Toast; <|start_filename|>src/components/Search.js<|end_filename|> import styled from 'styled-components'; import React, {useContext, useEffect, useRef, useState} from 'react'; import latest from '../../static/snapshots/latest.json'; import {MdVideoLibrary} from 'react-icons/md'; import {AiFillHeart, AiOutlineHeart} from 'react-icons/ai'; import Fuse from 'fuse.js'; import {navigate} from 'gatsby'; import {Context} from '../AppContext'; import useFavoriteState from '../hooks/useFavoriteState'; import {SearchAlt} from '@styled-icons/boxicons-regular'; import {SquaredCross} from '@styled-icons/entypo'; const Wrapper = styled.div` display: flex; flex-direction: column; justify-content: flex-start; background-color: rgba(56, 56, 56, 1); width: 50vw; max-width: 560px; aspect-ratio: calc(560 / 356); border-radius: 10px; padding: 12px; & > section.top { display: flex; flex: 1; flex-direction: column; margin-bottom: 8px; transition: all 300ms ease; & > .input-area { display: flex; height: 56px; align-items: center; border-radius: 5px; border: 3px double #4f77e2; padding: 0 12px; & > .icon { cursor: pointer; } & > .search { margin-right: 8px; min-width: 20px; } & > .cancel { margin-left: 8px; min-width: 20px; } & > input { flex: 1; font-size: 14px; border: none; outline: none; background-color: transparent; color: white; } } & > .list { flex: 1; height: auto; overflow-y: auto; padding: 10px 0; & > .item { cursor: pointer; height: 50px; background-color: gray; padding: 0 10px; display: flex; align-items: center; border-radius: 5px; margin: 8px 0; & > .icon { cursor: pointer; font-size: 1.5rem; min-width: 32px; } & > .video-icon { margin-right: 8px; } & > .title { color: white; max-width: 400px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } :hover { border: 1px solid #4f77e2; box-shadow: 0 0 10px #4f77e2; } } & > .item:last-child { margin-bottom: 0; } } } & > section.bottom { display: flex; & > .control { flex: 1; height: 30px; background-color: gray; border-radius: 5px; padding: 0 10px; display: flex; align-items: center; color: #fff; & > .hint { display: flex; align-items: center; margin: 0 8px; & > label { margin-left: 4px; font-size: 14px; } & > .key { font-size: 12px; background-color: darkgrey; border-radius: 5px; padding: 0 5px; margin: 0 2px; text-align: center; } } } } @media screen and (max-width: 996px) { width: 80vw; } `; const SearchItem = (props) => { const {video} = props; const app = useContext(Context); const {isInFavorite, toggleFavoriteState} = useFavoriteState({ confId: video.playlistId, talkIdx: video.idx, }); return ( <div onClick={async () => { app.actions.setModal(null); await navigate(`/player?conf=${video.playlistId}&idx=${video.idx}`); }} className="item"> <MdVideoLibrary fill="#fff" className="video-icon icon" /> <div className="title">{video.title}</div> <div style={{flex: 1}} /> {isInFavorite ? ( <AiFillHeart onClick={(e) => { e.stopPropagation(); toggleFavoriteState({ title: video.title, thumbnail: video.thumbnail, }); }} fill="#fff" className="love-icon icon" /> ) : ( <AiOutlineHeart onClick={(e) => { e.stopPropagation(); toggleFavoriteState({ title: video.title, thumbnail: video.thumbnail, }); }} fill="#fff" className="love-icon icon" /> )} </div> ); }; const Search = () => { const [keyword, setKeyword] = useState(''); const [result, setResult] = useState([]); const fuse = useRef(null); useEffect(() => { fuse.current = new Fuse(Object.values(latest), { findAllMatches: true, isCaseSensitive: false, keys: ['title'], }); }, []); const _onValueChange = (e) => { const {value} = e.target; setKeyword(value); setResult( fuse.current .search(value) .map((r) => ({ ...r.item, })) .splice(0, 5), ); }; return ( <Wrapper> <section className="top"> <div className="input-area"> <SearchAlt className="search icon" size={32} color="white" /> <input autoComplete="off" type="text" name="keyword" value={keyword} onChange={_onValueChange} /> <SquaredCross onClick={() => { setKeyword(''); setResult([]); }} className="cancel icon" size={32} color="white" /> </div> <div className="list"> {result.map((v, idx) => ( <SearchItem key={idx} video={v} /> ))} </div> </section> <section className="bottom"> <div className="control"> {/*<div className="hint">*/} {/* <div className="key">↵</div>*/} {/* <label>SELECT</label>*/} {/*</div>*/} {/*<div className="hint">*/} {/* <div className="key">↑</div>*/} {/* <div className="key">↓</div>*/} {/* <label>NAVIGATE</label>*/} {/*</div>*/} <div className="hint"> <div className="key">ESC</div> <label>Close</label> </div> </div> </section> </Wrapper> ); }; export default Search; <|start_filename|>scripts/fetch-data.js<|end_filename|> const fs = require('fs'); const util = require('util'); const path = require('path'); const fetch = require('node-fetch'); const ytChannels = require('../data/ytChannels.json'); const {matchConferenceByTitle} = require('../src/utils/matchConferenceByTitle'); async function fetchAllChannels() { const apiKey = '<KEY>'; const maxResults = 100; let totalCnt = 0; for (const ch of ytChannels) { const cnt = await fetchOneChannel(ch, {apiKey, maxResults}); console.log(ch.name, cnt); totalCnt += cnt; } console.log(`\nTotal: ${totalCnt}`); } async function fetchOneChannel(channel, {apiKey, maxResults}) { const writeFile = util.promisify(fs.writeFile); const playlistPath = 'data/playlist'; const playlistItemsPath = 'static/playlistitems'; async function fetchToJson(url) { return ( await fetch(url, { headers: { Accept: 'application/json', }, }) ).json(); } const playlists = await fetchToJson( `https://www.googleapis.com/youtube/v3/playlists?part=id%2CcontentDetails%2Cplayer%2Csnippet%2Cstatus&channelId=${channel.channelId}&maxResults=${maxResults}&key=${apiKey}`, ); await writeFile( path.join(playlistPath, `${channel.name}.json`), JSON.stringify(playlists, null, 2), ); let cnt = 0; for (const playlist of playlists.items) { const conf = matchConferenceByTitle({ title: playlist.snippet.title, conferences: channel.conferences, }); if (!conf) { continue; } const itemsJson = await fetchToJson( `https://www.googleapis.com/youtube/v3/playlistItems?part=id%2CcontentDetails%2Csnippet%2Cstatus&maxResults=${maxResults}&playlistId=${playlist.id}&key=${apiKey}`, ); await writeFile( path.join(playlistItemsPath, `${playlist.id}.json`), JSON.stringify(itemsJson, null, 2), ); cnt++; } return cnt; } module.exports = {fetchAllChannels}; <|start_filename|>src/components/layout.js<|end_filename|> import React from 'react'; import {useOutletSetter} from 'reconnect.js'; import '../index.css'; import ActivityIndicator from './ActivityIndicator'; import Toast from './Toast'; import Modal from './Modal'; const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); function Layout({children, location}) { const showSpinner = useOutletSetter('spinner'); React.useEffect(() => { async function onPageMounted() { if (['/', '/favorites'].indexOf(location?.pathname) > -1) { showSpinner(true); await delay(600); showSpinner(false); if (typeof window !== 'undefined') { window.scrollTo({top: 0, behavior: 'smooth'}); } } } onPageMounted(); }, [showSpinner, location?.pathname]); return ( <main> {children} <ActivityIndicator /> <Toast /> <Modal /> </main> ); } export default Layout; <|start_filename|>src/utils/getVideoByStat.js<|end_filename|> const latest = require('../../static/snapshots/latest.json'); const previous = require('../../static/snapshots/previous.json'); const getMostViewed = (limit) => { return Object.values(latest) .sort( (a, b) => parseInt((b.stats && b.stats.viewCount) || 0, 10) - parseInt((a.stats && a.stats.viewCount) || 0, 10), ) .slice(0, limit); }; const getNewReleased = (limit) => { return Object.values(latest) .sort((a, b) => (b.publishedAt > a.publishedAt ? 1 : -1)) .slice(0, limit); }; const getRecentViewed = (limit) => { const latestVideoList = Object.values(latest).map((video) => ({ id: video.videoId, viewed: parseInt((video.stats && video.stats.viewCount) || 0, 10), })); const previousVideoList = Object.values(previous).map((video) => ({ id: video.videoId, viewed: parseInt((video.stats && video.stats.viewCount) || 0, 10), })); let diffVideoViewedList = []; for (const video of latestVideoList) { const prevItem = previousVideoList.find((v) => v.id === video.id); diffVideoViewedList.push({ id: video.id, viewed: video.viewed - (prevItem ? prevItem.viewed : 0), }); } return diffVideoViewedList .sort((a, b) => b.viewed - a.viewed) .slice(0, limit) .map((video) => ({...latest[video.id], viewCnt: video.viewed})); }; module.exports = {getMostViewed, getRecentViewed, getNewReleased};
revtel/reactconf.tv
<|start_filename|>WebApp/Infrastructure/ConfigurableHealthCheckMode.cs<|end_filename|> namespace InspectorGadget.WebApp.Infrastructure { public enum ConfigurableHealthCheckMode { AlwaysSucceed, AlwaysFail, FailNextNumberOfTimes } } <|start_filename|>WebApp/Pages/Shared/DisplayTemplates/HealthCheckGadgetResult.cshtml<|end_filename|> @model HealthCheckGadget.Result <dl> <dt>Mode</dt> <dd><pre>@Model.HealthCheckMode.ToString()</pre></dd> <dt>Fail Next Number Of Times</dt> <dd><pre>@Model.FailNextNumberOfTimes</pre></dd> </dl> <|start_filename|>WebApp/Gadgets/SqlConnectionDatabaseType.cs<|end_filename|> namespace InspectorGadget.WebApp.Gadgets { public enum SqlConnectionDatabaseType { SqlServer, PostgreSql, MySql, CosmosDB } } <|start_filename|>WebApp/Gadgets/SqlConnectionGadget.cs<|end_filename|> using System; using System.Data.Common; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Azure.Core; using Azure.Identity; using InspectorGadget.WebApp.Controllers; using InspectorGadget.WebApp.Infrastructure; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.Cosmos; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Logging; using MySqlConnector; using Npgsql; namespace InspectorGadget.WebApp.Gadgets { public class SqlConnectionGadget : GadgetBase<SqlConnectionGadget.Request, SqlConnectionGadget.Result> { public class Request : GadgetRequest { public SqlConnectionDatabaseType DatabaseType { get; set; } public string SqlConnectionString { get; set; } public string SqlConnectionStringSuffix { get; set; } public string SqlQuery { get; set; } public bool UseAzureManagedIdentity { get; set; } public string AzureManagedIdentityClientId { get; set; } public string SqlConnectionStringValue => this.SqlConnectionString + this.SqlConnectionStringSuffix; } public class Result { public string AccessToken { get; set; } public string Output { get; set; } } public SqlConnectionGadget(ILogger logger, IHttpClientFactory httpClientFactory, IUrlHelper url, AppSettings appSettings) : base(logger, httpClientFactory, url.GetRelativeApiUrl(nameof(ApiController.SqlConnection)), appSettings.DisableSqlConnection) { } protected override async Task<Result> ExecuteCoreAsync(Request request) { this.Logger.LogInformation("Executing SQL Connection for DatabaseType {DatabaseType} with SqlQuery {SqlQuery}", request.DatabaseType.ToString(), request.SqlQuery); if (request.DatabaseType == SqlConnectionDatabaseType.CosmosDB) { using (var iterator = GetFeedIterator<object>(request)) { var resultSet = await iterator.ReadNextAsync(); return new Result { Output = resultSet.FirstOrDefault()?.ToString() }; } } else { var result = new Result(); using (var connection = await GetDbConnectionAsync(request, result)) using (var command = connection.CreateCommand()) { await connection.OpenAsync(); command.CommandText = request.SqlQuery; var output = await command.ExecuteScalarAsync(); result.Output = output?.ToString(); return result; } } } private async Task<DbConnection> GetDbConnectionAsync(Request request, Result result) { if (request.DatabaseType == SqlConnectionDatabaseType.SqlServer) { var connection = new SqlConnection(request.SqlConnectionStringValue); if (request.UseAzureManagedIdentity) { // Request an access token for Azure SQL Database using the current Azure Managed Identity. this.Logger.LogInformation("Acquiring access token using Azure Managed Identity using Client ID \"{ClientId}\"", request.AzureManagedIdentityClientId); // If AzureManagedIdentityClientId is requested, that indicates the User-Assigned Managed Identity to use; if omitted the System-Assigned Managed Identity will be used. var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions { ManagedIdentityClientId = request.AzureManagedIdentityClientId }); var authenticationResult = await credential.GetTokenAsync(new TokenRequestContext(new[] { "https://database.windows.net/.default" })); var accessToken = authenticationResult.Token; connection.AccessToken = accessToken; result.AccessToken = accessToken; } return connection; } else if (request.DatabaseType == SqlConnectionDatabaseType.PostgreSql) { return new NpgsqlConnection(request.SqlConnectionStringValue); } else if (request.DatabaseType == SqlConnectionDatabaseType.MySql) { return new MySqlConnection(request.SqlConnectionStringValue); } else { throw new NotSupportedException($"\"{request.DatabaseType.ToString()}\" is not a supported ADO.NET database type"); } } private static FeedIterator<T> GetFeedIterator<T>(Request request) { var connectionString = new DbConnectionStringBuilder { ConnectionString = request.SqlConnectionStringValue }; var client = default(CosmosClient); if (request.UseAzureManagedIdentity) { // If AzureManagedIdentityClientId is requested, that indicates the User-Assigned Managed Identity to use; if omitted the System-Assigned Managed Identity will be used. var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions { ManagedIdentityClientId = request.AzureManagedIdentityClientId }); // Grab the account endpoint from the connection string. if (!connectionString.TryGetValue("AccountEndpoint", out object accountEndpoint)) { throw new ArgumentException("The specified connection string does not contain the required 'AccountEndpoint' value."); } client = new CosmosClient((string)accountEndpoint, credential); } else { client = new CosmosClient(request.SqlConnectionStringValue); } // See if a Database and Container were specified in the connection string. if (!connectionString.TryGetValue("Database", out object databaseName)) { // No Database specified, return a query iterator for the Account. return client.GetDatabaseQueryIterator<T>(request.SqlQuery); } if (!connectionString.TryGetValue("Container", out object containerName)) { // No Container specified, return a query iterator for the Database. return client.GetDatabase((string)databaseName).GetContainerQueryIterator<T>(request.SqlQuery); } // A Database and Container were specified, return a query iterator for the Container. return client.GetDatabase((string)databaseName).GetContainer((string)containerName).GetItemQueryIterator<T>(request.SqlQuery); } } } <|start_filename|>WebApp/Pages/HealthCheck.cshtml.cs<|end_filename|> using System.Net.Http; using System.Threading.Tasks; using InspectorGadget.WebApp.Gadgets; using InspectorGadget.WebApp.Infrastructure; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace InspectorGadget.WebApp.Pages { public class HealthCheckModel : PageModel { private readonly ILogger logger; private readonly IHttpClientFactory httpClientFactory; private readonly AppSettings appSettings; [BindProperty] public HealthCheckGadget.Request GadgetRequest { get; set; } public GadgetResponse<HealthCheckGadget.Result> GadgetResponse { get; set; } public HealthCheckModel(ILogger<HttpRequestModel> logger, IHttpClientFactory httpClientFactory, AppSettings appSettings) { this.logger = logger; this.httpClientFactory = httpClientFactory; this.appSettings = appSettings; this.GadgetRequest = new HealthCheckGadget.Request { CallChainUrls = this.appSettings.DefaultCallChainUrls, HealthCheckMode = ConfigurableHealthCheck.Mode, FailNextNumberOfTimes = ConfigurableHealthCheck.FailNextNumberOfTimes }; } public async Task OnPost() { this.logger.LogInformation("Executing Health Check page"); var gadget = new HealthCheckGadget(this.logger, this.httpClientFactory, Url, this.appSettings); this.GadgetResponse = await gadget.ExecuteAsync(this.GadgetRequest); } } } <|start_filename|>WebApp/Pages/Shared/DisplayTemplates/AzureManagedIdentityGadgetResult.cshtml<|end_filename|> @model AzureManagedIdentityGadget.Result <dl> <dt>Expires On</dt> <dd><code>@Model.ExpiresOn.ToDisplayString()</code></dd> @if (!string.IsNullOrWhiteSpace(Model.AccessToken)) { <dt>Access Token (<a href="https://jwt.ms/#access_token=@(Model.AccessToken)" target="_blank" title="Decode this access token">decode</a>)</dt> <dd><pre>@Model.AccessToken</pre></dd> } </dl> <|start_filename|>WebApp/Infrastructure/ConfigurableHealthCheckReport.cs<|end_filename|> using System; namespace InspectorGadget.WebApp.Infrastructure { public class ConfigurableHealthCheckReport { public int Id { get; set; } public DateTimeOffset TimeStamp { get; set; } public bool Healthy { get; set; } public string Description { get; set; } } } <|start_filename|>WebApp/Pages/SqlConnection.cshtml<|end_filename|> @page @model SqlConnectionModel @{ ViewData["Title"] = "SQL Connection"; } <h1>@ViewData["Title"]</h1> <form method="POST"> <p class="text-muted">Allows you to perform a (scalar) query on a SQL Connection from the web server and render the results below.</p> <div class="form-group"> <label for="databaseType">Database Type</label> <select class="form-control val-required" name="databaseType" id="databaseType" title="You can set the default value as a 'DefaultSqlConnectionDatabaseType' configuration setting" onchange="updateUI()"> <option value="@SqlConnectionDatabaseType.SqlServer" selected="@(Model.GadgetRequest.DatabaseType == @SqlConnectionDatabaseType.SqlServer ? true : false)">SQL Server, Azure SQL Database, ...</option> <option value="@SqlConnectionDatabaseType.PostgreSql" selected="@(Model.GadgetRequest.DatabaseType == @SqlConnectionDatabaseType.PostgreSql ? true : false)">PostgreSQL</option> <option value="@SqlConnectionDatabaseType.MySql" selected="@(Model.GadgetRequest.DatabaseType == @SqlConnectionDatabaseType.MySql ? true : false)">MySQL, MariaDB, ...</option> <option value="@SqlConnectionDatabaseType.CosmosDB" selected="@(Model.GadgetRequest.DatabaseType == @SqlConnectionDatabaseType.CosmosDB ? true : false)">Azure Cosmos DB (SQL API)</option> </select> </div> <div class="form-group"> <label for="sqlConnectionString">SQL Connection String</label> <input type="password" name="sqlConnectionString" id="sqlConnectionString" value="@Model.GadgetRequest.SqlConnectionString" class="form-control val-required" autocomplete="off" placeholder="The (masked) connection string with which to connect to the database" title="You can set the default value as a 'DefaultSqlConnectionSqlConnectionString' configuration setting" /> <input type="text" name="sqlConnectionStringSuffix" id="sqlConnectionStringSuffix" value="@Model.GadgetRequest.SqlConnectionStringSuffix" class="form-control val-optional" placeholder="An optional (unmasked) connection string suffix which is appended to the connection string" title="You can set the default value as a 'DefaultSqlConnectionSqlConnectionStringSuffix' configuration setting" /> <small id="cosmosDBConnectionStringInfoPanel" class="form-text text-muted"> Optionally, add a <code>Database</code> and <code>Container</code> connection string property to go deeper than the account level, e.g. <code>&quot;AccountEndpoint=...;AccountKey=...;Database=SampleDB;Container=Persons;&quot;</code>. </small> </div> <div class="form-group"> <label for="sqlQuery">SQL Query</label> <input type="text" name="sqlQuery" id="sqlQuery" value="@Model.GadgetRequest.SqlQuery" class="form-control val-required" placeholder="The scalar SQL query to execute against the database" title="You can set the default value as a 'DefaultSqlConnectionSqlQuery' configuration setting" /> </div> <div id="azureManagedIdentityPanel"> <div class="form-group form-check"> <input type="checkbox" name="useAzureManagedIdentity" id="useAzureManagedIdentity" value="true" checked="@Model.GadgetRequest.UseAzureManagedIdentity" class="form-check-input" title="You can set the default value as a 'DefaultSqlConnectionUseAzureManagedIdentity' configuration setting" /> <label class="form-check-label" for="useAzureManagedIdentity">Use Azure Managed Identity to connect to the database</label> </div> <div class="form-group"> <label for="azureManagedIdentityClientId">User-Assigned Managed Identity Client ID</label> <input type="text" name="azureManagedIdentityClientId" id="azureManagedIdentityClientId" value="@Model.GadgetRequest.AzureManagedIdentityClientId" class="form-control val-optional" placeholder="The Client ID of a User-Assigned Managed Identity; leave blank to use the System-Assigned Managed Identity" title="You can set the default value as a 'DefaultSqlConnectionAzureManagedIdentityClientId' configuration setting" /> </div> </div> <div class="form-group"> <label for="callChainUrls"><a asp-page="/Api" asp-fragment="call-chaining">Call Chain</a></label> <input type="text" name="callChainUrls" id="callChainUrls" value="@Model.GadgetRequest.CallChainUrls" class="form-control val-optional" placeholder="Optionally chain calls across multiple hops (separate base URL's by spaces)" title="You can set the default value as a 'DefaultCallChainUrls' configuration setting" /> </div> <div class="form-group"> <input type="submit" value="Submit" class="btn btn-primary" /> </div> </form> @Html.DisplayFor(m => m.GadgetResponse) <script> function updateUI() { var databaseType = document.getElementById('databaseType').value; var sqlQuery = document.getElementById('sqlQuery').value; // Show the Azure Managed Identity panel if supported. if (databaseType == '@SqlConnectionDatabaseType.SqlServer' || databaseType == '@SqlConnectionDatabaseType.CosmosDB') { document.getElementById('azureManagedIdentityPanel').style.display = 'block'; } else { document.getElementById('azureManagedIdentityPanel').style.display = 'none'; } // Show the Cosmos DB connection string info panel if appropriate. if (databaseType == '@SqlConnectionDatabaseType.CosmosDB') { document.getElementById('cosmosDBConnectionStringInfoPanel').style.display = 'block'; } else { document.getElementById('cosmosDBConnectionStringInfoPanel').style.display = 'none'; } // Set the default query depending on the database type. const SqlServerDefaultQuery = 'SELECT \'User "\' + USER_NAME() + \'" logged in from IP address "\' + CAST(CONNECTIONPROPERTY(\'client_net_address\') AS NVARCHAR) + \'" to database "\' + DB_NAME() + \'" on server "\' + @@@@SERVERNAME + \'"\''; const PostgreSqlDefaultQuery = 'SELECT CONCAT(\'User "\', CURRENT_USER, \'" logged in from IP address "\', INET_CLIENT_ADDR(), \'" to database "\', CURRENT_DATABASE(), \'"\')'; const MySqlDefaultQuery = 'SELECT CONCAT_WS(\'\', \'User "\', USER(), \'" logged in to database "\', DATABASE(), \'"\')'; const CosmosDBDefaultQuery = 'SELECT GetCurrentDateTime() AS currentUtcDateTime'; if (sqlQuery == '' || sqlQuery == SqlServerDefaultQuery || sqlQuery == PostgreSqlDefaultQuery || sqlQuery == MySqlDefaultQuery || sqlQuery == CosmosDBDefaultQuery) { if (databaseType == '@SqlConnectionDatabaseType.SqlServer') { document.getElementById('sqlQuery').value = SqlServerDefaultQuery; } else if (databaseType == '@SqlConnectionDatabaseType.PostgreSql') { document.getElementById('sqlQuery').value = PostgreSqlDefaultQuery; } else if (databaseType == '@SqlConnectionDatabaseType.MySql') { document.getElementById('sqlQuery').value = MySqlDefaultQuery; } else if (databaseType == '@SqlConnectionDatabaseType.CosmosDB') { document.getElementById('sqlQuery').value = CosmosDBDefaultQuery; } } } updateUI(); </script> <|start_filename|>WebApp/Infrastructure/ConfigurableHealthCheck.cs<|end_filename|> using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging; namespace InspectorGadget.WebApp.Infrastructure { public class ConfigurableHealthCheck : IHealthCheck { public const string HealthCheckPath = "/health"; private const int MaxHistoryItems = 20; private static object lockObject = new object(); private static int nextConfigurableHealthCheckReportId = 1; public static ConfigurableHealthCheckMode Mode { get; private set; } public static int FailNextNumberOfTimes { get; private set; } public static IList<ConfigurableHealthCheckReport> History { get; private set; } = new List<ConfigurableHealthCheckReport>(); public static void Configure(ConfigurableHealthCheckMode mode, int failNextNumberOfTimes) { lock (lockObject) { Mode = mode; FailNextNumberOfTimes = failNextNumberOfTimes; } } private readonly ILogger Logger; public ConfigurableHealthCheck(ILogger<ConfigurableHealthCheck> logger) { this.Logger = logger; } public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default(CancellationToken)) { lock (lockObject) { var healthy = default(bool); var description = default(string); if (Mode == ConfigurableHealthCheckMode.AlwaysSucceed) { healthy = true; description = "Reporting healthy status because mode is set to always succeed"; } else if (Mode == ConfigurableHealthCheckMode.AlwaysFail) { healthy = false; description = "Reporting unhealthy status because mode is set to always fail"; } else if (Mode == ConfigurableHealthCheckMode.FailNextNumberOfTimes) { if (FailNextNumberOfTimes > 0) { healthy = false; description = $"Reporting unhealthy status because mode is set to fail for next {FailNextNumberOfTimes} times"; FailNextNumberOfTimes = Math.Max(0, FailNextNumberOfTimes - 1); } else { healthy = true; description = $"Reporting healthy status because mode is set to fail for next {FailNextNumberOfTimes} times"; } } History.Add(new ConfigurableHealthCheckReport { Id = nextConfigurableHealthCheckReportId++, TimeStamp = DateTimeOffset.UtcNow, Healthy = healthy, Description = description }); if (History.Count > MaxHistoryItems) { History.RemoveAt(0); } this.Logger.LogInformation(description); if (healthy) { return Task.FromResult(HealthCheckResult.Healthy(description)); } else { this.Logger.LogInformation(description); return Task.FromResult(new HealthCheckResult(context.Registration.FailureStatus, description)); } } } } } <|start_filename|>WebApp/Pages/Shared/DisplayTemplates/SqlConnectionGadgetResult.cshtml<|end_filename|> @model SqlConnectionGadget.Result <dl> @if (!string.IsNullOrWhiteSpace(Model.AccessToken)) { <dt>Access Token (<a href="https://jwt.ms/#access_token=@(Model.AccessToken)" target="_blank" title="Decode this access token">decode</a>)</dt> <dd><pre>@Model.AccessToken</pre></dd> } <dt>Output</dt> <dd><pre>@Model.Output</pre></dd> </dl> <|start_filename|>WebApp/Pages/HealthCheck.cshtml<|end_filename|> @page @model HealthCheckModel @{ ViewData["Title"] = "Health Check"; } <h1>@ViewData["Title"]</h1> <form method="POST"> <p class="text-muted">Allows you to configure the health check endpoint (located at <a href="health">@ConfigurableHealthCheck.HealthCheckPath</a>), e.g. for testing load balancers or container orchestrators.</p> <div class="form-group"> <div class="form-check"> <input class="form-check-input" type="radio" name="healthCheckMode" id="healthCheckModeAlwaysSucceed" value="@ConfigurableHealthCheckMode.AlwaysSucceed.ToString()" checked="@(Model.GadgetRequest.HealthCheckMode == ConfigurableHealthCheckMode.AlwaysSucceed)"> <label class="form-check-label" for="healthCheckModeAlwaysSucceed">Always succeed</label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="healthCheckMode" id="healthCheckModeAlwaysFail" value="@ConfigurableHealthCheckMode.AlwaysFail.ToString()" checked="@(Model.GadgetRequest.HealthCheckMode == ConfigurableHealthCheckMode.AlwaysFail)"> <label class="form-check-label" for="healthCheckModeAlwaysFail">Always fail</label> </div> <div class="form-inline"> <div class="form-check"> <input class="form-check-input" type="radio" name="healthCheckMode" id="healthCheckModeFailNextNumberOfTimes" value="@ConfigurableHealthCheckMode.FailNextNumberOfTimes.ToString()" checked="@(Model.GadgetRequest.HealthCheckMode == ConfigurableHealthCheckMode.FailNextNumberOfTimes)"> <label class="form-check-label mr-1" for="healthCheckModeFailNextNumberOfTimes">Fail for next</label> <input type="text" name="failNextNumberOfTimes" id="failNextNumberOfTimes" value="@Model.GadgetRequest.FailNextNumberOfTimes" class="form-control form-control-sm form-control-narrow mr-1 val-required" placeholder="Set the next number of times the health check should fail" title="You can set the default value as a 'DefaultHealthCheckFailNumberOfTimes' configuration setting" /> <label class="form-check-label" for="healthCheckModeFailNextNumberOfTimes">times</label> </div> </div> </div> <div class="form-group"> <label for="callChainUrls"><a asp-page="/Api" asp-fragment="call-chaining">Call Chain</a></label> <input type="text" name="callChainUrls" id="callChainUrls" value="@Model.GadgetRequest.CallChainUrls" class="form-control val-optional" placeholder="Optionally chain calls across multiple hops (separate base URL's by spaces)" title="You can set the default value as a 'DefaultCallChainUrls' configuration setting" /> </div> <div class="form-group"> <input type="submit" value="Submit" class="btn btn-primary" /> </div> </form> @Html.DisplayFor(m => m.GadgetResponse) @if (ConfigurableHealthCheck.History.Any()) { <h3>History</h3> <table class="table table-striped table-hover table-sm table-responsive mt-3"> <thead> <tr> <th>ID</th> <th>Status</th> <th>Description</th> <th>Time</th> </tr> </thead> <tbody> @foreach (var item in ConfigurableHealthCheck.History.Reverse()) { <tr> <td>@item.Id</td> <td class="@(item.Healthy ? "table-success" : "table-danger")">@(item.Healthy ? "Healthy" : "Unhealthy")</td> <td>@item.Description</td> <td>@item.TimeStamp.ToDisplayString()</td> </tr> } </tbody> </table> } <|start_filename|>WebApp/Gadgets/HealthCheckGadget.cs<|end_filename|> using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using InspectorGadget.WebApp.Controllers; using InspectorGadget.WebApp.Infrastructure; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace InspectorGadget.WebApp.Gadgets { public class HealthCheckGadget : GadgetBase<HealthCheckGadget.Request, HealthCheckGadget.Result> { public class Request : GadgetRequest { public ConfigurableHealthCheckMode HealthCheckMode { get; set; } public int FailNextNumberOfTimes { get; set; } } public class Result { public ConfigurableHealthCheckMode HealthCheckMode { get; set; } public int FailNextNumberOfTimes { get; set; } public IList<ConfigurableHealthCheckReport> History { get; set; } } public HealthCheckGadget(ILogger logger, IHttpClientFactory httpClientFactory, IUrlHelper url, AppSettings appSettings) : base(logger, httpClientFactory, url.GetRelativeApiUrl(nameof(ApiController.HealthCheck)), appSettings.DisableHealthCheck) { } protected override Task<Result> ExecuteCoreAsync(Request request) { this.Logger.LogInformation("Executing Health Check configuration for HealthCheckMode {HealthCheckMode} and FailNumberOfTimes {FailNumberOfTimes}", request.HealthCheckMode.ToString(), request.FailNextNumberOfTimes); ConfigurableHealthCheck.Configure(request.HealthCheckMode, request.FailNextNumberOfTimes); return Task.FromResult(new Result { HealthCheckMode = ConfigurableHealthCheck.Mode, FailNextNumberOfTimes = ConfigurableHealthCheck.FailNextNumberOfTimes, History = ConfigurableHealthCheck.History }); } } }
ormikopo1988/InspectorGadget
<|start_filename|>ui/src/components/TabTrigger.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; const TabTrigger = props => ( <div className={`tab-trigger ${props.className}`}> {React.cloneElement(props.children, { isActive: props.tabOpen === props.for, onClick: () => props.tabChange(props.for) })} </div> ); TabTrigger.defaultProps = { className: '' }; TabTrigger.propTypes = { children: PropTypes.node.isRequired, className: PropTypes.string, for: PropTypes.oneOfType([PropTypes.string, PropTypes.symbol]).isRequired, tabChange: PropTypes.func.isRequired, tabOpen: PropTypes.oneOfType([PropTypes.string, PropTypes.symbol]).isRequired }; export default TabTrigger; <|start_filename|>ui/src/utils/to-void.js<|end_filename|> const toVoid = () => {}; export default toVoid; <|start_filename|>ui/src/components/MessageCenter.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; // Components import Message from './Message'; import './MessageCenter.scss'; const MessageCenter = props => ( <div className="full-dim flex-c flex-a-c flex-jc-c message-center"> <Message msg={props.msg} type={props.type}> {props.children} </Message> </div> ); MessageCenter.propTypes = { children: PropTypes.node, msg: PropTypes.string, type: PropTypes.oneOf([ 'default', 'help', 'info', 'warning', 'error', 'loading' ]) }; export default MessageCenter; <|start_filename|>ui/src/utils/object-set.js<|end_filename|> const objectSet = (obj, path, value) => { const branches = [obj]; const pathArray = typeof path === 'string' ? path.split('.') : path; const pathLen = pathArray.length; const has = pathArray.every((prop, i) => { if (Object.prototype.hasOwnProperty.call(branches[i], prop)) { branches[i + 1] = branches[i][prop]; return true; } return false; }); if (has) { branches[pathLen - 1][pathArray[pathLen - 1]] = value; } return has; }; export default objectSet; <|start_filename|>ui/src/utils/with-raf.js<|end_filename|> import { requestAnimationFrame } from './request-animation-frame'; const withRaf = (fn, callback) => { let isRequesting = false; return (...args) => { if (isRequesting) { return undefined; } return requestAnimationFrame(() => { const resp = fn(...args); if (callback) callback(resp); isRequesting = false; }); }; }; export default withRaf; <|start_filename|>ui/src/utils/camel-to-const.js<|end_filename|> const camelToConst = str => str .split(/(?=[A-Z])/) .join('_') .toUpperCase(); export default camelToConst; <|start_filename|>ui/src/components/ExampleList.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; // Styles import './ExampleList.scss'; const ExampleList = props => ( <ul className="example-list flex-c flex-w-w no-list-style"> {props.examples.map((example, index) => ( <li className={example.columns === 2 && 'two-columns'} key={index}> <a href={example.url && example.url}> <figure className="example-figure" style={{ backgroundImage: `url(${example.image ? example.image : ''})` }} /> </a> {example.title && ( <a href={example.url && example.url}>{example.title}</a> )} {example.description && ( <p className="smaller">{example.description}</p> )} {example.location && ( <div className="smaller one-line location"> <input onClick="this.select();" value={example.location} /> </div> )} </li> ))} </ul> ); ExampleList.propTypes = { examples: PropTypes.array }; export default ExampleList; <|start_filename|>ui/src/utils/remove-higlass-event-listeners.js<|end_filename|> export const removeHiGlassEventListeners = (listeners, api) => { listeners = !Array.isArray(listeners) ? Object.values(listeners) : listeners; // eslint-disable-line no-param-reassign listeners.forEach(listener => { api.off(listener.event, listener.id); }); return []; }; export default removeHiGlassEventListeners; <|start_filename|>ui/src/components/AnnotationList.js<|end_filename|> import { PropTypes } from 'prop-types'; import React from 'react'; // Components import ButtonIcon from './ButtonIcon'; const AnnotationList = props => ( <ol className={`annotation-list ${props.className}`}> {props.annotations.map(annotation => ( <li className="flex-c" key={annotation.id}> <input onChange={() => this.selectAnnotation(annotation.id)} type="checkbox" checked={annotation.isShown} /> <div className="flex-g-1 annotation-list-title" onClick={() => this.selectAnnotation(annotation.id)} > {annotation.title} </div> <ButtonIcon icon="edit" iconOnly={true} isActive={props.activeAnnotationId === annotation.id} onClick={() => props.setActiveAnnotation(annotation.id)} /> </li> ))} </ol> ); AnnotationList.defaultProps = { annotations: [], className: '' }; AnnotationList.propTypes = { activeAnnotationId: PropTypes.string, annotations: PropTypes.array, className: PropTypes.string, selectAnnotation: PropTypes.func, setActiveAnnotation: PropTypes.func }; export default AnnotationList; <|start_filename|>ui/src/utils/object-has.js<|end_filename|> const objectHas = (obj, path) => { let branch = obj; return (typeof path === 'string' ? path.split('.') : path).every(prop => { if (Object.prototype.hasOwnProperty.call(branch, prop)) { branch = branch[prop]; return true; } return false; }); }; export default objectHas; <|start_filename|>ui/src/utils/debounce.js<|end_filename|> /** * Debounce a function call. * * @description * Function calls are delayed by `wait` milliseconds and only one out of * multiple function calls is executed. * * @param {functiom} func - Function to be debounced * @param {number} wait - Number of milliseconds to debounce the function call. * @param {boolean} immediate - If `true` function is not debounced. * @return {functiomn} Debounced function. */ const debounce = (func, wait, immediate) => { let timeout; const debounced = (...args) => { const later = () => { timeout = null; if (!immediate) { func(...args); } }; const callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) { func(...args); } }; debounce.cancel = () => { clearTimeout(timeout); timeout = null; }; return debounced; }; export default debounce; <|start_filename|>ui/src/utils/with-array.js<|end_filename|> const withArray = value => (Array.isArray(value) ? value : [value]); export default withArray; <|start_filename|>examples/config-encode-h1.json<|end_filename|> { "encoders": [ { "content_type": "histone-mark-chip-seq-12kb", "from_file": "examples/autoencoders.json" } ], "datasets": [ { "filepath": "examples/data/ENCFF117WXM.bigWig", "content_type": "histone-mark-chip-seq-12kb", "id": "encode-h1-hesc-encsr794ofw-2013-dnase-seq-rdn-signal", "name": "H1 DNase rdn signal" }, { "filepath": "examples/data/ENCFF593OAZ.bigWig", "content_type": "histone-mark-chip-seq-12kb", "id": "encode-h1-hesc-encsr271tfs-2013-chip-seq-h3k4me1-fc", "name": "H1 H3K4me1 fc" }, { "filepath": "examples/data/ENCFF623ZAW.bigWig", "content_type": "histone-mark-chip-seq-12kb", "id": "encode-h1-hesc-encsr443yas-2013-chip-seq-h3k4me3-fc", "name": "H1 H3K4me3 fc" }, { "filepath": "examples/data/ENCFF986PCY.bigWig", "content_type": "histone-mark-chip-seq-12kb", "id": "encode-h1-hesc-encsr880suy-2013-chip-seq-h3k27ac-fc", "name": "H1 H3K27ac fc" } ], "coords": "grch38", "chroms": ["chr21"], "step_freq": 4, "db_path": "examples/search-h1.db" } <|start_filename|>ui/src/utils/download-as-json.js<|end_filename|> import downloadAsFile from './download-as-file'; const downloadAsJson = (filename, obj) => { downloadAsFile( filename, new Blob([JSON.stringify(obj, null, 2)], { type: 'application/json' }) ); }; export default downloadAsJson; <|start_filename|>ui/src/reducers/index.js<|end_filename|> import { combineReducers } from 'redux'; import { routerReducer as routing } from 'react-router-redux'; import defaultSetReducer from '../utils/default-set-reducer'; import { TAB_RIGHT_BAR_INFO, TAB_RESULTS } from '../configs/search'; const searchId = defaultSetReducer('searchId', null); const serverStartTime = defaultSetReducer('serverStartTime', -1); const homeInfoBarClose = defaultSetReducer('homeInfoBarClose', false); const viewConfig = defaultSetReducer('viewConfig', null); const higlassMouseTool = defaultSetReducer('higlassMouseTool', 'panZoom'); const searchHover = defaultSetReducer('searchHover', -1); const searchRightBarHelp = defaultSetReducer('searchRightBarHelp', false); const searchRightBarMetadata = defaultSetReducer( 'searchRightBarMetadata', false ); const searchRightBarProgress = defaultSetReducer( 'searchRightBarProgress', true ); const searchRightBarProjection = defaultSetReducer( 'searchRightBarProjection', true ); const searchRightBarProjectionSettings = defaultSetReducer( 'searchRightBarProjectionSettings', false ); const searchRightBarShow = defaultSetReducer('searchRightBarShow', true); const searchRightBarTab = defaultSetReducer( 'searchRightBarTab', TAB_RIGHT_BAR_INFO ); const searchRightBarWidth = defaultSetReducer('searchRightBarWidth', 200); const searchSelection = defaultSetReducer('searchSelection', []); const searchTab = defaultSetReducer('searchTab', TAB_RESULTS); const showAutoencodings = defaultSetReducer('showAutoencodings', false); const appReducer = combineReducers({ routing, searchId, serverStartTime, homeInfoBarClose, viewConfig, higlassMouseTool, searchHover, searchRightBarHelp, searchRightBarMetadata, searchRightBarProgress, searchRightBarProjection, searchRightBarProjectionSettings, searchRightBarShow, searchRightBarTab, searchRightBarWidth, searchSelection, searchTab, showAutoencodings }); const rootReducer = (state, action) => { if (action.type === 'RESET') { state = undefined; // eslint-disable-line no-param-reassign } return appReducer(state, action); }; export default rootReducer; <|start_filename|>ui/src/components/DropDown.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; // Higher-order components import { withPubSub } from '../hocs/pub-sub'; // Utils import hasParent from '../utils/has-parent'; class DropDown extends React.Component { constructor(props) { super(props); this.state = { isOpen: false }; this.pubSubs = []; } componentDidMount() { if (!this.props.noCloseOnOuterClick) { this.pubSubs.push( this.props.pubSub.subscribe('click', this.clickHandler.bind(this)) ); } } componentWillUnmount() { this.pubSubs.forEach(subscription => this.props.pubSub.unsubscribe(subscription) ); this.pubSubs = []; } componentDidUpdate(prevProps, prevState) { if ( this.props.id && this.state.isOpen && this.state.isOpen !== prevState.isOpen ) { this.props.pubSub.publish(`DropDown${this.props.id}`, this.state.isOpen); } } render() { const childrenWithProps = React.Children.map(this.props.children, child => React.cloneElement(child, { dropDownIsOpen: this.state.isOpen, dropDownToggle: this.toggle.bind(this) }) ); let className = 'rel drop-down'; className += this.props.className ? ` ${this.props.className}` : ''; className += this.state.isOpen ? ' drop-down-is-open' : ''; className += this.props.alignRight ? ' drop-down-align-right' : ''; className += this.props.alignTop ? ' drop-down-align-top' : ''; return ( <div className={className} ref={el => { this.el = el; }} > {childrenWithProps} </div> ); } /* ------------------------------ Custom Methods -------------------------- */ clickHandler(event) { if (!hasParent(event.target, this.el)) { this.close(); } } close() { this.setState({ isOpen: false }); } open() { this.setState({ isOpen: true }); } toggle() { if (this.state.isOpen) { this.close(); } else { this.open(); } } } DropDown.defaultProps = { alignRight: false, alignTop: false, className: null, id: null, noCloseOnOuterClick: false }; DropDown.propTypes = { alignRight: PropTypes.bool, alignTop: PropTypes.bool, children: PropTypes.node.isRequired, className: PropTypes.string, id: PropTypes.string, noCloseOnOuterClick: PropTypes.bool, pubSub: PropTypes.object.isRequired }; export default withPubSub(DropDown); <|start_filename|>ui/src/utils/merge-error.js<|end_filename|> const mergeError = error => ({ error, status: 500 }); export default mergeError; <|start_filename|>ui/src/components/Main.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; import { Route, Switch, withRouter } from 'react-router'; // Views import About from '../views/About'; import Help from '../views/Help'; import Home from '../views/Home'; import NotFound from '../views/NotFound'; import Search from '../views/Search'; class Main extends React.Component { componentDidUpdate(prevProps) { if (this.props.location !== prevProps.location) { window.scrollTo(0, 0); } } render() { return ( <Switch> <Route exact path="/about" component={About} /> <Route exact path="/search" component={Search} /> <Route exact path="/search/:id" component={Search} /> <Route exact path="/help" render={Help.render} /> <Route exact path="/" component={Home} /> <Route component={NotFound} /> </Switch> ); } } Main.propTypes = { isAuthenticated: PropTypes.bool, location: PropTypes.object.isRequired }; export default withRouter(Main); <|start_filename|>ui/src/configs/index.js<|end_filename|> export const DEFAULT_SERVER = 'localhost'; export const DEFAULT_SERVER_PORT = 5000; <|start_filename|>ui/src/components/ButtonLikeLink.js<|end_filename|> import { PropTypes } from 'prop-types'; import React from 'react'; import { Link } from 'react-router-dom'; // Styles import './ButtonLikeLink.scss'; const ButtonLikeLink = props => ( <div className={`flex-c flex-a-c button-like-link ${props.className}`}> <Link to={props.to}>{props.children}</Link> </div> ); ButtonLikeLink.defaultProps = { className: '' }; ButtonLikeLink.propTypes = { children: PropTypes.node.isRequired, className: PropTypes.string, to: PropTypes.string.isRequired }; export default ButtonLikeLink; <|start_filename|>ui/src/components/Spinner.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; // Styles import './Spinner.scss'; const Spinner = props => ( <div className={`spinner ${props.delayed ? 'is-delayed' : ''}`}> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40" width={props.width} height={props.height} > <circle cx="20" cy="20" r="18" strokeWidth="4" fill="none" stroke="#000" /> <g className="correct" transform="translate(20, 20)"> <g className="blocks"> <animateTransform attributeName="transform" attributeType="XML" dur="1.5s" from="0" repeatCount="indefinite" to="360" type="rotate" /> <path className="one" d="M0-20c1.104 0 2 .896 2 2s-.896 2-2 2V0l-4 21h25v-42H0v1z" fill="#fff" > <animateTransform attributeName="transform" attributeType="XML" calcMode="spline" dur="1.5s" from="0" values="0; 360" keyTimes="0; 1" keySplines="0.2 0.2 0.15 1" repeatCount="indefinite" to="360" type="rotate" /> </path> <path className="two" d="M0-20c-1.104 0-2 .896-2 2s.896 2 2 2V0l4 21h-25v-42H0v1z" fill="#fff" > <animateTransform attributeName="transform" attributeType="XML" calcMode="spline" dur="1.5s" from="0" values="0; 360" keyTimes="0; 1" keySplines="0.1 0.15 0.8 0.8" repeatCount="indefinite" to="360" type="rotate" /> </path> </g> </g> </svg> </div> ); Spinner.defaultProps = { height: 40, width: 40 }; Spinner.propTypes = { delayed: PropTypes.bool, height: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]) }; export default Spinner; <|start_filename|>ui/src/components/DropDownSlider.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; // Components import Button from './Button'; import DropDown from './DropDown'; import DropDownContent from './DropDownContent'; import DropDownTrigger from './DropDownTrigger'; import './DropDownSlider.scss'; const DropDownSlider = props => ( <DropDown className={`drop-down-slider ${props.reversed ? 'reversed' : ''}`}> <DropDownTrigger> <Button>{props.value}</Button> </DropDownTrigger> <DropDownContent> <div className="flex-c flex-a-c"> {props.reversed ? ( <span className="drop-down-slider-max">{props.max}</span> ) : ( <span className="drop-down-slider-min">{props.min}</span> )} <input id={props.id} type="range" min={props.min} max={props.max} step={props.step} disabled={props.disabled} value={props.value} onChange={props.onChange} /> {props.reversed ? ( <span className="drop-down-slider-min">{props.min}</span> ) : ( <span className="drop-down-slider-max">{props.max}</span> )} </div> {props.histogram && props.histogram.length && ( <div className="flex-c histogram"> {props.histogram.map((bin, i) => ( <div key={i} className="flex-g-1" style={{ height: `${Math.min(1, bin / props.histogramNorm) * 100}%` }} /> ))} </div> )} </DropDownContent> </DropDown> ); DropDownSlider.defaultProps = { disabled: false, histogram: [], histogramNorm: 1, max: 1, min: 0, reversed: false, step: 0.05 }; DropDownSlider.propTypes = { disabled: PropTypes.bool, histogram: PropTypes.array, histogramNorm: PropTypes.number, id: PropTypes.string, max: PropTypes.number, min: PropTypes.number, onChange: PropTypes.func.isRequired, reversed: PropTypes.bool, step: PropTypes.number, value: PropTypes.number.isRequired }; export default DropDownSlider; <|start_filename|>ui/src/utils/num-to-classif.js<|end_filename|> const numToCassif = num => { switch (num) { case -1: return 'negative'; case 1: return 'positive'; case 0: default: return 'neutral'; } }; export default numToCassif; <|start_filename|>ui/src/utils/cookie.js<|end_filename|> /* eslint prefer-template:0 */ /** * Get a cookie. * * @param {string} key - Cookie ID. * @return {string|null} If cookie exists, returns the content of the cookie. */ const get = key => decodeURIComponent( document.cookie.replace( new RegExp( '(?:(?:^|.*;)\\s*' + encodeURIComponent(key).replace(/[-.+*]/g, '\\$&') + '\\s*\\=\\s*([^;]*).*$)|^.*$' ), '$1' ) ) || null; /** * Check if a cookie exists. * * @param {string} key - Cookie ID. * @return {boolean} If `true` a cookie with id `key` exists. */ const has = key => new RegExp( '(?:^|;\\s*)' + encodeURIComponent(key).replace(/[-.+*]/g, '\\$&') + '\\s*\\=' ).test(document.cookie); /** * Remove a cookie. * * @param {string} key - Cookie ID. * @param {string} path - Cookie path. * @param {string} domain - Cookie domain. * @return {boolean} If `true` an existing cookie was removed, else `false`. */ const remove = (key, path, domain) => { if (!key || !has(key)) { return false; } document.cookie = encodeURIComponent(key) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT' + (domain ? '; domain=' + domain : '') + (path ? '; path=' + path : ''); return true; }; const set = (key, value, end, path, domain, secure) => { if (!key || /^(?:expires|max-age|path|domain|secure)$/i.test(key)) { return false; } let sExpires = ''; if (end) { switch (end.constructor) { case Number: sExpires = end === Infinity ? '; expires=Fri, 31 Dec 9999 23:59:59 GMT' : '; max-age=' + end; break; case String: sExpires = '; expires=' + end; break; case Date: sExpires = '; expires=' + end.toUTCString(); break; default: // Nothing } } document.cookie = encodeURIComponent(key) + '=' + encodeURIComponent(value) + sExpires + (domain ? '; domain=' + domain : '') + (path ? '; path=' + path : '') + (secure ? '; secure' : ''); return true; }; export default { get, has, remove, set }; <|start_filename|>ui/src/utils/mean.js<|end_filename|> import sum from './sum'; const mean = arr => sum(arr) / arr.length; export default mean; <|start_filename|>examples/config-encode-e11-5-limb.json<|end_filename|> { "encoders": [ { "content_type": "dnase-seq-3kb", "from_file": "examples/autoencoders.json" }, { "content_type": "histone-mark-chip-seq-3kb", "from_file": "examples/autoencoders.json" } ], "datasets": [ { "filepath": "examples/data/ENCFF641OPE.bigWig", "content_type": "dnase-seq-3kb", "id": "encode-e11-5-limb-dnase-rdns", "name": "e11.5 limb DNase rdn signal" }, { "filepath": "examples/data/ENCFF336LAW.bigWig", "content_type": "histone-mark-chip-seq-3kb", "id": "encode-e11-5-limb-chip-h3k27ac-fc", "name": "e11.5 limb H3K27ac fc" } ], "coords": "mm10", "chroms": ["chr12"], "step_freq": 2, "db_path": "examples/search-e11-5-limb.db" } <|start_filename|>ui/src/utils/classif-to-num.js<|end_filename|> const classifToNum = num => { switch (num[0]) { case 'n': return -1; case 'p': return 1; default: return 0; } }; export default classifToNum; <|start_filename|>ui/src/components/InfoBar.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; // Components import ButtonIcon from './ButtonIcon'; // Styles import './InfoBar.scss'; const InfoBar = props => ( <header className={`info-bar ${props.isClose ? 'info-bar-is-close' : ''}`}> <div className={`info-bar-content ${props.wrap ? 'wrap' : ''}`}> {props.children} </div> {props.isClosable && ( <div className="flex-c flex-a-c flex-jc-c rel info-bar-close"> <ButtonIcon icon="arrow-bottom" iconMirrorH={!props.isClose} iconOnly={true} onClick={props.onClose} /> </div> )} </header> ); InfoBar.propTypes = { children: PropTypes.node.isRequired, isClose: PropTypes.bool, isClosable: PropTypes.bool, onClose: PropTypes.func, wrap: PropTypes.bool }; export default InfoBar; <|start_filename|>ui/src/views/NotFound.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; // Components import Content from '../components/Content'; import ContentWrapper from '../components/ContentWrapper'; import Footer from '../components/Footer'; import Icon from '../components/Icon'; import './NotFound.scss'; const NotFound = props => ( <ContentWrapper name="not-found"> <Content name="not-found" wrap={true} rel={true}> <div className="flex-c flex-v flex-a-c flex-jc-c full-dim"> <div className="flex-c flex-v flex-a-c not-found-header"> <div className="icon-wrapper"> <Icon iconId="sad" /> </div> <h2 className="m-t-0">{props.title}</h2> </div> <em>{props.message}</em> </div> </Content> <Footer /> </ContentWrapper> ); NotFound.defaultProps = { message: 'The requested page either moved or does not exist.', title: 'Nothing Found!' }; NotFound.propTypes = { message: PropTypes.string, title: PropTypes.string }; export default NotFound; <|start_filename|>ui/src/components/SpinnerCenter.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; // Components import Spinner from './Spinner'; // Styles import './SpinnerCenter.scss'; const SpinnerCenter = props => ( <div className="full-dim flex-c flex-a-c flex-jc-c spinner-center"> <Spinner delayed={props.delayed} /> </div> ); SpinnerCenter.propTypes = { delayed: PropTypes.bool }; export default SpinnerCenter; <|start_filename|>ui/src/utils/range.js<|end_filename|> const range = (start, stop, step = 1) => Array(Math.ceil((stop - start) / step)) .fill(start) .map((x, y) => x + y * step); export default range; <|start_filename|>ui/src/components/TopBar.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; import { withRouter } from 'react-router'; import { NavLink } from 'react-router-dom'; // Components import Hamburger from './Hamburger'; import Icon from './Icon'; // Styles import './TopBar.scss'; const isSearch = pathname => pathname && pathname.match(/\/search(?:(?=.)(\?|\/)|$)/); class TopBar extends React.Component { constructor(props) { super(props); this.state = { menuIsShown: false }; this.toggleMenu = this.toggleMenu.bind(this); this.unlisten = this.props.history.listen(() => this.setState({ menuIsShown: false }) ); } componentWillUnmount() { this.unlisten(); } /* ------------------------------ Custom Methods -------------------------- */ toggleMenu(isOpen) { this.setState({ menuIsShown: isOpen }); } /* -------------------------------- Render -------------------------------- */ render() { let wrapClass = 'wrap'; let sizeClass = ''; if (isSearch(this.props.location.pathname)) { wrapClass = 'wrap-basic'; sizeClass = 'smaller'; } return ( <header className={`top-bar ${sizeClass}`}> <div className={`flex-c flex-jc-sb top-bar-wrapper ${wrapClass}`}> <div className="flex-c branding-launch"> <NavLink to="/" className="flex-c flex-a-c branding"> <Icon iconId="logo-two-tone" /> <span className="higlass"> Pea<span className="higlass-hi">x</span> </span> </NavLink> </div> <nav className={`flex-c flex-jc-e flex-a-s is-toggable ${ this.state.menuIsShown ? 'is-shown' : '' }`} > <ul className="flex-c flex-jc-e flex-a-s no-list-style primary-nav-list"> <li> <NavLink to="/search" activeClassName="is-active"> Searches </NavLink> </li> <li> <NavLink to="/about" activeClassName="is-active"> About </NavLink> </li> { // <li> // <NavLink to="/help" activeClassName="is-active"> // Help // </NavLink> // </li> } </ul> <Hamburger isActive={this.state.menuIsShown} onClick={this.toggleMenu} /> </nav> </div> </header> ); } } TopBar.propTypes = { match: PropTypes.object.isRequired, location: PropTypes.object.isRequired, history: PropTypes.object.isRequired }; export default withRouter(TopBar); <|start_filename|>ui/src/utils/api.js<|end_filename|> import update from 'immutability-helper'; import { decode } from 'tab64'; // Utils import getServer from './get-server'; import mergeError from './merge-error'; import mergeJsonResponse from './merge-json-response'; const server = `${getServer()}/api/v1`; const getInfo = async () => fetch(`${server}/info/`) .then(mergeJsonResponse) .then(response => { if (response.status !== 200) return false; return response.body; }); const newSearch = async rangeSelection => fetch(`${server}/search/`, { method: 'post', headers: { 'Content-Type': 'application/json; charset=utf-8' }, body: JSON.stringify({ window: rangeSelection }) }) .then(mergeJsonResponse) .catch(mergeError); const getSearchInfo = async searchId => fetch(`${server}/search/?id=${searchId}`) .then(mergeJsonResponse) .catch(mergeError); const getAllSearchInfos = async (max = 0) => fetch(`${server}/search/?max=${max}`) .then(mergeJsonResponse) .catch(mergeError); const setClassification = async (searchId, windowId, classification) => fetch(`${server}/classification/`, { method: 'put', headers: { 'Content-Type': 'application/json; charset=utf-8' }, body: JSON.stringify({ searchId, windowId, classification }) }) .then(mergeJsonResponse) .catch(mergeError); const deleteClassification = async (searchId, windowId) => fetch(`${server}/classification/`, { method: 'delete', headers: { 'Content-Type': 'application/json; charset=utf-8' }, body: JSON.stringify({ searchId, windowId }) }) .then(mergeJsonResponse) .catch(mergeError); const getClassifications = async searchId => fetch(`${server}/classifications/?s=${searchId}`) .then(mergeJsonResponse) .catch(mergeError); const getDataTracks = async () => fetch(`${server}/data-tracks/`) .then(mergeJsonResponse) .catch(mergeError); const getPredictions = async (searchId, border = 0.5) => fetch(`${server}/predictions/?s=${searchId}&b=${border}`) .then(mergeJsonResponse) .catch(mergeError); const getSeeds = async searchId => fetch(`${server}/seeds/?s=${searchId}`) .then(mergeJsonResponse) .catch(mergeError); const newClassifier = async searchId => fetch(`${server}/classifier/?s=${searchId}`, { method: 'post' }) .then(mergeJsonResponse) .catch(mergeError); const getClassifier = async searchId => fetch(`${server}/classifier/?s=${searchId}`) .then(mergeJsonResponse) .catch(mergeError); const getProgress = async searchId => fetch(`${server}/progress/?s=${searchId}`) .then(mergeJsonResponse) .catch(mergeError); const newProjection = async (searchId, minDist = 0.1, nn = 5) => fetch(`${server}/projection/?s=${searchId}&md=${minDist}&nn=${nn}`, { method: 'put' }) .then(mergeJsonResponse) .catch(mergeError); const getProjection = async searchId => fetch(`${server}/projection/?s=${searchId}`) .then(mergeJsonResponse) .then(resp => update(resp, { body: (body = {}) => update(body, { projection: { $set: decode(body.projection || '', 'float32') } }) }) ) .catch(mergeError); const getProbabilities = async searchId => fetch(`${server}/probabilities/?s=${searchId}`) .then(mergeJsonResponse) .then(resp => update(resp, { body: (body = {}) => update(body, { results: { $set: decode(body.results || '', 'float32') } }) }) ) .catch(mergeError); const getClasses = async searchId => fetch(`${server}/classes/?s=${searchId}`) .then(mergeJsonResponse) .then(resp => update(resp, { body: (body = {}) => update(body, { results: { $set: decode(body.results || '', 'uint8') } }) }) ) .catch(mergeError); export default { deleteClassification, getAllSearchInfos, getClasses, getClassifications, getClassifier, getProgress, getDataTracks, getInfo, getPredictions, getProbabilities, getProjection, getSearchInfo, getSeeds, newClassifier, newProjection, newSearch, setClassification }; <|start_filename|>ui/src/components/with-list.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; const withList = getKey => Component => { const List = ({ list }) => ( <ul className="list no-list-style"> {list.map(item => ( <li className="list-item" key={getKey(item)}> <Component {...item} /> </li> ))} </ul> ); List.propTypes = { list: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, PropTypes.symbol ]) }) ) }; return List; }; export default withList; <|start_filename|>ui/src/components/with-either.js<|end_filename|> import React from 'react'; const withEither = (conditionalRenderingFn, EitherComponent) => Component => { const Either = props => conditionalRenderingFn(props) ? ( <EitherComponent {...props} /> ) : ( <Component {...props} /> ); return Either; }; export default withEither; <|start_filename|>ui/src/index.js<|end_filename|> import createPubSub from 'pub-sub-es'; import React from 'react'; import ReactDOM from 'react-dom'; import { ConnectedRouter } from 'react-router-redux'; import { Provider } from 'react-redux'; import { createState, history } from './factories/state'; // HOCs import { Provider as PubSubProvider } from './hocs/pub-sub'; // Components import App from './components/App'; import AppFake from './components/AppFake'; // Actions import { setServerStartTime } from './actions'; // Utils import getServer from './utils/get-server'; import Logger from './utils/logger'; import registerServiceWorker from './registerServiceWorker'; // Styles import './index.scss'; const logger = Logger('Index'); // Initialize store const state = createState(); let rehydratedStore; const storeRehydrated = state.configure(); // Init pub-sub service const pubSub = createPubSub(); const getServerStartTime = store => fetch(`${getServer()}/api/v1/started/`) .then(response => response.text()) .then(time => ({ store, serverStartTime: parseInt(time, 10) })); const render = (Component, store, error) => { if (!store) { ReactDOM.render( <PubSubProvider value={pubSub}> <AppFake error={error} /> </PubSubProvider>, document.getElementById('root') ); } else { ReactDOM.render( <Provider store={store}> <ConnectedRouter history={history}> <PubSubProvider value={pubSub}> <Component /> </PubSubProvider> </ConnectedRouter> </Provider>, document.getElementById('root') ); } }; render(AppFake); storeRehydrated .then(getServerStartTime) .then(({ store, serverStartTime }) => { if (store.getState().present.serverStartTime !== serverStartTime) { // The server restarted, hence we need to reset the store as we don't // know whether the server has persistent data or not. state.reset(); store.dispatch(setServerStartTime(serverStartTime)); } rehydratedStore = store; render(App, store); }) .catch(error => { logger.error('Failed to rehydrate the store! This is fatal!', error); render( undefined, undefined, 'Failed to initialize! Did you start the server? Otherwise, please contact an admin.' ); }); if (module.hot) { module.hot.accept('./components/App', () => { const NextApp = require('./components/App').default; // eslint-disable-line global-require render(NextApp, rehydratedStore); }); storeRehydrated.then(store => { window.store = store; }); } registerServiceWorker(); <|start_filename|>ui/src/components/Hamburger.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; // Styles import './Hamburger.scss'; class Hamburger extends React.Component { render() { return ( <button className="hamburger-wrapper" onClick={this.toggle.bind(this)}> <div className={`hamburger hamburger-to-x ${ this.props.isActive ? 'is-active' : '' }`} > <span /> </div> <div className="hamburger-bg" /> </button> ); } /* ------------------------------ Custom Methods -------------------------- */ toggle() { this.props.onClick(!this.props.isActive); } } Hamburger.propTypes = { isActive: PropTypes.bool, onClick: PropTypes.func.isRequired }; export default Hamburger; <|start_filename|>ui/src/components/InputIcon.js<|end_filename|> import { PropTypes } from 'prop-types'; import React from 'react'; // Components import Icon from './Icon'; // Styles import './InputIcon.scss'; const classNames = props => { let className = 'input-icon'; className += ` ${props.className}`; className += props.isActive ? ' is-active' : ''; className += props.isDisabled ? ' is-disabled' : ''; return className; }; const InputIcon = props => ( <div className={classNames(props)}> <Icon iconId={props.icon} mirrorH={props.iconMirrorH} mirrorV={props.iconMirrorV} /> <input type={props.type} disabled={props.isDisabled} placeholder={props.placeholder} onChange={props.onChange} onInput={props.onInput} /> </div> ); InputIcon.defaultProps = { isDisabled: false, placeholder: '', type: 'text' }; InputIcon.propTypes = { className: PropTypes.string, icon: PropTypes.string.isRequired, iconMirrorH: PropTypes.bool, iconMirrorV: PropTypes.bool, isActive: PropTypes.bool, isDisabled: PropTypes.bool, onChange: PropTypes.func, onInput: PropTypes.func, type: PropTypes.string, placeholder: PropTypes.string }; export default InputIcon; <|start_filename|>ui/src/utils/load-view-config.js<|end_filename|> const loadViewConfig = file => new Promise((resolve, reject) => { const reader = new FileReader(); reader.addEventListener('load', fileEvent => { try { resolve(JSON.parse(fileEvent.target.result)); } catch (e) { reject(new Error('Only drop valid JSON'), e); } }); try { reader.readAsText(file); } catch (e) { reject(new Error('Only drop actual files')); } }); export default loadViewConfig; <|start_filename|>ui/src/utils/readable-date.js<|end_filename|> const readableDate = (date, hasHour) => { let d = date; try { d.getMonth(); } catch (e) { d = new Date(d); } const format = { year: 'numeric', month: 'short', day: 'numeric' }; if (hasHour) { format.hour = 'numeric'; format.minute = 'numeric'; } return d.toLocaleString('en-us', format); }; export default readableDate; <|start_filename|>ui/src/components/BottomBar.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; // Styles import './BottomBar.scss'; const BottomBar = props => ( <footer className="flex-c flex-jc-sb bottom-bar">{props.children}</footer> ); BottomBar.propTypes = { children: PropTypes.node.isRequired }; export default BottomBar; <|start_filename|>examples/config-encode-e11-5-midbrain.json<|end_filename|> { "encoders": [ { "content_type": "dnase-seq-3kb", "from_file": "examples/autoencoders.json" }, { "content_type": "histone-mark-chip-seq-3kb", "from_file": "examples/autoencoders.json" } ], "datasets": [ { "filepath": "examples/data/ENCFF906WCV.bigWig", "content_type": "dnase-seq-3kb", "id": "encode-e11-5-midbrain-dnase-rdns", "name": "e11.5 midbrain DNase rdn signal" }, { "filepath": "examples/data/ENCFF847OYS.bigWig", "content_type": "histone-mark-chip-seq-3kb", "id": "encode-e11-5-midbrain-chip-h3k27ac-fc", "name": "e11.5 midbrain H3K27ac fc" } ], "coords": "mm10", "chroms": ["chr1", "chr2"], "step_freq": 2, "db_path": "examples/search-e11-5-midbrain.db" } <|start_filename|>ui/src/components/LabeledSlider.js<|end_filename|> import { PropTypes } from 'prop-types'; import React from 'react'; // Utils import ButtonIcon from './ButtonIcon'; // Styles import './LabeledSlider.scss'; class LabeledSlider extends React.Component { constructor(props) { super(props); this.state = { isBam: false }; this.onBamEndBnd = this.onBamEnd.bind(this); } componentDidMount() { this.bamEl.addEventListener('animationend', this.onBamEndBnd); } componentWillUnmount() { this.bamEl.removeEventListener('animationend', this.onBamEndBnd); } componentDidUpdate(prevProps) { if (prevProps.value !== this.props.value) { if (this.state.isBam) { this.bamEl.style.webkitAnimation = 'none'; setTimeout(() => { this.bamEl.style.webkitAnimation = ''; }, 0); } else { this.setState({ isBam: true }); } } } get valueClass() { return this.state.isBam ? 'labeled-slider-value labeled-slider-value-changed' : 'labeled-slider-value'; } onBamEnd() { this.setState({ isBam: false }); } render() { let className = 'labeled-slider'; className += ` ${this.props.sameLine ? ' same-line' : ''}`; className += ` ${this.props.className || ''}`; return ( <div className={className}> <label className="flex-c flex-jc-sb" htmlFor={this.props.id}> <div className="flex-c flex-a-c labeled-slider-label-container"> <span className="labeled-slider-label">{this.props.label}</span> <span className="flex-c flex-jc-c labeled-slider-value-container"> <span className={this.valueClass}> <span ref={ref => { this.bamEl = ref; }} className="labeled-slider-value-bam" /> {this.props.value} </span> </span> </div> {this.props.sameLine && ( <div className="flex-g-1 m-l-0-25"> <input id={this.props.id} type="range" min={this.props.min} max={this.props.max} step={this.props.step} disabled={this.props.disabled} value={this.props.value} onChange={this.props.onChange} /> </div> )} <div className={this.props.info && this.props.sameLine ? 'm-l-0-25' : ''} > {this.props.info && ( <ButtonIcon className="info-external" external={true} icon="info" iconOnly={true} isRound={true} href={this.props.info} /> )} </div> </label> {!this.props.sameLine && ( <input id={this.props.id} type="range" min={this.props.min} max={this.props.max} step={this.props.step} disabled={this.props.disabled} value={this.props.value} onChange={this.props.onChange} /> )} </div> ); } } LabeledSlider.defaultProps = { className: '', min: 0, max: 10, onChange: () => {}, sameLine: false, step: 1 }; LabeledSlider.propTypes = { className: PropTypes.string, disabled: PropTypes.bool, id: PropTypes.string, info: PropTypes.string, label: PropTypes.string.isRequired, max: PropTypes.number, min: PropTypes.number, onChange: PropTypes.func, sameLine: PropTypes.bool, step: PropTypes.number, value: PropTypes.number.isRequired }; export default LabeledSlider; <|start_filename|>ui/src/utils/input-to-num.js<|end_filename|> const inputToNum = ({ target: { value } }) => +value; export default inputToNum; <|start_filename|>ui/src/utils/get-server.js<|end_filename|> import { DEFAULT_SERVER_PORT } from '../configs'; const hostname = window.HGAC_SERVER || window.location.hostname; const port = window.HGAC_SERVER_PORT || DEFAULT_SERVER_PORT; const getServer = () => `//${hostname}:${port}`; export default getServer; <|start_filename|>ui/src/components/AppFake.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; // Components import Content from './Content'; import ContentWrapper from './ContentWrapper'; import MessageCenter from './MessageCenter'; import Icon from './Icon'; import SpinnerCenter from './SpinnerCenter'; // Styles import './Footer.scss'; import './TopBar.scss'; const AppLoading = props => ( <div className="app full-mdim"> <header className="top-bar"> <div className="flex-c flex-jc-sb top-bar-wrapper wrap"> <div className="flex-c branding-launch"> <a href="/" className="flex-c flex-a-c branding"> <Icon iconId="logo-two-tone" /> <span className="higlass"> Pea<span className="higlass-hi">x</span> </span> </a> </div> <nav className="flex-c flex-jc-e flex-a-s is-toggable"> <ul className="flex-c flex-jc-e flex-a-s no-list-style"> <li> <a href="/search">Search</a> </li> <li> <a href="/about">About</a> </li> </ul> </nav> </div> </header> <ContentWrapper name="app-fake"> <Content name="app-fake" rel={true} wrap={true}> {props.error ? ( <MessageCenter msg={props.error} type="error" /> ) : ( <SpinnerCenter delayed={true} /> )} </Content> <footer className="footer"> <div className="wrap flex-c flex-a-c flex-jc-sb"> <div className="flex-c flex-a-c flex-v"> <div className="flex-c"> <Icon iconId="logo-seas" title="<NAME> School of Engineering and Applied Sciences" /> <Icon iconId="logo-novartis" title="Novartis Institute for BioMedical Research" /> </div> </div> <nav> <ul className="flex-c flex-jc-e flex-a-s no-list-style"> <li> <a href="/search">Search</a> </li> <li> <a href="/about">About</a> </li> </ul> </nav> </div> </footer> </ContentWrapper> </div> ); AppLoading.propTypes = { error: PropTypes.string }; export default AppLoading; <|start_filename|>ui/src/utils/is-same.js<|end_filename|> const isSame = array => array.every(value => value === array[0]); export default isSame; <|start_filename|>ui/src/utils/max.js<|end_filename|> const max = arr => arr.reduce((m, v) => (m >= v ? m : v), -Infinity); export default max; <|start_filename|>ui/src/components/ButtonCheck.js<|end_filename|> import { PropTypes } from 'prop-types'; import React from 'react'; // Components import Icon from './Icon'; // Styles import './ButtonCheck.scss'; const classNames = props => { let className = 'flex-c flex-a-c flex-jc-c button-check'; className += props.isActive ? ' is-active' : ''; className += props.isChecked ? ' is-checked' : ''; className += props.isDisabled ? ' is-disabled' : ''; className += props.checkboxPosition === 'right' ? ' flex-rev' : ''; className += ` ${props.className || ''}`; return className; }; const ButtonIcon = props => ( <label className={classNames(props)} tabIndex="0"> <div className="flex-c flex-jc-c flex-a-c checkbox"> <input type="checkbox" checked={props.isChecked} disabled={props.isDisabled} onChange={props.onSelect} /> <Icon iconId="checkmark" /> </div> <span>{props.children}</span> </label> ); ButtonIcon.defaultProps = { checkboxPosition: 'left' }; ButtonIcon.propTypes = { checkboxPosition: PropTypes.oneOf(['left', 'right']), children: PropTypes.node, className: PropTypes.string, isActive: PropTypes.bool, isChecked: PropTypes.bool, isDisabled: PropTypes.bool, onSelect: PropTypes.func }; export default ButtonIcon; <|start_filename|>ui/src/configs/higlass.js<|end_filename|> // eslint-disable-next-line import/prefer-default-export export const DEFAULT_OPTIONS = { containerPaddingX: 0, containerPaddingY: 0, viewPaddingTop: 0, viewPaddingBottom: 0, viewPaddingLeft: 0, viewPaddingRight: 0 }; <|start_filename|>ui/src/components/Arrow.js<|end_filename|> import { PropTypes } from 'prop-types'; import React from 'react'; // Styles import './Arrow.scss'; const classNames = props => { let className = 'arrow'; className += ` arrow-${props.direction}`; return className; }; const styles = props => ({ borderTopColor: `${props.direction === 'down' ? props.color : 'transparent'}`, borderTopWidth: `${props.direction !== 'up' ? props.size : 0}px`, borderRightColor: `${ props.direction === 'left' ? props.color : 'transparent' }`, borderRightWidth: `${props.direction !== 'right' ? props.size : 0}px`, borderBottomColor: `${ props.direction === 'up' ? props.color : 'transparent' }`, borderBottomWidth: `${props.direction !== 'down' ? props.size : 0}px`, borderLeftColor: `${ props.direction === 'right' ? props.color : 'transparent' }`, borderLeftWidth: `${props.direction !== 'left' ? props.size : 0}px` }); const Arrow = props => ( <div className={classNames(props)} style={styles(props)} /> ); Arrow.defaultProps = { color: '#000', direction: 'top', size: 5 }; Arrow.propTypes = { color: PropTypes.string, direction: PropTypes.oneOf(['up', 'right', 'down', 'left']), size: PropTypes.number }; export default Arrow; <|start_filename|>ui/src/components/DropDownTrigger.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; const DropDownTrigger = props => ( <div className="drop-down-trigger"> {React.cloneElement(props.children, { isActive: props.dropDownIsOpen, onClick: props.dropDownToggle })} </div> ); DropDownTrigger.propTypes = { children: PropTypes.node.isRequired, dropDownIsOpen: PropTypes.bool, dropDownToggle: PropTypes.func }; export default DropDownTrigger; <|start_filename|>examples/config-roadmap-e116-gm12878.json<|end_filename|> { "encoders": [ { "content_type": "dnase-seq-3kb", "from_file": "examples/autoencoders.json" }, { "content_type": "histone-mark-chip-seq-3kb", "from_file": "examples/autoencoders.json" } ], "datasets": [ { "filepath": "examples/data/E116-DNase.fc.signal.bigWig", "content_type": "dnase-seq-3kb", "id": "roadmap-epigenomics-gm12878-e116-dnase-fc", "name": "GM12878 DNase fc" }, { "filepath": "examples/data/E116-H3K27ac.fc.signal.bigWig", "content_type": "histone-mark-chip-seq-3kb", "id": "roadmap-epigenomics-gm12878-e116-h3k27ac-fc", "name": "GM12878 H3K27ac fc" }, { "filepath": "examples/data/E116-H3K4me1.fc.signal.bigWig", "content_type": "histone-mark-chip-seq-3kb", "id": "roadmap-epigenomics-gm12878-e116-h3k4me1-fc", "name": "GM12878 H3K4me1 fc" }, { "filepath": "examples/data/E116-H3K4me3.fc.signal.bigWig", "content_type": "histone-mark-chip-seq-3kb", "id": "roadmap-epigenomics-gm12878-e116-h3k4me3-fc", "name": "GM12878 H3K4me3 fc" } ], "coords": "hg19", "chroms": ["chr20", "chr21"], "step_freq": 2, "db_path": "examples/search-roadmap-e116-gm12878.db" } <|start_filename|>ui/src/utils/sum.js<|end_filename|> const sum = arr => arr.reduce((s, v) => s + v, 0); export default sum; <|start_filename|>ui/src/components/TabContent.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; // Styles import './TabContent.scss'; const classNames = props => { let className = 'tab-content'; className += ` ${props.className}`; className += props.tabOpen === props.for ? ' is-open' : ''; return className; }; const TabContent = props => ( <div className={classNames(props)}> {props.tabOpen === props.for && props.children} </div> ); TabContent.propTypes = { children: PropTypes.node.isRequired, className: PropTypes.string, for: PropTypes.oneOfType([PropTypes.string, PropTypes.symbol]).isRequired, tabOpen: PropTypes.oneOfType([PropTypes.string, PropTypes.symbol]).isRequired }; export default TabContent; <|start_filename|>ui/src/views/SearchSubTopBar.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; import { connect } from 'react-redux'; // Higher-order components import { withPubSub } from '../hocs/pub-sub'; // Components import AppInfo from '../components/AppInfo'; import ButtonIcon from '../components/ButtonIcon'; import SubTopBar from '../components/SubTopBar'; import SubTopBottomBarButtons from '../components/SubTopBottomBarButtons'; import ToolTip from '../components/ToolTip'; // Services import { setShowAutoencodings } from '../actions'; // Utils import { Deferred, Logger } from '../utils'; const logger = Logger('SearchSubTopBar'); const showInfo = pubSub => () => { pubSub.publish('globalDialog', { message: <AppInfo />, request: new Deferred(), resolveOnly: true, resolveText: 'Close', icon: 'logo', headline: 'Peax' }); }; const SearchSubTopBar = props => ( <SubTopBar> <SubTopBottomBarButtons className="flex-c flex-a-c no-list-style"> <li> <ToolTip align="left" delayIn={2000} delayOut={500} title={ <span className="flex-c"> <span>Show Autoencodings</span> </span> } > <ButtonIcon icon="autoencoding" iconOnly={true} isActive={props.showAutoencodings} onClick={() => { props.setShowAutoencodings(!props.showAutoencodings); }} /> </ToolTip> </li> <li> <ToolTip align="left" delayIn={2000} delayOut={500} title={ <span className="flex-c"> <span>Normalize to this</span> </span> } > <ButtonIcon icon="ratio" iconOnly={true} isIconMirrorOnFocus={true} isActive={props.isMinMaxValuesByTarget} onClick={props.normalize} /> </ToolTip> </li> <li> <ToolTip align="left" delayIn={2000} delayOut={500} title={ <span className="flex-c"> <span>Reset viewports</span> <span className="short-cut">R</span> </span> } > <ButtonIcon icon="reset" iconOnly={true} isDisabled={!props.viewportChanged} isIconRotationOnFocus={true} onClick={props.resetViewport} /> </ToolTip> </li> </SubTopBottomBarButtons> <SubTopBottomBarButtons className="flex-c flex-a-c flex-jc-e no-list-style"> <li> <ToolTip align="right" delayIn={2000} delayOut={500} title={ <span className="flex-c"> <span>Show App Information</span> </span> } > <ButtonIcon icon="info" iconOnly={true} onClick={showInfo(props.pubSub)} /> </ToolTip> </li> <li> <ToolTip align="right" delayIn={2000} delayOut={500} title={ <span className="flex-c"> <span>Download Classification</span> <span className="short-cut">CMD + S</span> </span> } > <ButtonIcon icon="download" iconOnly={true} isDisabled={true} onClick={() => { logger.warn('Not supported yet.'); }} /> </ToolTip> </li> </SubTopBottomBarButtons> </SubTopBar> ); SearchSubTopBar.defaultProps = { isMinMaxValuesByTarget: false, viewportChanged: false }; SearchSubTopBar.propTypes = { isMinMaxValuesByTarget: PropTypes.bool, resetViewport: PropTypes.func.isRequired, normalize: PropTypes.func.isRequired, pubSub: PropTypes.object.isRequired, setShowAutoencodings: PropTypes.func, showAutoencodings: PropTypes.bool, viewportChanged: PropTypes.bool }; const mapStateToProps = state => ({ showAutoencodings: state.present.showAutoencodings }); const mapDispatchToProps = dispatch => ({ setShowAutoencodings: showAutoencodings => dispatch(setShowAutoencodings(showAutoencodings)) }); export default connect( mapStateToProps, mapDispatchToProps )(withPubSub(SearchSubTopBar)); <|start_filename|>ui/src/components/ElementWrapperAdvanced.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; import { compose } from 'recompose'; // Components import ElementWrapper from './ElementWrapper'; import MessageCenter from './MessageCenter'; import SpinnerCenter from './SpinnerCenter'; // HOCs import withEither from './with-either'; const isNotFound = props => props.isNotFound; const isError = props => props.isError; const isLoading = props => props.isLoading; const ErrorMsg = props => ( <MessageCenter msg={props.isError} type="error"> {props.isErrorNodes} </MessageCenter> ); ErrorMsg.propTypes = { isError: PropTypes.string, isErrorNodes: PropTypes.node }; const NotFoundMsg = props => ( <MessageCenter msg={props.isNotFound} type="default"> {props.isNotFoundNodes} </MessageCenter> ); NotFoundMsg.propTypes = { isNotFound: PropTypes.string, isNotFoundNodes: PropTypes.node }; const ElementWrapperAdvanced = compose( withEither(isError, ErrorMsg), withEither(isNotFound, NotFoundMsg), withEither(isLoading, SpinnerCenter) )(ElementWrapper); export default ElementWrapperAdvanced; <|start_filename|>ui/src/components/Icon.js<|end_filename|> import { PropTypes } from 'prop-types'; import React from 'react'; // Config import icons, { WARNING } from '../configs/icons'; // Styles import './Icon.scss'; const wrapHtml = html => ({ __html: html }); const getSvg = id => wrapHtml(icons[id] ? icons[id].svg : WARNING.svg); const getFillRule = id => icons[id] && icons[id].fillRule ? icons[id].fillRule : ''; const getViewBox = id => icons[id] && icons[id].viewBox ? icons[id].viewBox : '0 0 16 16'; const convertId = id => (id ? id.replace(/-/g, '_').toUpperCase() : ''); const Icon = props => ( <div className={`icon icon-${props.iconId} ${ props.mirrorH ? 'is-mirror-h' : '' } ${props.mirrorV ? 'is-mirror-v' : ''} ${props.inline ? 'is-inline' : ''}`} title={props.title} > <svg xmlns="http://www.w3.org/2000/svg" className="full-dim" viewBox={getViewBox(convertId(props.iconId))} fillRule={getFillRule(convertId(props.iconId))} dangerouslySetInnerHTML={getSvg(convertId(props.iconId))} /> </div> ); Icon.propTypes = { iconId: PropTypes.string.isRequired, inline: PropTypes.bool, mirrorH: PropTypes.bool, mirrorV: PropTypes.bool, title: PropTypes.string }; export default Icon; <|start_filename|>ui/src/components/Footer.js<|end_filename|> import React from 'react'; import { NavLink } from 'react-router-dom'; // Components import Icon from './Icon'; import ToolTip from './ToolTip'; // Styles import './Footer.scss'; const Footer = () => ( <footer className="footer"> <div className="wrap flex-c flex-a-c flex-jc-sb"> <div className="flex-c flex-a-c flex-v"> <div className="flex-c"> <ToolTip align="left" delayIn={2000} delayOut={500} title={ <span className="flex-c"> <span> <NAME> School of Engineering and Applied Sciences </span> </span> } > <Icon iconId="logo-seas" /> </ToolTip> <ToolTip align="left" delayIn={2000} delayOut={500} title={ <span className="flex-c"> <span>Novartis Institute of BioMedical Research</span> </span> } > <Icon iconId="logo-novartis" /> </ToolTip> </div> </div> <nav> <ul className="flex-c flex-jc-e flex-a-s no-list-style"> <li> <NavLink exact to="/" activeClassName="is-active"> Home </NavLink> </li> <li> <NavLink exact to="/search" activeClassName="is-active"> Searches </NavLink> </li> <li> <NavLink exact to="/about" activeClassName="is-active"> About </NavLink> </li> { // <li> // <NavLink exact to="/help" activeClassName="is-active"> // Help // </NavLink> // </li> } </ul> </nav> </div> </footer> ); export default Footer; <|start_filename|>ui/src/components/DropNotifier.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; // Styles import './DropNotifier.scss'; class DropNotifier extends React.Component { constructor(props) { super(props); this.state = { isActive: false }; this.listeners = []; this.addEventListeners(); } componentWillUnmount() { this.removeEventListeners(); } render() { return ( <div className={`drop-notifier flex-c flex-jc-c flex-a-c ${ this.state.isActive ? 'is-active' : '' }`} > <div className="drop-layer full-dim-win" ref={el => { this.dropLayer = el; }} /> <span>Drop JSON Config</span> </div> ); } /* ------------------------------ Custom Methods -------------------------- */ addEventListeners() { this.eventListeners = [ { name: 'dragenter', callback: event => { this.setState({ isActive: true }); event.stopPropagation(); event.preventDefault(); return false; } }, { name: 'dragover', callback: event => { event.stopPropagation(); event.preventDefault(); return false; } }, { name: 'dragleave', callback: event => { if (event.target === this.dropLayer) { this.setState({ isActive: false }); } event.stopPropagation(); event.preventDefault(); return false; } }, { name: 'drop', callback: event => { this.setState({ isActive: false }); this.props.drop(event); event.preventDefault(); } } ]; this.eventListeners.forEach(event => document.addEventListener(event.name, event.callback, false) ); } removeEventListeners() { this.eventListeners.forEach(event => document.removeEventListener(event.name, event.fnc) ); } } DropNotifier.propTypes = { drop: PropTypes.func.isRequired }; export default DropNotifier; <|start_filename|>ui/scripts/write-config.js<|end_filename|> /* eslint-env: node */ /** Copyright 2018 Novartis Institutes for BioMedical Research Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.* */ const fs = require("fs"); const changeCase = require("change-case"); const globalEnvironment = require("../config/gEnv").env; const run = prod => { const config = {}; try { const configBase = require("../config.json"); // eslint-disable-line global-require, import/no-unresolved Object.assign(config, configBase); } catch (ex) { // Nothing } try { const configLocal = require(`../config.${prod ? "prod" : "dev"}.json`); // eslint-disable-line global-require, import/no-unresolved, import/no-dynamic-require Object.assign(config, configLocal); } catch (e) { /* Nothing */ } try { const configLocal = require("../config.local.json"); // eslint-disable-line global-require, import/no-unresolved Object.assign(config, configLocal); } catch (e) { /* Nothing */ } const env = Object.keys(config) .filter(key => globalEnvironment.indexOf(key) >= 0) .map( key => `window.HGAC_${changeCase.constantCase(key)}=${ typeof key === "string" ? JSON.stringify(config[key]) : config[key] };` ); fs.writeFile("./build/config.js", env.join("\n"), err => { if (err) { console.log(err); } }); }; module.exports = { run }; <|start_filename|>ui/src/components/with-maybe.js<|end_filename|> import React from 'react'; const withMaybe = conditionalRenderingFn => Component => { const Maybe = props => conditionalRenderingFn(props) ? null : <Component {...props} />; return Maybe; }; export default withMaybe; <|start_filename|>ui/src/utils/zip.js<|end_filename|> import isSame from './is-same'; class ZipError extends Error { constructor(...args) { super(...args); Error.captureStackTrace(this, ZipError); } } const zip = (arrays, strides) => { if (arrays.length !== strides.length) throw new ZipError('number of arrays and number of strides does not match'); const normLenghts = arrays.map((array, i) => array.length / strides[i]); if (!isSame(normLenghts)) throw new ZipError('normalized array length does not equal'); const out = []; const indices = arrays.map(() => 0); const numArrays = arrays.length; for (let i = 0; i < normLenghts[0]; i++) { const entry = []; for (let j = 0; j < numArrays; j++) { entry.push(...arrays[j].slice(indices[j], indices[j] + strides[j])); indices[j] += strides[j]; } out.push(entry); } return out; }; export default zip; <|start_filename|>ui/src/components/RightBarContent.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; // Styles import './RightBarContent.scss'; const classNames = () => { const className = 'full-dim right-bar-content'; return className; }; const RightBarContent = props => ( <div className={classNames(props)}>{props.children}</div> ); RightBarContent.propTypes = { children: PropTypes.node.isRequired }; export default RightBarContent; <|start_filename|>ui/src/components/TabEntry.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; // Components import Icon from './Icon'; // Styles import './TabEntry.scss'; class TabEntry extends React.Component { constructor(props) { super(props); this.state = { isOpen: true }; } render() { let className = 'tab-entry'; className += this.props.className ? ` ${this.props.className}` : ''; className += this.isOpen && this.props.isHeightStretching ? ' flex-g-1' : ''; className += this.props.title ? ' tab-entry-has-header' : ''; className += this.props.isVScrollable ? ' is-v-scrollable' : ''; return ( <div className={className}> {this.props.title && ( <div className="tab-entry-header flex-c flex-a-c" onClick={this.toggle.bind(this)} > <Icon iconId="arrow-bottom" mirrorH={!this.isOpen} /> {this.props.title} </div> )} <div className="tab-entry-content"> {this.isOpen && this.props.children} </div> </div> ); } /* ----------------------------- Getter / Setter -------------------------- */ get isOpen() { return typeof this.props.isOpen !== 'undefined' ? this.props.isOpen : this.state.isOpen; } /* ------------------------------ Custom Methods -------------------------- */ close() { this.setState({ isOpen: false }); } open() { this.setState({ isOpen: true }); } toggle() { if (typeof this.props.isOpen !== 'undefined' && this.props.toggle) { this.props.toggle(this.props.isOpen); return; } if (this.isOpen) { this.close(); } else { this.open(); } } } TabEntry.propTypes = { children: PropTypes.node.isRequired, className: PropTypes.string, isCollapsible: PropTypes.bool, isHeightStretching: PropTypes.bool, isOpen: PropTypes.bool, isVScrollable: PropTypes.bool, title: PropTypes.string, toggle: PropTypes.func }; export default TabEntry; <|start_filename|>ui/src/components/Content.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; // Configs import { RIGHT_BAR_MIN_WIDTH } from './RightBar'; // Styles import './Content.scss'; const classNames = props => { let className = 'flex-g-1 content'; className += ` ${props.name}-content`; className += props.hasRightBar ? ' has-right-bar' : ''; className += props.hasSubTopBar ? ' has-sub-top-bar' : ''; className += props.rel ? ' rel' : ''; className += props.wrap ? ' wrap' : ''; className += !props.bottomMargin ? ' no-bottom-margin' : ''; className += props.isVertFlex ? ' flex-c flex-v' : ''; className += props.hasSmallerTopBar ? ' has-smaller-top-bar' : ''; return className; }; const styles = props => { if (props.hasRightBar) { return { marginRight: `${ props.rightBarShow ? Math.max(RIGHT_BAR_MIN_WIDTH, props.rightBarWidth) : RIGHT_BAR_MIN_WIDTH }px` }; } return {}; }; const Content = props => ( <main className={classNames(props)} style={styles(props)}> {props.children} </main> ); Content.defaultProps = { bottomMargin: true }; Content.propTypes = { bottomMargin: PropTypes.bool, children: PropTypes.node, hasRightBar: PropTypes.bool, hasSubTopBar: PropTypes.bool, isVertFlex: PropTypes.bool, hasSmallerTopBar: PropTypes.bool, name: PropTypes.string.isRequired, rel: PropTypes.bool, rightBarShow: PropTypes.bool, rightBarWidth: PropTypes.number, wrap: PropTypes.bool }; export default Content; <|start_filename|>ui/src/utils/merge-json-response.js<|end_filename|> const mergeJsonResponse = response => response.json().then(body => ({ body, status: response.status })); export default mergeJsonResponse; <|start_filename|>ui/src/views/SearchSubTopBarTabs.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; import { connect } from 'react-redux'; // Components import Button from '../components/Button'; import ButtonIcon from '../components/ButtonIcon'; import SubTopBar from '../components/SubTopBar'; import TabTrigger from '../components/TabTrigger'; // Actions import { setSearchSelection, setSearchTab } from '../actions'; // Configs import { TAB_CLASSIFICATIONS, TAB_RESULTS, TAB_SEEDS, TAB_SELECTION } from '../configs/search'; // Utils import { Logger } from '../utils'; const logger = Logger('SearchSubTopBarTabs'); // eslint-disable-line const SearchSubTopBarTabs = props => ( <SubTopBar className="search-tab-triggers" stretch={true}> <TabTrigger for={TAB_SEEDS} tabChange={props.setTab} tabOpen={props.tab} className="rel flex-g-1" > <Button className="full-wh">New Samples</Button> </TabTrigger> <TabTrigger for={TAB_RESULTS} tabChange={props.setTab} tabOpen={props.tab} className="rel flex-g-1" > <Button className="full-wh">Results</Button> </TabTrigger> <TabTrigger for={TAB_CLASSIFICATIONS} tabChange={props.setTab} tabOpen={props.tab} className="rel flex-g-1" > <Button className="full-wh">Labels</Button> </TabTrigger> <TabTrigger for={TAB_SELECTION} tabChange={props.setTab} tabOpen={props.tab} className={`rel ${ props.selectedRegions.length ? 'flex-g-1' : 'flex-g-0' }`} > <Button className={`full-h ${ props.selectedRegions.length ? 'full-w' : 'no-w' } flex-c flex-jc-c flex-a-c search-tab-trigger-selection`} tag="div" > Selection <ButtonIcon icon="cross" iconOnly onClick={e => { e.stopPropagation(); props.clearSelection(); if (props.tab === TAB_SELECTION) { props.setTab(TAB_RESULTS); } }} /> </Button> </TabTrigger> </SubTopBar> ); SearchSubTopBarTabs.defaultProps = { minClassifications: Infinity, numClassifications: 0 }; SearchSubTopBarTabs.propTypes = { clearSelection: PropTypes.func, minClassifications: PropTypes.number, numClassifications: PropTypes.number, selectedRegions: PropTypes.array.isRequired, setTab: PropTypes.func.isRequired, tab: PropTypes.oneOfType([PropTypes.string, PropTypes.symbol]).isRequired }; const mapStateToProps = state => ({ selectedRegions: state.present.searchSelection, tab: state.present.searchTab }); const mapDispatchToProps = dispatch => ({ clearSelection: () => dispatch(setSearchSelection([])), setTab: searchTab => dispatch(setSearchTab(searchTab)) }); export default connect( mapStateToProps, mapDispatchToProps )(SearchSubTopBarTabs); <|start_filename|>ui/src/views/Help.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; // Higher-order components import { withPubSub } from '../hocs/pub-sub'; // Components import Content from '../components/Content'; import ContentWrapper from '../components/ContentWrapper'; import Footer from '../components/Footer'; import Icon from '../components/Icon'; import IconGallery from '../components/IconGallery'; // Utils import Deferred from '../utils/deferred'; // Stylesheets import './About.scss'; const showIcons = pubSub => { pubSub.publish('globalDialog', { message: <IconGallery />, request: new Deferred(), resolveOnly: true, resolveText: 'Close', headline: 'All Available Icons' }); }; class Help extends React.Component { constructor(props) { super(props); this.pubSubs = []; this.swag = [[73, 67, 79, 78, 83]]; this.swagI = 0; this.swagJ = 0; this.swagInterval = 500; this.swagTime = performance.now(); } componentDidMount() { this.pubSubs.push( this.props.pubSub.subscribe('keyup', this.keyUpHandler.bind(this)) ); } componentWillUnmount() { this.pubSubs.forEach(subscription => this.props.pubSub.unsubscribe(subscription) ); this.pubSubs = []; } keyUpHandler(event) { this.keyUpSwagHandler(event.keyCode); } keyUpSwagHandler(keyCode) { const now = performance.now(); if (now - this.swagTime > this.swagInterval) { this.swagJ = 0; } this.swagTime = now; if (this.swagJ === 0) { this.swag.forEach((codeWurst, index) => { if (keyCode === codeWurst[0]) { this.swagI = index; this.swagJ = 1; } }); } else if (keyCode === this.swag[this.swagI][this.swagJ]) { this.swagJ += 1; } if (this.swagJ === this.swag[this.swagI].length) { switch (this.swagI) { case 0: showIcons(this.props.pubSub); break; default: // Nothing } } } render() { return ( <ContentWrapper name="help"> <Content name="help"> <div className="border-bottom p-t-1 p-b-1"> <div className="wrap"> <p> You need help getting started with Peax or ran into a tricky issue? Fear not! Below is a list of excellent resources that can hopefully help you out! </p> </div> </div> <div className="wrap p-b-2"> <h3 id="getting-started" className="iconized underlined anchored"> <a href="#getting-started" className="hidden-anchor"> <Icon iconId="link" /> </a> <Icon iconId="launch" /> <span>Getting Started</span> </h3> <p> At some point in the far far away future you will find some marvelous getting started guide here. Until then you are excused to freak out. </p> </div> </Content> <Footer /> </ContentWrapper> ); } } Help.propTypes = { pubSub: PropTypes.object.isRequired }; export default withPubSub(Help); <|start_filename|>ui/src/components/AppInfo.js<|end_filename|> import React from 'react'; // Utils import getServer from '../utils/get-server'; import Logger from '../utils/logger'; const URL = `${getServer()}/version.txt`; const logger = Logger('AppInfo'); class AppInfo extends React.Component { constructor(props) { super(props); this.state = { serverVersion: <em>(loading&hellip;)</em> }; fetch(URL) .then(response => response.text()) .then(response => { if (response.split('\n')[0].substr(0, 14) !== 'SERVER_VERSION') { throw Error( 'Could not parse `version.txt`. Expecting the first line to start with `SERVER_VERSION`.' ); } this.setState({ serverVersion: response.split('\n')[0].slice(16) }); }) .catch(error => { logger.warn('Could not retrieve or parse server version.', error); this.setState({ serverVersion: <em>(unknown)</em> }); }); } render() { return ( <div className="app-info"> <ul className="no-list-style"> <li> <strong>Peax</strong>: Version {VERSION_PEAX} </li> <li> <strong>HiGlass</strong>: Version {VERSION_HIGLASS} </li> <li> <strong>Server</strong>: Version {this.state.serverVersion} </li> </ul> </div> ); } } export default AppInfo; <|start_filename|>examples/config-encode-e11-5-limb-midbrain.json<|end_filename|> { "encoders": [ { "content_type": "dnase-seq-3kb", "from_file": "examples/autoencoders.json" }, { "content_type": "histone-mark-chip-seq-3kb", "from_file": "examples/autoencoders.json" } ], "datasets": [ { "filepath": "examples/data/ENCFF641OPE.bigWig", "content_type": "dnase-seq-3kb", "id": "encode-e11-5-limb-dnase-rdns", "name": "Limb: DNase rdn signal" }, { "filepath": "examples/data/ENCFF336LAW.bigWig", "content_type": "histone-mark-chip-seq-3kb", "id": "encode-e11-5-limb-chip-h3k27ac-fc", "name": "Limb: H3K27ac fc" }, { "filepath": "examples/data/ENCFF906WCV.bigWig", "content_type": "dnase-seq-3kb", "id": "encode-e11-5-midbrain-dnase-rdns", "name": "Midbrain: DNase rdn signal" }, { "filepath": "examples/data/ENCFF847OYS.bigWig", "content_type": "histone-mark-chip-seq-3kb", "id": "encode-e11-5-midbrain-chip-h3k27ac-fc", "name": "Midbrain: H3K27ac fc" } ], "coords": "mm10", "chroms": ["chr1"], "step_freq": 2, "db_path": "examples/search-e11-5-limb-midbrain.db" } <|start_filename|>ui/src/components/SubTopBar.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; // Styles import './SubTopBar.scss'; const SubTopBar = props => ( <header className={`sub-top-bar ${props.className}`}> <div className={`flex-c ${ props.stretch ? 'flex-a-s' : 'flex-a-c' } flex-jc-sb sub-top-bar-content-wrap ${props.wrap ? 'wrap' : ''}`} > {props.children} </div> </header> ); SubTopBar.defaultProps = { className: '', stretch: false, wrap: false }; SubTopBar.propTypes = { children: PropTypes.node.isRequired, className: PropTypes.string, stretch: PropTypes.bool, wrap: PropTypes.bool }; export default SubTopBar; <|start_filename|>ui/src/components/Message.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; // Components import Icon from './Icon'; import Spinner from './Spinner'; import './Message.scss'; const getIcon = type => { switch (type) { case 'error': case 'warning': return 'warning'; case 'help': return 'help'; case 'info': default: return 'info-disc'; } }; const Message = props => ( <div className={`flex-c flex-v flex-a-c message message-${props.type}`}> {props.type === 'loading' ? ( <Spinner /> ) : ( <Icon iconId={getIcon(props.type)} /> )} <p>{props.msg ? props.msg : props.children}</p> <div>{props.msg && props.children && props.children}</div> </div> ); Message.defaultProps = { type: 'default' }; Message.propTypes = { children: PropTypes.node, msg: PropTypes.string, type: PropTypes.oneOf([ 'default', 'help', 'info', 'warning', 'error', 'loading' ]) }; export default Message; <|start_filename|>ui/src/views/About.js<|end_filename|> import React from 'react'; // Components import Content from '../components/Content'; import ContentWrapper from '../components/ContentWrapper'; import Footer from '../components/Footer'; import Icon from '../components/Icon'; // Stylesheets import './About.scss'; const About = () => ( <ContentWrapper name="about"> <Content name="about"> <div className="wrap p-b-2"> <h3 id="abstract" className="iconized underlined anchored"> <a href="#abstract" className="hidden-anchor"> <Icon iconId="link" /> </a> <Icon iconId="text" /> <span>Summary</span> </h3> <p className="abstract"> Epigenomic data expresses a rich body of diverse patterns that help to identify regulatory elements like promoter, enhancers, etc. But finding these patterns reliably genome wide is challenging. Peax is a tool for interactive visual pattern search and exploration of epigenomic patterns based on unsupervised representation learning with convolutional autoencoders. The visual search is driven by manually labeled genomic regions for actively learning a classifier to reflect your notion of interestingness. </p> <h3 id="preprint" className="iconized underlined anchored"> <a href="#preprint" className="hidden-anchor"> <Icon iconId="link" /> </a> <Icon iconId="document" /> <span>Preprint</span> </h3> <p> <strong> Peax: Interactive Visual Pattern Search in Sequential Data Using Unsupervised Deep Representation Learning </strong> <br /> <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> <br /> <em>bioRxiv</em>, 2019, doi:{' '} <a href="https://doi.org/10.1101/597518" target="_blank" rel="noopener noreferrer" > 10.1101/597518 </a> </p> <h3 id="abstract" className="iconized underlined anchored"> <a href="#abstract" className="hidden-anchor"> <Icon iconId="link" /> </a> <Icon iconId="people" /> <span>People</span> </h3> <ol className="no-list-style authors"> <li className="flex-c flex-v"> <span className="name"><NAME></span> <span className="affiliation"> Harvard John A. Paulson School of Engineering and Applied Sciences </span> <ul className="no-list-style flex-c out-links"> <li> <a className="flex-c flex-a-c" href="https://lekschas.de" target="_blank" rel="noopener noreferrer" > <Icon iconId="globe" /> lekschas.de </a> </li> <li> <a className="flex-c flex-a-c" href="https://twitter.com/flekschas" target="_blank" rel="noopener noreferrer" > <Icon iconId="gezwitscher" /> flekschas </a> </li> <li> <a className="flex-c flex-a-c" href="https://github.com/flekschas" target="_blank" rel="noopener noreferrer" > <Icon iconId="github" /> flekschas </a> </li> </ul> </li> <li className="flex-c flex-v"> <span className="name"><NAME></span> <span className="affiliation"> Novartis Institutes for BioMedical Research </span> <ul className="no-list-style flex-c out-links"> <li> <a className="flex-c flex-a-c" href="https://twitter.com/fixedbydrift" target="_blank" rel="noopener noreferrer" > <Icon iconId="gezwitscher" /> fixedbydrift </a> </li> </ul> </li> <li className="flex-c flex-v"> <span className="name"><NAME></span> <span className="affiliation"> Har<NAME>son School of Engineering and Applied Sciences </span> <ul className="no-list-style flex-c out-links"> <li> <a className="flex-c flex-a-c" href="https://danielhaehn.com" target="_blank" rel="noopener noreferrer" > <Icon iconId="globe" /> danielhaehn.com </a> </li> <li> <a className="flex-c flex-a-c" href="https://twitter.com/danielhaehn" target="_blank" rel="noopener noreferrer" > <Icon iconId="gezwitscher" /> danielhaehn </a> </li> <li> <a className="flex-c flex-a-c" href="https://github.com/haehn" target="_blank" rel="noopener noreferrer" > <Icon iconId="github" /> haehn </a> </li> </ul> </li> <li className="flex-c flex-v"> <span className="name"><NAME></span> <span className="affiliation"> Novartis Institutes for BioMedical Research </span> <ul className="no-list-style flex-c out-links"> <li> <a className="flex-c flex-a-c" href="http://ericmjl.com" target="_blank" rel="noopener noreferrer" > <Icon iconId="globe" /> ericmjl.com </a> </li> <li> <a className="flex-c flex-a-c" href="https://twitter.com/ericmjl" target="_blank" rel="noopener noreferrer" > <Icon iconId="gezwitscher" /> ericmjl </a> </li> <li> <a className="flex-c flex-a-c" href="https://github.com/ericmjl" target="_blank" rel="noopener noreferrer" > <Icon iconId="github" /> ericmjl </a> </li> </ul> </li> <li className="flex-c flex-v"> <span className="name"><NAME></span> <span className="affiliation">Harvard Medical School</span> <ul className="no-list-style flex-c out-links"> <li> <a className="flex-c flex-a-c" href="http://gehlenborglab.org" target="_blank" rel="noopener noreferrer" > <Icon iconId="globe" /> gehlenborglab.org </a> </li> <li> <a className="flex-c flex-a-c" href="https://twitter.com/ngehlenborg" target="_blank" rel="noopener noreferrer" > <Icon iconId="gezwitscher" /> ngehlenborg </a> </li> <li> <a className="flex-c flex-a-c" href="https://github.com/ngehlenborg" target="_blank" rel="noopener noreferrer" > <Icon iconId="github" /> ngehlenborg </a> </li> </ul> </li> <li className="flex-c flex-v"> <span className="name"><NAME></span> <span className="affiliation"> Harvard John A. Paulson School of Engineering and Applied Sciences </span> <ul className="no-list-style flex-c out-links"> <li> <a className="flex-c flex-a-c" href="https://vcg.seas.harvard.edu/people" target="_blank" rel="noopener noreferrer" > <Icon iconId="globe" /> vcg.seas.harvard.edu </a> </li> <li> <a className="flex-c flex-a-c" href="https://twitter.com/hpfister" target="_blank" rel="noopener noreferrer" > <Icon iconId="gezwitscher" /> hpfister </a> </li> </ul> </li> </ol> <h3 id="source-code" className="iconized underlined anchored"> <a href="#source-code" className="hidden-anchor"> <Icon iconId="link" /> </a> <Icon iconId="code" /> Code &amp; Data </h3> <ul className="no-list-style large-spacing iconized"> <li className="iconized"> <Icon iconId="github" /> <span className="m-r-0-5">Source code:</span> <a href="https://github.com/novartis/peax" target="_blank" rel="noopener noreferrer" > github.com/novartis/peax </a> </li> <li className="iconized"> <Icon iconId="data" /> <span className="m-r-0-5">Trained autoencoders:</span> <a href="https://doi.org/10.5281/zenodo.2609763" target="_blank" rel="noopener noreferrer" > doi.org/10.5281/zenodo.2609763 </a> </li> </ul> <br /> <p>Peax is based on and using the following open source tools:</p> <ul className="no-list-style large-spacing iconized"> <li className="iconized"> <Icon iconId="github" /> <span className="m-r-0-5">Genome viewer:</span> <a href="https://github.com/higlass/higlass" target="_blank" rel="noopener noreferrer" > github.com/higlass/higlass </a> </li> <li className="iconized"> <Icon iconId="github" /> <span className="m-r-0-5">UI architecture:</span> <a href="https://github.com/higlass/higlass-app" target="_blank" rel="noopener noreferrer" > github.com/higlass/higlass-app </a> </li> <li className="iconized"> <Icon iconId="github" /> <span className="m-r-0-5">Server:</span> <a href="https://github.com/higlass/hgflask" target="_blank" rel="noopener noreferrer" > github.com/higlass/hgflask </a> </li> </ul> <h3 id="design" className="iconized underlined anchored"> <a href="#design" className="hidden-anchor"> <Icon iconId="link" /> </a> <Icon iconId="pen-ruler" /> Design </h3> <p> The website and logo (<Icon iconId="logo" inline />) are designed by{' '} <a href="https://lekschas.de" target="_blank" rel="noopener noreferrer" > <NAME> </a> . </p> <h3 id="copyright" className="iconized underlined anchored"> <a href="#copyright" className="hidden-anchor"> <Icon iconId="link" /> </a> <Icon iconId="info-circle" /> Icons </h3> <p> The following sets of beautiful icons have been slightly adjusted by Fritz Lekschas and are used across the application. Hugs thanks to the authors for their fantastic work! </p> <ul className="no-list-style large-spacing iconized"> <li className="flex-c iconized"> <Icon iconId="code" /> <p className="nm"> <a href="https://thenounproject.com/term/code/821469/" target="_blank" rel="noopener noreferrer" > Code </a> <span> by <NAME></span> </p> </li> <li className="flex-c iconized"> <Icon iconId="launch" /> <p className="nm"> <a href="https://thenounproject.com/icon/1372884/" target="_blank" rel="noopener noreferrer" > Launch </a> <span> by Bhuvan</span> </p> </li> </ul> </div> </Content> <Footer /> </ContentWrapper> ); export default About; <|start_filename|>ui/src/views/SearchRightBarHelp.js<|end_filename|> import React from 'react'; // Components import Icon from '../components/Icon'; const SearchRightBarHelp = () => ( <div className="right-bar-help flex-c flex-v full-wh"> <ul className="search-right-bar-padding no-list-style compact-list compact-list-with-padding"> <li> <strong>Hit: </strong> <span> A hit is a genomic window that is classified positive by the random forest model based on your labels and your probability threshold. </span> </li> <li> <strong>Label: </strong> <span> A label is the manual assignment of either a positive ( <Icon iconId="checkmark" inline />) or negative ( <Icon iconId="cross" inline />) class to a genomic window. </span> </li> <li> <strong>Training: </strong> <span> After labeling some genomic windows, a random forest classifier will be train. </span> </li> <li> <strong>Uncertainty: </strong> <span> Class prediction uncertainty is defined as the mean distance of classification probabilities from 0.5. An uncertainty of 1 is the worst and means that the classifier predicts the class for window with probability 0.5. An uncertainty of 0 is the best and means that the classifier predicts the class for window with either 1.0 or 0.0. </span> </li> <li> <strong>Variance: </strong> <span> Class prediction variance is defined as the mean variance of class predictions based on confidence intervals as proposed by{' '} <a href="http://jmlr.org/papers/v15/wager14a.html" target="_blank" rel="noopener noreferrer" > Wager et al. 2014 </a> </span> </li> </ul> </div> ); export default SearchRightBarHelp; <|start_filename|>ui/src/components/DropDownContent.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; // Styles import './DropDownContent.scss'; const DropDownContent = props => ( <div className="drop-down-content"> <div className="flex-c flex-v">{props.children}</div> </div> ); DropDownContent.propTypes = { children: PropTypes.node.isRequired }; export default DropDownContent; <|start_filename|>ui/src/components/ErrorMsgCenter.js<|end_filename|> import PropTypes from 'prop-types'; import React from 'react'; // Components import ErrorMsg from './ErrorMsg'; const ErrorMsgCenter = props => ( <div className="full-dim flex-c flex-a-c flex-jc-c error-msg-center"> <ErrorMsg msg={props.msg} /> </div> ); ErrorMsgCenter.propTypes = { msg: PropTypes.string.isRequired }; export default ErrorMsgCenter;
haehn/peax
<|start_filename|>static/js/client.js<|end_filename|> let app_index = null; const socket = io({ // triggers server's io.on connect path: `${app_index = document.getElementById("app_index").getAttribute("content")}/socket.io` }); let filesize_limit = null; let page_limit = null; let queue_size = null; const dropdown_btn = document.getElementById("dropdown_btn"); const dropdown_menu = document.getElementById("dropdown_menu"); const last24hours_total_wrapper = document.getElementById("last24hours_total_wrapper"); const last7days_total_wrapper = document.getElementById("last7days_total_wrapper"); const last30days_total_wrapper = document.getElementById("last30days_total_wrapper"); const last24hours_list_wrapper = document.getElementById("last24hours_list_wrapper"); const last7days_list_wrapper = document.getElementById("last7days_list_wrapper"); const last30days_list_wrapper = document.getElementById("last30days_list_wrapper"); const countdown_wrapper = document.getElementById("countdown_wrapper"); const progress = document.getElementById("progress"); const progress_wrapper = document.getElementById("progress_wrapper"); const progress_status = document.getElementById("progress_status"); const convert_btn = document.getElementById("convert_btn"); const loading_btn = document.getElementById("loading_btn"); const cancel_btn = document.getElementById("cancel_btn"); const alert_wrapper = document.getElementById("alert_wrapper"); const file_input_container = document.getElementById("file_input_container"); const file_input = document.getElementById("file_input"); const file_input_label = document.getElementById("file_input_label"); const terminal = document.getElementById("terminal"); const post_terminal_space = document.getElementById("post_terminal_space"); const messages = document.getElementById("messages"); const form_check_inputs = document.getElementsByClassName("form-check-input"); const no_ocr_dark_radio = document.getElementById("no_ocr_dark_radio"); const ocr_dark_radio = document.getElementById("ocr_dark_radio"); const dim_radio = document.getElementById("dim_radio"); const retain_img_colors_checkbox = document.getElementById("retain_img_colors_checkbox"); const text_color_1_checkbox = document.getElementById("text_color_1_checkbox"); const text_color_2_checkbox = document.getElementById("text_color_2_checkbox"); const color_picker_1 = document.getElementById("color_picker_1"); const color_picker_2 = document.getElementById("color_picker_2"); const language_checkbox = document.getElementById("language_checkbox"); const language_select = document.getElementById("language_select"); let language_select_btn = setTimeout(() => language_select_btn = document.getElementsByClassName("bs-placeholder")[0], 1000); let language_select_dropdown = setTimeout(() => language_select_dropdown = document.getElementsByClassName("bootstrap-select")[0], 1000); const jobs_queued_text = document.getElementById("jobs_queued_text"); const jobs_queued_wrapper = document.getElementById("jobs_queued_wrapper"); const queue_position_text = document.getElementById("queue_position_text"); const queue_position_wrapper = document.getElementById("queue_position_wrapper"); const dl = document.getElementById("dl"); if (document.cookie) { const light_mode = document.cookie.split("; ").find((cookie) => cookie.startsWith("light_mode")).split("=")[1]; if (light_mode == "on") { document.documentElement.classList.add("invert"); document.body.classList.add("light_mode"); dropdown_btn.classList.add("anti_invert"); dropdown_menu.classList.add("anti_invert"); dropdown_menu.classList.add("light_mode"); file_input_container.classList.add("anti_invert"); color_picker_1.classList.add("anti_invert"); color_picker_2.classList.add("anti_invert"); alert_wrapper.classList.add("anti_invert"); convert_btn.classList.add("anti_invert"); [...form_check_inputs].forEach((form_check_input) => form_check_input.classList.add("anti_invert")); setTimeout(() => [...document.getElementById("language_select_container").children[0].children].forEach((child) => child.classList.add("anti_invert")), 1000); } } document.addEventListener("keydown", (evt) => { (evt.code == "Escape" ? setTimeout(() => (!dropdown_menu.classList.contains("show") ? dropdown_btn.blur() : null), 100) : null); setTimeout(() => { const no_results = document.getElementsByClassName("no-results")[0]; (no_results && !no_results.classList.contains("d-none") ? no_results.classList.add("d-none") : null); (typeof language_select_dropdown != "number" && !language_select_dropdown.classList.contains("show") ? language_select_btn.blur() : null); }, 100); }); document.addEventListener("click", (evt) => (evt.target.classList.contains("dropdown-item") || evt.target.parentElement && evt.target.parentElement.classList.contains("dropdown-item") ? language_select_btn.blur() : null)); setTimeout(() => { language_select_btn.addEventListener("click", (evt) => (!language_select_dropdown.classList.contains("show") ? language_select_btn.blur() : null)); }, 1000); dropdown_btn.addEventListener("click", (evt) => { setTimeout(() => (!dropdown_menu.classList.contains("show") ? dropdown_btn.blur() : null), 100); setTimeout(() => { dropdown_menu.scrollIntoView({ behavior: "smooth", block: "end" }); }, 250); }); file_input.addEventListener("input", (evt) => file_input_label.innerText = file_input.files[0].name); no_ocr_dark_radio.addEventListener("click", (evt) => { text_color_1_checkbox.disabled = false; text_color_1_checkbox.checked = true; text_color_2_checkbox.disabled = true; text_color_2_checkbox.checked = false; retain_img_colors_checkbox.disabled = false; language_checkbox.disabled = true; language_checkbox.checked = false; }); ocr_dark_radio.addEventListener("click", (evt) => { text_color_2_checkbox.disabled = false; text_color_2_checkbox.checked = true; text_color_1_checkbox.disabled = true; text_color_1_checkbox.checked = false; retain_img_colors_checkbox.disabled = true; retain_img_colors_checkbox.checked = false; language_checkbox.disabled = false; language_checkbox.checked = true; }); dim_radio.addEventListener("click", (evt) => { text_color_1_checkbox.disabled = true; text_color_1_checkbox.checked = false; text_color_2_checkbox.disabled = true; text_color_2_checkbox.checked = false; retain_img_colors_checkbox.disabled = true; retain_img_colors_checkbox.checked = false; language_checkbox.disabled = true; language_checkbox.checked = false; }); convert_btn.addEventListener("click", async (evt) => { const alert_message_wrapper = document.getElementById("alert_message_wrapper"); if (alert_message_wrapper) { const alert_message = alert_message_wrapper.innerHTML; if (alert_message == "file uploaded" || alert_message == "current job incomplete") { show_alert("current job incomplete", "danger"); return; } } if (!file_input.value) { show_alert("no file selected", "warning"); return; } const file = file_input.files[0]; let filename = file.name; const filesize = file.size; // in binary bytes if (filename.split(".").pop().toLowerCase() != "pdf") { show_alert("this is not a pdf file", "warning"); return; } if (filesize > filesize_limit) { show_alert(`file size limit exceeded (${filesize_limit/1048576}mb)`, "warning"); return; } try { const num_pages = await new Promise((resolve, reject) => { const reader = new FileReader(); reader.readAsBinaryString(file); reader.onloadend = function () { const match = reader.result.match(/\/Type[\s]*\/Page[^s]/g); (match ? resolve(match.length) : reject("no match")); } reader.onerror = function () { reject(reader.error); } }); if (num_pages > page_limit) { show_alert(`page limit exceeded (${page_limit})`, "warning"); return; } } catch (err) { if (err != "no match") { console.error(err); show_alert("error", "danger"); return; } } alert_wrapper.innerHTML = ""; file_input.disabled = true; convert_btn.classList.add("d-none"); loading_btn.classList.remove("d-none"); cancel_btn.classList.remove("d-none"); progress_wrapper.classList.remove("d-none"); jobs_queued_text.classList.add("d-none"); filename = Math.random().toString().substring(2, 17); const data = new FormData(); data.append("file", file, filename); const request = new XMLHttpRequest(); request.open("post", `${app_index}/upload`); request.responseType = "json"; request.upload.addEventListener("progress", (evt) => { const loaded = evt.loaded; const total = evt.total; const percentage_complete = (loaded/total)*100; progress.setAttribute("style", `width: ${Math.floor(percentage_complete)}%`); progress_status.innerText = `${Math.floor(percentage_complete)}% uploaded`; }); request.addEventListener("load", (evt) => { reset(); show_alert("file uploaded", "success"); }); request.addEventListener("error", (evt) => { reset(); show_alert("error uploading file", "danger"); }); request.addEventListener("abort", (evt) => { reset(); show_alert("upload cancelled", "primary"); }); cancel_btn.addEventListener("click", (evt) => request.abort()); request.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { setTimeout(() => { post_terminal_space.scrollIntoView({ behavior: "smooth", block: "end" }); }, 1000); let transform_option = document.querySelector("input[name='transform_option']:checked").value.replace("_radio", ""); (transform_option == "no_ocr_dark" && retain_img_colors_checkbox.checked ? transform_option = "no_ocr_dark_retain_img_colors" : null); const color_hex = (text_color_1_checkbox.checked ? color_picker_1.value : color_picker_2.value); const language_code = (language_select.value == "" ? "eng" : language_select.value); socket.emit("enqueue", filename, transform_option, color_hex, language_code); queue_position_text.classList.remove("d-none"); } } request.send(data); }); socket.on("replace localhost with dev private ip", (dev_private_ip) => { const all_a_tags = document.getElementsByTagName("a"); [...all_a_tags].forEach((a_tag) => a_tag.href = a_tag.href.replace("localhost", dev_private_ip)); }); socket.on("update countdown", (countdown) => countdown_wrapper.innerHTML = countdown); socket.on("update domain request info", (domain_request_info) => { last24hours_total_wrapper.innerHTML = domain_request_info.last24hours_total; last7days_total_wrapper.innerHTML = domain_request_info.last7days_total; last30days_total_wrapper.innerHTML = domain_request_info.last30days_total; last24hours_list_wrapper.innerHTML = ""; last7days_list_wrapper.innerHTML = ""; last30days_list_wrapper.innerHTML = ""; list_domain_request_info(domain_request_info.last24hours_countries, last24hours_list_wrapper); list_domain_request_info(domain_request_info.last7days_countries, last7days_list_wrapper); list_domain_request_info(domain_request_info.last30days_countries, last30days_list_wrapper); }); socket.on("set limits", (limits) => { filesize_limit = limits[0]; page_limit = limits[1]; }); socket.on("update jobs queued", (jobs_queued) => queue_size = jobs_queued_wrapper.innerHTML = jobs_queued); socket.on("update queue position", (queue_position) => queue_position_wrapper.innerHTML = `${queue_position}/${queue_size}`); socket.on("start", () => { jobs_queued_text.classList.remove("d-none"); queue_position_text.classList.add("d-none"); }); socket.on("message", (message) => { remove_blinking_caret(); output_message(message); add_blinking_caret(); terminal.scrollTop = terminal.scrollHeight; // scroll down }); socket.on("download", (filename) => { dl.href = `${app_index}/download?socket_id=${socket.id}&filename=${filename}`; dl.click(); alert_wrapper.innerHTML = ""; }); function list_domain_request_info(countries_array, parent_ul) { let li = null; if (countries_array.length == 0) { return; } else if (countries_array.length <= 3) { countries_array.forEach((country) => { li = document.createElement("li"); li.classList.add("mt-n1"); li.innerHTML = `${country.clientCountryName}: ${country.requests}`; parent_ul.appendChild(li); }); } else { countries_array.slice(0, 3).forEach((country) => { li = document.createElement("li"); li.classList.add("mt-n1"); li.innerHTML = `${country.clientCountryName}: ${country.requests}`; parent_ul.appendChild(li); }); li = document.createElement("li"); li.classList.add("mt-n1"); li.innerHTML = `${countries_array.length - 3} more`; parent_ul.appendChild(li); } } function output_message(message) { const p = document.createElement("p"); p.classList.add("mb-1"); p.innerHTML = `> ${message}`; messages.appendChild(p); } function remove_blinking_caret() { messages.removeChild(document.getElementById("gt_sign")); } function add_blinking_caret() { const p = document.createElement("p"); p.id = "gt_sign"; p.classList.add("mb-1"); p.innerHTML = "> <span id='blinking_caret'>|</span>"; messages.appendChild(p); } function show_alert(message, type) { alert_wrapper.innerHTML = ` <div id="alert" class="alert alert-${type} alert-dismissable fade show mt-2 mb-0 py-1" role="alert"> <span id="alert_message_wrapper">${message}</span> <button class="close" type="button" data-dismiss="alert"> <span>&times;</span> </button> </div> `; } function reset() { file_input.value = null; file_input.disabled = false; file_input_label.innerText = "choose file"; convert_btn.classList.remove("d-none"); loading_btn.classList.add("d-none"); cancel_btn.classList.add("d-none"); progress_wrapper.classList.add("d-none"); progress.setAttribute("style", "width: 0%"); } <|start_filename|>model/file_operations.js<|end_filename|> const project_root = process.cwd(); const filesystem = require("fs"); async function purge(filename) { await Promise.all([ filesystem.promises.unlink(`${project_root}/data/${filename}_in.pdf`), filesystem.promises.unlink(`${project_root}/data/${filename}_temp.pdf`), filesystem.promises.unlink(`${project_root}/data/${filename}_no_text.pdf`), filesystem.promises.unlink(`${project_root}/data/${filename}_out.pdf`) ]); } let leftover_pdfs = []; async function log_leftover_pdfs() { files = await filesystem.promises.readdir(`${project_root}/data`); files.forEach((file) => (file.endsWith(".pdf") ? leftover_pdfs.push(file) : null)); // console.log("logged leftover pdfs"); } async function delete_leftover_pdfs() { await Promise.all(leftover_pdfs.map((pdf) => filesystem.promises.unlink(`${project_root}/data/${pdf}`))); // console.log("deleted leftover pdfs"); leftover_pdfs = []; } async function cleanup(init=false) { (init ? await log_leftover_pdfs() : null); await delete_leftover_pdfs(); log_leftover_pdfs(); // console.log("cleanup completed"); } function cycle_cleanup() { setInterval(() => cleanup().catch((err) => console.error(err)), 36000000); // 10h } module.exports.purge = purge; module.exports.cleanup = cleanup; module.exports.cycle_cleanup = cycle_cleanup; <|start_filename|>model/sql_operations.js<|end_filename|> const project_root = process.cwd(); const run_config = (project_root.toLowerCase().slice(0, 20) == "/mnt/c/users/j9108c/" ? "dev" : "prod"); const secrets = (run_config == "dev" ? require(`${project_root}/_secrets.js`).dev : require(`${project_root}/_secrets.js`).prod); const node_pg = require("pg"); const sql_client = new node_pg.Client(secrets.sql_connection); async function connect_to_db() { await sql_client.connect(); (run_config == "dev" ? console.log("connected to (test) sql db") : console.log("connected to (prod) sql db")); } async function init_db() { if (run_config == "dev") { const result = await sql_client.query( "select table_name " + "from information_schema.tables " + "where table_schema='public' " + "and table_type='BASE TABLE';" ); const all_tables = result.rows; await Promise.all(all_tables.map((table) => { sql_client.query( `drop table ${table.table_name} cascade;` ); })); console.log("dropped all tables"); } else if (run_config == "prod") { console.log("kept all tables"); } await sql_client.query( "create table if not exists visit (" + "id int primary key, " + "count int not null" + ");" ); console.log('created table (visit) if not exist'); await sql_client.query( "insert into visit " + "values (0, 0) " + "on conflict do nothing;" ); await sql_client.query( "create table if not exists conversion (" + "id int primary key, " + "count int not null" + ");" ); console.log('created table (conversion) if not exist'); await sql_client.query( "insert into conversion " + "values (0, 0) " + "on conflict do nothing;" ); } async function add_visit() { await sql_client.query( "update visit " + "set count=count+1 " + "where id=0;" ); } async function add_conversion() { await sql_client.query( "update conversion " + "set count=count+1 " + "where id=0;" ); } module.exports.connect_to_db = connect_to_db; module.exports.init_db = init_db; module.exports.add_visit = add_visit; module.exports.add_conversion = add_conversion; <|start_filename|>controller/server.js<|end_filename|> const project_root = process.cwd(); const run_config = (project_root.toLowerCase().slice(0, 20) == "/mnt/c/users/j9108c/" ? "dev" : "prod"); console.log(`${run_config}: ${project_root}`); const secrets = (run_config == "dev" ? require(`${project_root}/_secrets.js`).dev : require(`${project_root}/_secrets.js`).prod); const sql_operations = require(`${project_root}/model/sql_operations.js`); const file_operations = require(`${project_root}/model/file_operations.js`); const express = require("express"); const express_hbs = require("express-handlebars"); const http = require("http"); const socket_io = require("socket.io"); const socket_io_client = require("socket.io-client"); const child_process = require("child_process"); const fileupload = require("express-fileupload"); const app = express(); const app_name = "dark-mode-pdf"; const app_index = `/apps/${app_name}`; // index of this server relative to domain const server = http.createServer(app); const io = socket_io(server, { path: `${app_index}/socket.io` }); sql_operations.connect_to_db().then(() => sql_operations.init_db()).catch((err) => console.error(err)); file_operations.cleanup(true).then(() => file_operations.cycle_cleanup()).catch((err) => console.error(err)); process.nextTick(() => setInterval(() => io.emit("update jobs queued", Object.keys(queue).length), 100)); const queue = {}; app.use(fileupload()); app.use(`${app_index}/static`, express.static(`${project_root}/static`)); app.set("views", `${project_root}/static/html`); app.set("view engine", "handlebars"); app.engine("handlebars", express_hbs({ layoutsDir: `${project_root}/static/html`, defaultLayout: "template.handlebars" })); app.get(app_index, (req, res) => { res.render("index.handlebars", { title: `${app_name} — j9108c`, description: "converts PDFs to dark mode" }); }); app.get(app_index.split("-").join(""), (req, res) => { res.redirect(302, app_index); }); app.post(`${app_index}/upload`, (req, res) => { req.files.file.mv(`${project_root}/data/${req.files.file.name}_in.pdf`, (err) => (err ? console.error(err) : null)); res.end(); }); app.get(`${app_index}/download`, (req, res) => { console.log("sending pdf to your downloads"); io.to(req.query.socket_id).emit("message", "sending pdf to your downloads"); res.download(`${project_root}/data/${req.query.filename}_out.pdf`, `${req.query.filename}_out.pdf`, async () => { try { console.log("deleting your data from the server"); io.to(req.query.socket_id).emit("message", "deleting your data from the server"); await file_operations.purge(req.query.filename); } catch (err) { null; } finally { console.log("your data has been deleted from the server"); io.to(req.query.socket_id).emit("message", "your data has been deleted from the server"); console.log(`end ${req.query.filename}`); io.to(req.query.socket_id).emit("message", `end ${req.query.filename}`); delete queue[req.query.socket_id]; } }); }); app.get(`${app_index}/*`, (req, res) => { res.status(404).render("error.handlebars", { title: `404 — j9108c`, http_status: 404 }); }); io.on("connect", (socket) => { console.log(`socket (${socket.id}) connected`); const headers = socket.handshake.headers; // console.log(headers); const socket_address = headers.host.split(":")[0]; (socket_address == dev_private_ip_copy ? io.to(socket.id).emit("replace localhost with dev private ip", dev_private_ip_copy) : null); sql_operations.add_visit().catch((err) => console.error(err)); io.to(socket.id).emit("update countdown", countdown_copy); if (domain_request_info_copy) { io.to(socket.id).emit("update domain request info", domain_request_info_copy); } else { setTimeout(() => (domain_request_info_copy ? io.to(socket.id).emit("update domain request info", domain_request_info_copy) : null), 5000); } io.to(socket.id).emit("set limits", [secrets.filesize_limit, secrets.page_limit]); socket.on("enqueue", async (filename, transform_option, color_hex, language_code) => { queue[socket.id] = { filename: filename, interval_id: null, reject: null }; if (Object.keys(queue).length > 1) { io.to(socket.id).emit("message", "other job in progress"); setTimeout(() => io.to(socket.id).emit("message", "your job has been queued"), 1000); setTimeout(() => io.to(socket.id).emit("message", "please wait..."), 2000); } try { await new Promise((resolve, reject) => { const interval_id = setInterval(() => { io.to(socket.id).emit("update queue position", Object.keys(queue).indexOf(socket.id)); if (Object.keys(queue)[0] == socket.id) { clearInterval(interval_id); resolve(); } }, 1000); queue[socket.id].interval_id = interval_id; queue[socket.id].reject = reject; }); } catch (err) { (err != "socket disconnected" ? console.error(err) : null); return; } io.to(socket.id).emit("start"); console.log(`start ${filename}`); io.to(socket.id).emit("message", `start ${filename}`); const spawn = child_process.spawn(`${project_root}/virtual_environment/bin/python`, ["-u", `${project_root}/model/transform.py`, transform_option, filename, color_hex, language_code]); spawn.stderr.on("data", (data) => { const python_stderr = data.toString(); console.error(python_stderr); }); spawn.stdout.on("data", (data) => { const python_stdout = data.toString(); if (python_stdout != "\n") { console.log(python_stdout); io.to(socket.id).emit("message", python_stdout); } }); spawn.on("exit", (exit_code) => { if (exit_code != 0) { console.error(`error: spawn process exited with code ${exit_code}`); io.to(socket.id).emit("message", `error: spawn process exited with code ${exit_code}`); file_operations.purge(queue[socket.id].filename).catch((err) => null); queue[socket.id].reject("spawn error"); delete queue[socket.id]; return; } if (transform_option == "no_ocr_dark" || transform_option == "no_ocr_dark_retain_img_colors") { io.to(socket.id).emit("message", "loading..."); const spawn = child_process.spawn("gs", ["-o", `${project_root}/data/${filename}_no_text.pdf`, "-sDEVICE=pdfwrite", "-dFILTERTEXT", `${project_root}/data/${filename}_in.pdf`]); spawn.on("exit", (exit_code) => { if (exit_code != 0) { console.error(`error: spawn process exited with code ${exit_code}`); io.to(socket.id).emit("message", `error: spawn process exited with code ${exit_code}`); file_operations.purge(queue[socket.id].filename).catch((err) => null); queue[socket.id].reject("spawn error"); delete queue[socket.id]; return; } const spawn = child_process.spawn("java", ["-classpath", `${project_root}/vendor/pdfbox CLI tool — v=2.0.22.jar`, `${project_root}/model/overlay.java`, transform_option, filename]); spawn.stderr.on("data", (data) => { const java_stderr = data.toString(); console.error(java_stderr); }); spawn.stdout.on("data", (data) => { const java_stdout = data.toString(); if (java_stdout != "\n") { console.log(java_stdout); io.to(socket.id).emit("message", java_stdout); } }); spawn.on("exit", (exit_code) => { if (exit_code != 0) { console.error(`error: spawn process exited with code ${exit_code}`); io.to(socket.id).emit("message", `error: spawn process exited with code ${exit_code}`); file_operations.purge(queue[socket.id].filename).catch((err) => null); queue[socket.id].reject("spawn error"); delete queue[socket.id]; return; } sql_operations.add_conversion().catch((err) => console.error(err)); io.to(socket.id).emit("download", filename); }); }); } else { sql_operations.add_conversion().catch((err) => console.error(err)); io.to(socket.id).emit("download", filename); } }); }); socket.on("disconnect", () => { if (queue[socket.id]) { file_operations.purge(queue[socket.id].filename).catch((err) => null); clearInterval(queue[socket.id].interval_id); queue[socket.id].reject("socket disconnected"); delete queue[socket.id]; } }); }); let dev_private_ip_copy = null; let countdown_copy = null; let domain_request_info_copy = null; const io_as_client = socket_io_client.connect("http://localhost:1025", { reconnect: true, extraHeaders: { app: app_name, port: secrets.localhost_port } }); io_as_client.on("connect", () => { console.log("connected as client to j9108c (localhost:1025)"); io_as_client.on("store all apps urls", (all_apps_urls) => app.locals.all_apps_urls = all_apps_urls); io_as_client.on("store dev private ip", (dev_private_ip) => dev_private_ip_copy = dev_private_ip); io_as_client.on("update countdown", (countdown) => io.emit("update countdown", countdown_copy = countdown)); io_as_client.on("update domain request info", (domain_request_info) => io.emit("update domain request info", domain_request_info_copy = domain_request_info)); }); // set app local vars (auto passed as data to all hbs renders) app.locals.all_apps_urls = null; app.locals.app_index = app_index; app.locals.repo = `https://github.com/j9108c/${app_name}`; app.locals.current_year = new Date().getFullYear(); // port and listen const port = process.env.PORT || secrets.localhost_port; server.listen(port, () => console.log(`server (${app_name}) started on (localhost:${port})`)); <|start_filename|>model/overlay.java<|end_filename|> import java.lang.InterruptedException; import java.io.IOException; import java.io.File; import java.util.List; import java.util.HashMap; // https://pdfbox.apache.org/docs/2.0.12/javadocs import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.multipdf.Splitter; import org.apache.pdfbox.multipdf.Overlay; public class overlay { static void overlay(List<PDDocument> overlay_pdf, String position, int pagecount, List<PDDocument> base_pdf, PDDocument output_pdf) throws IOException, InterruptedException { System.out.println("applying " + position + " overlay"); Thread.sleep(100); // sleep for 100ms. need these small time delays after each print because of issue with spawn grouping the print outputs without the delays Overlay overlayer = new Overlay(); if (position.equals("background")) { overlayer.setOverlayPosition(Overlay.Position.BACKGROUND); } else if (position.equals("foreground")) { overlayer.setOverlayPosition(Overlay.Position.FOREGROUND); } int j = 0; for (int i = 0; i < pagecount; i++) { overlayer.setDefaultOverlayPDF(overlay_pdf.get(i)); overlayer.setInputPDF(base_pdf.get(i)); PDDocument overlayed_as_doc = overlayer.overlay(new HashMap<Integer, String>()); PDPage overlayed_page = overlayed_as_doc.getPage(0); output_pdf.addPage(overlayed_page); j = i+1; if (i == 0) { System.out.println("done 1 page"); Thread.sleep(100); } else { System.out.println("done " + j + " pages"); Thread.sleep(100); } } System.out.println("overlayed all pages (" + j + ")"); Thread.sleep(100); overlayer.close(); } public static void main(String[] args) throws IOException, InterruptedException { String project_root = System.getProperty("user.dir"); // where the app is started from; NOT where the controller file is and NOT where this file is // System.out.println(project_root); String transform_option = args[0]; // System.out.println(transform_option); String filename = args[1]; // System.out.println(filename); // load original pdf to be the background overlay File file = new File(project_root + "/data/" + filename + "_in.pdf"); PDDocument background_pdf = PDDocument.load(file); // load dark mode transformed pdf (will be middle layer) file = new File(project_root + "/data/" + filename + "_temp.pdf"); PDDocument middle_pdf = PDDocument.load(file); // load text-stripped pdf to be the foreground overlay file = new File(project_root + "/data/" + filename + "_no_text.pdf"); PDDocument foreground_pdf = PDDocument.load(file); // split each pdf into its own list of PDDocument Splitter splitter = new Splitter(); List<PDDocument> split_b = splitter.split(background_pdf); List<PDDocument> split_m = splitter.split(middle_pdf); List<PDDocument> split_f = splitter.split(foreground_pdf); // get pagecount int pagecount = split_m.size(); if (!(split_b.size() == split_m.size() && split_m.size() == split_f.size())) { System.err.println("warning: pdfs have different pagecounts"); Thread.sleep(100); } // overlay pages to dark mode transformed pdf pages, then append the aggregate pages to a final pdf PDDocument out_pdf = new PDDocument(); overlay(split_b, "background", pagecount, split_m, out_pdf); if (transform_option.equals("no_ocr_dark_retain_img_colors")) { List<PDDocument> split_o = splitter.split(out_pdf); out_pdf = new PDDocument(); overlay(split_f, "foreground", pagecount, split_o, out_pdf); } // save final pdf System.out.println("creating output pdf"); Thread.sleep(100); out_pdf.save(project_root + "/data/" + filename + "_out.pdf"); System.out.println("created output pdf"); Thread.sleep(100); // close in-memory representations background_pdf.close(); middle_pdf.close(); foreground_pdf.close(); out_pdf.close(); } } <|start_filename|>package.json<|end_filename|> { "author": "j9108c", "name": "dark-mode-pdf", "repository": "github:j9108c/dark-mode-pdf", "license": "MIT", "main": "./controller/server.js", "scripts": { "dev": "nodemon ./controller/server.js", "prod_start": "pm2 start ./controller/server.js --interpreter node --name dark-mode-pdf", "prod_restart": "pm2 restart ./controller/server.js", "prod_stop": "pm2 stop ./controller/server.js" }, "devDependencies": { "nodemon": "^2.0.7" }, "nodemonConfig": { "ignore": [ "./data/" ] }, "dependencies": { "express": "^4.17.1", "express-fileupload": "^1.2.1", "express-handlebars": "^4.0.6", "pg": "^8.6.0", "socket.io": "^4.1.2", "socket.io-client": "^4.1.2" } }
j9108c/dark-mode-pdf
<|start_filename|>library/src/main/java/com/crazypumpkin/versatilerecyclerview/library/Util.java<|end_filename|> package com.crazypumpkin.versatilerecyclerview.library; import android.content.res.Resources; /** * 常用函数 * Created by CrazyPumPkin on 2016/12/3. */ public class Util { /** * dp转px * @param dp */ public static int dp2px(float dp){ return (int) (dp * Resources.getSystem().getDisplayMetrics().density + 0.5f); } /** * sp转px * @param sp * @return */ public static int sp2px(float sp){ return (int) (sp * Resources.getSystem().getDisplayMetrics().scaledDensity + 0.5f); } } <|start_filename|>app/src/main/java/com/crazypumpkin/versatilerecyclerview/Util.java<|end_filename|> package com.crazypumpkin.versatilerecyclerview; import android.content.Context; import java.io.IOException; import java.io.InputStream; /** * Created by CrazyPumPkin on 2016/12/13. */ public class Util { /** * 从assets下读取文本 * @param context * @param fileName * @return */ public static String getTextFromAssets(Context context, String fileName){ String result = ""; try { InputStream is = context.getAssets().open(fileName); byte[] buffer = new byte[is.available()]; is.read(buffer); result = new String(buffer,"utf-8"); is.close(); } catch (IOException e) { e.printStackTrace(); } return result; } } <|start_filename|>app/src/main/java/com/crazypumpkin/versatilerecyclerview/MainActivity.java<|end_filename|> package com.crazypumpkin.versatilerecyclerview; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Toast; import com.crazypumpkin.versatilerecyclerview.citypicker.CityPicker; public class MainActivity extends AppCompatActivity { private CityPicker mCityPicker; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void onClick(View v) { switch (v.getId()) { case R.id.btn_wheelview: if (mCityPicker == null) { mCityPicker = new CityPicker(this, findViewById(R.id.rl_container)) .setOnCitySelectListener(new CityPicker.OnCitySelectListener() { @Override public void onCitySelect(String province, String city, String county) { Toast.makeText(MainActivity.this, province + city + county, Toast.LENGTH_SHORT).show(); } }); } mCityPicker.show(); break; } } } <|start_filename|>app/src/main/java/com/crazypumpkin/versatilerecyclerview/citypicker/Province.java<|end_filename|> package com.crazypumpkin.versatilerecyclerview.citypicker; import java.util.ArrayList; import java.util.List; /** * 省 * Created by CrazyPumPkin on 2016/12/13. */ public class Province { private String areaName; private List<City> cities = new ArrayList<>(); public String getAreaName() { return areaName; } public void setAreaName(String areaName) { this.areaName = areaName; } public List<City> getCities() { return cities; } public void setCities(List<City> cities) { this.cities = cities; } } <|start_filename|>app/src/main/java/com/crazypumpkin/versatilerecyclerview/citypicker/CityPicker.java<|end_filename|> package com.crazypumpkin.versatilerecyclerview.citypicker; import android.app.Activity; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.PopupWindow; import com.crazypumpkin.versatilerecyclerview.R; import com.crazypumpkin.versatilerecyclerview.Util; import com.crazypumpkin.versatilerecyclerview.library.WheelRecyclerView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.util.ArrayList; import java.util.List; /** * 城市选择器 * Created by CrazyPumPkin on 2016/12/5. */ public class CityPicker implements PopupWindow.OnDismissListener, View.OnClickListener { private OnCitySelectListener mOnCitySelectListener; private PopupWindow mPickerWindow; private View mParent; private WheelRecyclerView mProvinceWheel; private WheelRecyclerView mCityWheel; private WheelRecyclerView mCountyWheel; private Activity mContext; private List<Province> mDatas; public CityPicker(Activity context, View parent) { mContext = context; mParent = parent; //初始化选择器 View pickerView = LayoutInflater.from(context).inflate(R.layout.city_picker, null); mProvinceWheel = (WheelRecyclerView) pickerView.findViewById(R.id.wheel_province); mCityWheel = (WheelRecyclerView) pickerView.findViewById(R.id.wheel_city); mCountyWheel = (WheelRecyclerView) pickerView.findViewById(R.id.wheel_county); pickerView.findViewById(R.id.tv_exit).setOnClickListener(this); pickerView.findViewById(R.id.tv_ok).setOnClickListener(this); mPickerWindow = new PopupWindow(pickerView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true); mPickerWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE)); mPickerWindow.setFocusable(true); mPickerWindow.setAnimationStyle(R.style.CityPickerAnim); mPickerWindow.setOnDismissListener(this); initData(); } /** * 初始化城市数据 */ private void initData() { mDatas = new Gson().fromJson(Util.getTextFromAssets(mContext, "city.json"), new TypeToken<List<Province>>() { }.getType()); mProvinceWheel.setData(getProvinceNames()); mCityWheel.setData(getCityNames(0)); mCountyWheel.setData(getCountyNames(0, 0)); mProvinceWheel.setOnSelectListener(new WheelRecyclerView.OnSelectListener() { @Override public void onSelect(int position, String data) { onProvinceWheelRoll(position); } }); mCityWheel.setOnSelectListener(new WheelRecyclerView.OnSelectListener() { @Override public void onSelect(int position, String data) { onCityWheelRoll(position); } }); } private void onProvinceWheelRoll(int position) { mCityWheel.setData(getCityNames(position)); mCountyWheel.setData(getCountyNames(position, 0)); } private void onCityWheelRoll(int position) { mCountyWheel.setData(getCountyNames(mProvinceWheel.getSelected(), position)); } /** * 获取省份名称列表 * * @return */ private List<String> getProvinceNames() { List<String> provinces = new ArrayList<>(); for (Province province : mDatas) { provinces.add(province.getAreaName()); } return provinces; } /** * 获取某个省份的城市名称列表 * * @param provincePos * @return */ private List<String> getCityNames(int provincePos) { List<String> cities = new ArrayList<>(); for (City city : mDatas.get(provincePos).getCities()) { cities.add(city.getAreaName()); } return cities; } /** * 获取某个城市的县级区域名称列表 * * @param provincePos * @param cityPos * @return */ private List<String> getCountyNames(int provincePos, int cityPos) { List<String> counties = new ArrayList<>(); if (mDatas.get(provincePos).getCities().size() > 0) { for (County county : mDatas.get(provincePos).getCities().get(cityPos).getCounties()) { counties.add(county.getAreaName()); } } return counties; } /** * 弹出Window时使背景变暗 * * @param alpha */ private void backgroundAlpha(float alpha) { Window window = mContext.getWindow(); WindowManager.LayoutParams lp = window.getAttributes(); lp.alpha = alpha; window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); window.setAttributes(lp); } public CityPicker setOnCitySelectListener(OnCitySelectListener listener) { mOnCitySelectListener = listener; return this; } public void show() { backgroundAlpha(0.5f); mPickerWindow.showAtLocation(mParent, Gravity.BOTTOM, 0, 0); } @Override public void onDismiss() { backgroundAlpha(1f); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.tv_ok: if (mOnCitySelectListener != null) { Province province = mDatas.get(mProvinceWheel.getSelected()); City city = province.getCities().size() > 0 ? province.getCities().get(mCityWheel.getSelected()) : null; String provinceName = province.getAreaName(); String cityName = city == null ? "" : city.getAreaName(); String countyName = city == null ? "" : city.getCounties().get(mCountyWheel.getSelected()).getAreaName(); mOnCitySelectListener.onCitySelect(provinceName, cityName, countyName); mPickerWindow.dismiss(); } break; case R.id.tv_exit: mPickerWindow.dismiss(); break; } } public interface OnCitySelectListener { void onCitySelect(String province, String city, String county); } } <|start_filename|>library/src/main/java/com/crazypumpkin/versatilerecyclerview/library/WheelRecyclerView.java<|end_filename|> package com.crazypumpkin.versatilerecyclerview.library; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; import java.util.List; /** * 滚轮控件的RecyclerView版本 * Created by CrazyPumPkin on 2016/12/3. */ public class WheelRecyclerView extends RecyclerView { //默认参数 private final int DEFAULT_WIDTH = Util.dp2px(160); private final int DEFAULT_ITEM_HEIGHT = Util.dp2px(50); private final int DEFAULT_SELECT_TEXT_COLOR = Color.parseColor("#3396FF"); private final int DEFAULT_UNSELECT_TEXT_COLOR = getResources().getColor(R.color.text_black); private final int DEFAULT_SELECT_TEXT_SIZE = Util.sp2px(14); private final int DEFAULT_UNSELECT_TEXT_SIZE = Util.sp2px(14); private final int DEFAULT_OFFSET = 1; private final int DEFAULT_DIVIDER_WIDTH = ViewGroup.LayoutParams.MATCH_PARENT; private final int DEFAULT_DIVIDER_HEIGHT = Util.dp2px(1); private final int DEFAULT_DIVIVER_COLOR = Color.parseColor("#E4F1FF"); private WheelAdapter mAdapter; private LinearLayoutManager mLayoutManager; private List<String> mDatas; //数据 private int mItemHeight; //选项高度 private int mOffset; //处于中间的item为选中,在头尾需补充 offset个空白view,可显示的item数量=2*offset+1 private int mSelectTextColor; //选中item的文本颜色 private int mUnselectTextColor; //非选中item的文本颜色 private float mSelectTextSize; //选中item的文本大小 private float mUnselectTextSize;//非选中item的文本大小 private float mDividerWidth;//分割线的宽度 private float mDividerHeight;//分割线高度 private int mDividerColor;//分割线颜色 private Paint mPaint;//绘制分割线的paint private OnSelectListener mOnSelectListener; private int mSelected; public WheelRecyclerView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.WheelRecyclerView); mItemHeight = (int) ta.getDimension(R.styleable.WheelRecyclerView_itemHeight, DEFAULT_ITEM_HEIGHT); mSelectTextColor = ta.getColor(R.styleable.WheelRecyclerView_selectTextColor, DEFAULT_SELECT_TEXT_COLOR); mUnselectTextColor = ta.getColor(R.styleable.WheelRecyclerView_unselectTextColor, DEFAULT_UNSELECT_TEXT_COLOR); mSelectTextSize = ta.getDimension(R.styleable.WheelRecyclerView_selectTextSize, DEFAULT_SELECT_TEXT_SIZE); mUnselectTextSize = ta.getDimension(R.styleable.WheelRecyclerView_unselectTextSize, DEFAULT_UNSELECT_TEXT_SIZE); mOffset = ta.getInteger(R.styleable.WheelRecyclerView_wheelOffset, DEFAULT_OFFSET); mDividerWidth = ta.getDimension(R.styleable.WheelRecyclerView_dividerWidth, DEFAULT_DIVIDER_WIDTH); mDividerHeight = ta.getDimension(R.styleable.WheelRecyclerView_dividerHeight, DEFAULT_DIVIDER_HEIGHT); mDividerColor = ta.getColor(R.styleable.WheelRecyclerView_dividerColor, DEFAULT_DIVIVER_COLOR); ta.recycle(); mDatas = new ArrayList<>(); mPaint = new Paint(); mPaint.setColor(mDividerColor); mPaint.setStrokeWidth(mDividerHeight); init(); } private void init() { mLayoutManager = new LinearLayoutManager(getContext()); setLayoutManager(mLayoutManager); if (mDividerColor != Color.TRANSPARENT && mDividerHeight != 0 && mDividerWidth != 0) { addItemDecoration(new DividerItemDecoration()); } mAdapter = new WheelAdapter(); setAdapter(mAdapter); addOnScrollListener(new OnWheelScrollListener()); } @Override protected void onMeasure(int widthSpec, int heightSpec) { int width; int height; int heightSpecSize = MeasureSpec.getSize(heightSpec); int heightSpecMode = MeasureSpec.getMode(heightSpec); //当指定了控件高度时,每个item平分整个高度,控件无指定高度时,默认高度为可视item的累加高度 switch (heightSpecMode) { case MeasureSpec.EXACTLY: height = heightSpecSize; mItemHeight = height / (mOffset * 2 + 1); break; default: height = (mOffset * 2 + 1) * mItemHeight; break; } width = getDefaultSize(DEFAULT_WIDTH, widthSpec); if (mDividerWidth == DEFAULT_DIVIDER_WIDTH) { mDividerWidth = width; } setMeasuredDimension(width, height); } public void setData(List<String> datas) { if (datas == null) { return; } mDatas.clear(); mDatas.addAll(datas); mAdapter.notifyDataSetChanged(); setSelect(0); scrollTo(0,0); } public void setOnSelectListener(OnSelectListener listener) { mOnSelectListener = listener; } public void setSelect(int position) { mSelected = position; mLayoutManager.scrollToPosition(mSelected); } public int getSelected() { return mSelected; } private class WheelAdapter extends Adapter<WheelAdapter.WheelHolder> { @Override public WheelHolder onCreateViewHolder(ViewGroup parent, int viewType) { WheelHolder holder = new WheelHolder(LayoutInflater.from(getContext()).inflate(R.layout.item_wheel, parent, false)); holder.name.getLayoutParams().height = mItemHeight; return holder; } @Override public int getItemCount() { return mDatas.size() == 0 ? 0 : mDatas.size() + mOffset * 2; } @Override public void onBindViewHolder(WheelHolder holder, int position) { //头尾填充offset个空白view以使数据能处于中间选中状态 if (position < mOffset || position > mDatas.size() + mOffset - 1) { holder.name.setText(""); } else { holder.name.setText(mDatas.get(position - mOffset)); } } class WheelHolder extends ViewHolder { TextView name; public WheelHolder(View itemView) { super(itemView); name = (TextView) itemView.findViewById(R.id.tv_name); } } } private class OnWheelScrollListener extends OnScrollListener { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if (newState == RecyclerView.SCROLL_STATE_IDLE) { //当控件停止滚动时,获取可视范围第一个item的位置,滚动调整控件以使选中的item刚好处于正中间 int firstVisiblePos = mLayoutManager.findFirstVisibleItemPosition(); if (firstVisiblePos == RecyclerView.NO_POSITION) { return; } Rect rect = new Rect(); mLayoutManager.findViewByPosition(firstVisiblePos).getHitRect(rect); if (Math.abs(rect.top) > mItemHeight / 2) { smoothScrollBy(0, rect.bottom); mSelected = firstVisiblePos + 1; } else { smoothScrollBy(0, rect.top); mSelected = firstVisiblePos; } if (mOnSelectListener != null) { mOnSelectListener.onSelect(mSelected, mDatas.get(mSelected)); } } } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); setSelectedItem(); } } private void setSelectedItem(){ //获取可视范围的第一个控件的位置 int firstVisiblePos = mLayoutManager.findFirstVisibleItemPosition(); if (firstVisiblePos == RecyclerView.NO_POSITION) { return; } Rect rect = new Rect(); mLayoutManager.findViewByPosition(firstVisiblePos).getHitRect(rect); //被选中item是否已经滑动超出中间区域 boolean overScroll = Math.abs(rect.top) > mItemHeight / 2 ? true : false; //更新可视范围内所有item的样式 for (int i = 0; i < 1 + mOffset * 2; i++) { TextView item; if (overScroll) { item = (TextView) mLayoutManager.findViewByPosition(firstVisiblePos + i + 1); } else { item = (TextView) mLayoutManager.findViewByPosition(firstVisiblePos + i); } if (i == mOffset) { item.setTextColor(mSelectTextColor); item.setTextSize(TypedValue.COMPLEX_UNIT_PX, mSelectTextSize); } else { item.setTextColor(mUnselectTextColor); item.setTextSize(TypedValue.COMPLEX_UNIT_PX, mUnselectTextSize); } } } private class DividerItemDecoration extends ItemDecoration { @Override public void onDrawOver(Canvas c, RecyclerView parent, State state) { //绘制分割线 float startX = getMeasuredWidth() / 2 - mDividerWidth / 2; float topY = mItemHeight * mOffset; float endX = getMeasuredWidth() / 2 + mDividerWidth / 2; float bottomY = mItemHeight * (mOffset + 1); c.drawLine(startX, topY, endX, topY, mPaint); c.drawLine(startX, bottomY, endX, bottomY, mPaint); } } public interface OnSelectListener { void onSelect(int position, String data); } } <|start_filename|>app/src/main/java/com/crazypumpkin/versatilerecyclerview/citypicker/County.java<|end_filename|> package com.crazypumpkin.versatilerecyclerview.citypicker; /** * 县级区域 * Created by CrazyPumPkin on 2016/12/13. */ public class County { private String areaName; public String getAreaName() { return areaName; } public void setAreaName(String areaName) { this.areaName = areaName; } } <|start_filename|>app/src/main/java/com/crazypumpkin/versatilerecyclerview/citypicker/City.java<|end_filename|> package com.crazypumpkin.versatilerecyclerview.citypicker; import java.util.ArrayList; import java.util.List; /** * 城市 * Created by CrazyPumPkin on 2016/12/13. */ public class City { private String areaName; private List<County> counties = new ArrayList<>(); public String getAreaName() { return areaName; } public void setAreaName(String areaName) { this.areaName = areaName; } public List<County> getCounties() { return counties; } public void setCounties(List<County> counties) { this.counties = counties; } }
CrazyPumPkin/VersatileRecyclerView
<|start_filename|>iso8211.go<|end_filename|> // Copyright 2015 <NAME> <<EMAIL>>. All rights reserved. // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. // Package iso8211 implements ISO 8211 parsing. // It is targeted to NOAA IHO S-57 format vector chart files. // // ISO 8211 is one of those baroque 1990's era binary file formats. // file: LeadRecord, DataRecord... // Record : Header, data // LeadRecord : Header, FieldType... // DataRecord : Header, Field... // FieldType : FieldHeader, SubField tags and formats // Field : SubFields // // References: // http://www.iho.int/iho_pubs/standard/S-57Ed3.1/31Main.pdf // http://sourceforge.net/projects/py-iso8211/ // https://www.iso.org/obp/ui/#iso:std:iso-iec:8211:ed-2:v1:en // http://mcmcweb.er.usgs.gov/sdts/SDTS_standard_nov97/p3body.html // http://www.charts.noaa.gov/ENCs/ENCs.shtml package iso8211 import ( "bytes" "encoding/binary" "errors" "io" "reflect" "regexp" "strconv" ) // RawHeader is a convenience for directly loading the on-disk // binary Header format. type RawHeader struct { RecordLength [5]byte InterchangeLevel byte LeaderID byte InLineCode byte Version byte ApplicationIndicator byte FieldControlLength [2]byte BaseAddress [5]byte ExtendedCharacterSetIndicator [3]byte SizeOfFieldLength byte SizeOfFieldPosition byte Reserved byte SizeOfFieldTag byte } // DirEntry describes each following Field type DirEntry struct { Tag []byte Length int Position int } // Header holds the overall layout for a Record. type Header struct { RecordLength uint64 InterchangeLevel byte LeaderID byte InLineCode byte Version byte ApplicationIndicator byte FieldControlLength uint64 BaseAddress uint64 ExtendedCharacterSetIndicator []byte LengthSize, PositionSize, TagSize int8 Entries []DirEntry } // LeadRecord is the first Record in a file. It has metadata for each // Field in the file. type LeadRecord struct { Header Header FieldTypes map[string]FieldType } // Field is a field within a data record, it holds an array of values // called SubFields. type Field struct { Tag string Length int Position int FieldType FieldType SubFields []interface{} } // DataRecord contains data for a set of Fields and their SubFields. type DataRecord struct { Header Header Lead *LeadRecord Fields []Field } // RawFieldHeader is a convenience for loading the on-disk binary FieldType // header. type RawFieldHeader struct { DataStructure byte DataType byte AuxiliaryControls [2]byte PrintableFt byte PrintableUt byte EscapeSeq [3]byte } // SubFieldType holds the Go type, size and tag for each SubField. type SubFieldType struct { Kind reflect.Kind Size int Tag []byte } // FieldType holds the metadata describing fields and subfields. type FieldType struct { Tag string Length int Position int DataStructure byte DataType byte AuxiliaryControls []byte PrintableFt byte PrintableUt byte EscapeSeq []byte Name []byte ArrayDescriptor []byte FormatControls []byte SubFields []SubFieldType } // Read loads a binary format RawHeader and its DirEntries into // the Header model. func (header *Header) Read(file io.Reader) error { var err error var ddr RawHeader ddrSize := uint64(binary.Size(ddr)) // Read the header err = binary.Read(file, binary.LittleEndian, &ddr) if err != nil { return err } header.RecordLength, _ = strconv.ParseUint(string(ddr.RecordLength[:]), 10, 64) header.InterchangeLevel = ddr.InterchangeLevel header.LeaderID = ddr.LeaderID header.InLineCode = ddr.InLineCode header.Version = ddr.Version header.ApplicationIndicator = ddr.ApplicationIndicator header.FieldControlLength, _ = strconv.ParseUint(string(ddr.FieldControlLength[:]), 10, 64) header.BaseAddress, _ = strconv.ParseUint(string(ddr.BaseAddress[:]), 10, 64) header.ExtendedCharacterSetIndicator = ddr.ExtendedCharacterSetIndicator[:] header.LengthSize = int8(ddr.SizeOfFieldLength - '0') header.PositionSize = int8(ddr.SizeOfFieldPosition - '0') header.TagSize = int8(ddr.SizeOfFieldTag - '0') // Read the directory entries := (header.BaseAddress - 1 - ddrSize) / uint64(header.LengthSize+header.PositionSize+header.TagSize) header.Entries = make([]DirEntry, entries) dir := make([]byte, header.BaseAddress-ddrSize) file.Read(dir) buf := bytes.NewBuffer(dir) for idx := uint64(0); idx < entries; idx++ { header.Entries[idx].Tag = buf.Next(int(header.TagSize)) header.Entries[idx].Length, _ = strconv.Atoi(string(buf.Next(int(header.LengthSize))[:])) header.Entries[idx].Position, _ = strconv.Atoi(string(buf.Next(int(header.PositionSize))[:])) } return err } // Read loads the LeadRecord Header and the FieldTypes func (lead *LeadRecord) Read(file io.Reader) error { var err error err = lead.Header.Read(file) if err != nil { return err } if lead.Header.LeaderID != 'L' { return errors.New("record is not a Lead record") } err = lead.ReadFields(file) return err } func (lead *LeadRecord) ReadFields(file io.Reader) error { var err error lead.FieldTypes = make(map[string]FieldType, len(lead.Header.Entries)) for _, d := range lead.Header.Entries { field := FieldType{Tag: string(d.Tag), Length: d.Length, Position: d.Position} field.Read(file) lead.FieldTypes[field.Tag] = field } return err } func (field *Field) Read(file io.Reader) error { var err error data := make([]byte, field.Length) file.Read(data) if field.FieldType.Tag != "" { field.SubFields = field.FieldType.Decode(data[:field.Length-1]) } return err } func (data *DataRecord) Read(file io.Reader) error { var err error err = data.Header.Read(file) if err != nil { return err } if data.Header.LeaderID != 'D' { return errors.New("record is not a Data record") } err = data.ReadFields(file) return err } func (data *DataRecord) ReadFields(file io.Reader) error { var err error data.Fields = make([]Field, len(data.Header.Entries)) for i, d := range data.Header.Entries { field := Field{Tag: string(d.Tag), Length: d.Length, Position: d.Position} if data.Lead != nil { field.FieldType = data.Lead.FieldTypes[field.Tag] } err = field.Read(file) data.Fields[i] = field } return err } func (dir *FieldType) Read(file io.Reader) error { var field RawFieldHeader err := binary.Read(file, binary.LittleEndian, &field) dir.DataStructure = field.DataStructure dir.DataType = field.DataType dir.AuxiliaryControls = field.AuxiliaryControls[:] dir.PrintableFt = field.PrintableFt dir.PrintableUt = field.PrintableUt dir.EscapeSeq = field.EscapeSeq[:] fdata := make([]byte, dir.Length-9) file.Read(fdata) desc := bytes.Split(fdata[:dir.Length-10], []byte{'\x1f'}) dir.Name = desc[0] dir.ArrayDescriptor = desc[1] if len(desc) > 2 { dir.FormatControls = desc[2] } return err } /* Format parses the ISO-8211 format controls and array descriptors. Based on Section 7.2.2.1 of the IHO S-57 Publication. http://www.iho.int/iho_pubs/standard/S-57Ed3.1/31Main.pdf Array Descriptor and Format Controls. The array descriptor is a ! separated list of tags describing the data field. If it begins with a * the tag list is repeated. The format controls decribe the format of the data for each tag. eg: Descriptor AGEN!FIDN!FIDS , Format (b12,b14,b12) is three binary encoded integers. AGEN is an int16, FIDN an int32 and FIDS an int16. The 'b' indicates binary int, '1' indicates unsigned, the second digit indicates the number of bytes. Decriptor *YCOO!XCOO, Format (2b24) is two binary encoded integers. Both are int32s, the '2' after the 'b' indicates signed. The * in the descriptor indicates that pair is repeated to fill the data field. */ func (dir *FieldType) Format() []SubFieldType { if dir.SubFields != nil { return dir.SubFields } var re = regexp.MustCompile(`(\d*)(\w+)\(*(\d*)\)*`) if len(dir.FormatControls) > 2 { Tags := bytes.Split(dir.ArrayDescriptor, []byte{'!'}) Tagidx := 0 types := make([]SubFieldType, len(Tags)) for _, a := range re.FindAllSubmatch(dir.FormatControls, -1) { i := 1 if len(a[1]) > 0 { i, _ = strconv.Atoi(string(a[1])) } var size int if len(a[3]) > 0 { size, _ = strconv.Atoi(string(a[3])) } for ; i > 0; i-- { switch a[2][0] { case 'A': types[Tagidx] = SubFieldType{reflect.String, size, Tags[Tagidx]} case 'I': types[Tagidx] = SubFieldType{reflect.String, size, Tags[Tagidx]} case 'R': types[Tagidx] = SubFieldType{reflect.String, size, Tags[Tagidx]} case 'B': types[Tagidx] = SubFieldType{reflect.Array, size / 8, Tags[Tagidx]} case 'b': switch string(a[2][1:]) { case "11": types[Tagidx] = SubFieldType{reflect.Uint8, 1, Tags[Tagidx]} case "12": types[Tagidx] = SubFieldType{reflect.Uint16, 2, Tags[Tagidx]} case "14": types[Tagidx] = SubFieldType{reflect.Uint32, 4, Tags[Tagidx]} case "21": types[Tagidx] = SubFieldType{reflect.Int8, 1, Tags[Tagidx]} case "22": types[Tagidx] = SubFieldType{reflect.Int16, 2, Tags[Tagidx]} case "24": types[Tagidx] = SubFieldType{reflect.Int32, 4, Tags[Tagidx]} } } Tagidx++ } } dir.SubFields = types } return dir.SubFields } // Decode uses the FieldType Format to convert the binary file format // SubFields into an array of Go data types. func (dir FieldType) Decode(buffer []byte) []interface{} { buf := bytes.NewBuffer(buffer) var values []interface{} for buf.Len() > 0 { for _, ftype := range dir.Format() { switch ftype.Kind { case reflect.Uint8: { var v uint8 binary.Read(buf, binary.LittleEndian, &v) values = append(values, v) } case reflect.Uint16: { var v uint16 binary.Read(buf, binary.LittleEndian, &v) values = append(values, v) } case reflect.Uint32: { var v uint32 binary.Read(buf, binary.LittleEndian, &v) values = append(values, v) } case reflect.Int8: { var v int8 binary.Read(buf, binary.LittleEndian, &v) values = append(values, v) } case reflect.Int16: { var v int16 binary.Read(buf, binary.LittleEndian, &v) values = append(values, v) } case reflect.Int32: { var v int32 binary.Read(buf, binary.LittleEndian, &v) values = append(values, v) } default: { if ftype.Size == 0 { i, _ := buf.ReadString('\x1f') if len(i) > 0 { values = append(values, i[:len(i)-1]) } else { values = append(values, "") } } else { i := buf.Next(ftype.Size) values = append(values, string(i)) } } } } } return values } <|start_filename|>iso8211_test.go<|end_filename|> // Copyright 2015 <NAME> <<EMAIL>>. All rights reserved. // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file. package iso8211 import ( "fmt" "os" "reflect" "testing" ) func TestFieldTypeFormat(t *testing.T) { var f FieldType f.FormatControls = []byte("(A)") v := f.Format() e := SubFieldType{reflect.String, 0, nil} if len(v) != 1 || !reflect.DeepEqual(v[0], e) { t.Error("Expected ", e, ", got ", v) } var f2 FieldType f2.FormatControls = []byte("(b11,2b24,A(3),B(40))") f2.ArrayDescriptor = []byte("A!B!C!D!E") v = f2.Format() a := []SubFieldType{ {reflect.Uint8, 1, []byte{'A'}}, {reflect.Int32, 4, []byte{'B'}}, {reflect.Int32, 4, []byte{'C'}}, {reflect.String, 3, []byte{'D'}}, {reflect.Array, 5, []byte{'E'}}} if len(v) != len(a) { t.Error("Format did not return the expected number of values") } else { for i, o := range v { if !reflect.DeepEqual(o, a[i]) { t.Error("At ", i, " Expected ", a[i], ", got ", o) } } } } func TestS57File(t *testing.T) { f, err := os.Open("testdata/US5MD12M.001") if err != nil { t.Error("Unexpected error: ", err) } defer f.Close() var l LeadRecord if l.Read(f) != nil { t.Error("Error reading the lead record") } var d DataRecord d.Lead = &l if d.Read(f) != nil { t.Error("Error reading Data record 1") } if len(d.Fields) != 3 && d.Fields[0].SubFields[0] != 1 { t.Error("Data record 1 is not what we expected.") } if d.Read(f) != nil { t.Error("Error reading Data record 2") } if len(d.Fields) != 4 && d.Fields[0].SubFields[0] != 2 { t.Error("Data record 2 is not what we expected.") } if len(d.Fields[3].SubFields) != 6 && d.Fields[3].SubFields[4] != 148 { t.Error("Data record 2, Field 4 is not what we expected.", d.Fields[3]) } if d.Read(f) == nil { t.Error("Should be at EOF") } } func Example() { f, err := os.Open("testdata/US5MD12M.001") if err != nil { fmt.Println("No file. ", err) } var l LeadRecord l.Read(f) var d DataRecord d.Lead = &l for d.Read(f) == nil { fmt.Printf("Rec: %d\n", d.Fields[0].SubFields[0]) } // Output: // Rec: 1 // Rec: 2 }
wangxmdw/iso8211
<|start_filename|>package.json<|end_filename|> { "name": "gh-find-current-pr", "version": "1.2.0", "description": "GitHub Action for finding the Pull Request (PR) associated with the current SHA.", "main": "main.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/jwalton/gh-find-current-pr.git" }, "keywords": [ "github", "actions", "github actions", "pull request", "PR" ], "author": "<NAME>", "license": "MIT", "bugs": { "url": "https://github.com/jwalton/gh-find-current-pr/issues" }, "homepage": "https://github.com/jwalton/gh-find-current-pr#readme", "dependencies": { "@actions/core": "^1.3.0", "@actions/github": "^5.0.0" } }
mvarrieur/gh-find-current-pr
<|start_filename|>CIE.AspNetCore.Authentication/CIE.AspNetCore.WebApp/Views/Home/LoggedOut.cshtml<|end_filename|> @{ ViewData["Title"] = "Logged out "; } <h1>@ViewData["Title"]</h1> <p>Hey whoever you were, why did you logout?</p> <|start_filename|>CIE.AspNetCore.Authentication/CIE.AspNetCore.WebApp/Views/Home/LoggedIn.cshtml<|end_filename|> @{ ViewData["Title"] = "Logged in"; } <h1>@ViewData["Title"]</h1> <p>Hey @User.Identity.Name you are loggedin</p>
AndreaPetrelli/cie-aspnetcore
<|start_filename|>lib/index.js<|end_filename|> "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = autoAsyncWrap; var _expressAsyncWrap = _interopRequireDefault(require("express-async-wrap")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function autoAsyncWrap(route) { const stack = route.stack; for (const layer of stack) { if (layer.route) { autoAsyncWrap(layer.route); } else { if (layer.handle.stack) { autoAsyncWrap(layer.handle); } else { if (layer.handle[Symbol.toStringTag] === 'AsyncFunction') { layer.handle = (0, _expressAsyncWrap.default)(layer.handle); } } } } } <|start_filename|>src/index.js<|end_filename|> import wrap from 'express-async-wrap' export default function autoAsyncWrap(route) { const stack = route.stack for (const layer of stack) { if (layer.route) { autoAsyncWrap(layer.route) } else { if (layer.handle.stack) { autoAsyncWrap(layer.handle) } else { if (layer.handle[Symbol.toStringTag] === 'AsyncFunction') { layer.handle = wrap(layer.handle) } } } } }
naver/auto-async-wrap
<|start_filename|>basic/lesson3/verilator/sim/vinc/verilated_sc.h<|end_filename|> // -*- mode: C++; c-file-style: "cc-mode" -*- //************************************************************************* // // Copyright 2009-2020 by <NAME>. This program is free software; you can // redistribute it and/or modify it under the terms of either the GNU // Lesser General Public License Version 3 or the Perl Artistic License. // Version 2.0. // // Verilator is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // //************************************************************************* /// /// \file /// \brief Verilator: Common include for all Verilated SystemC files /// /// This file is included automatically by Verilator at the top of /// all SystemC files it generates. /// /// Code available from: https://verilator.org /// //************************************************************************* #ifndef _VERILATED_SC_H_ #define _VERILATED_SC_H_ 1 ///< Header Guard #include "verilatedos.h" #include "systemc.h" //============================================================================= // VL_SC_BV_DATAP // We want to get a pointer to m_data in the sc_bv_base class, // but it is protected. So make an exposing class, then use // cast magic to get at it. Saves patching get_datap in SystemC. // This class is thread safe (though most of SystemC is not). #define VL_SC_BV_DATAP(bv) (VlScBvExposer::sp_datap(bv)) class VlScBvExposer : public sc_bv_base { public: static const vluint32_t* sp_datap(const sc_bv_base& base) VL_MT_SAFE { return static_cast<const VlScBvExposer*>(&base)->sp_datatp(); } const vluint32_t* sp_datatp() const { return reinterpret_cast<vluint32_t*>(m_data); } // Above reads this protected element in sc_bv_base: // sc_digit* m_data; // data array }; //========================================================================= #endif // Guard <|start_filename|>basic/lesson3/verilator/sim/vinc/verilated_fst_c.h<|end_filename|> // -*- mode: C++; c-file-style: "cc-mode" -*- //============================================================================= // // THIS MODULE IS PUBLICLY LICENSED // // Copyright 2001-2020 by <NAME>. This program is free software; // you can redistribute it and/or modify it under the terms of either the GNU // Lesser General Public License Version 3 or the Perl Artistic License Version 2.0. // // This is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // //============================================================================= /// /// \file /// \brief C++ Tracing in FST Format /// //============================================================================= // SPDIFF_OFF #ifndef _VERILATED_FST_C_H_ #define _VERILATED_FST_C_H_ 1 #include "verilatedos.h" #include "verilated.h" #include "gtkwave/fstapi.h" #include <list> #include <map> #include <string> #include <vector> class VerilatedFst; class VerilatedFstCallInfo; typedef void (*VerilatedFstCallback_t)(VerilatedFst* vcdp, void* userthis, vluint32_t code); //============================================================================= // VerilatedFst /// Base class to create a Verilator FST dump /// This is an internally used class - see VerilatedFstC for what to call from applications class VerilatedFst { typedef std::map<vluint32_t, fstHandle> Code2SymbolType; typedef std::map<int, fstEnumHandle> Local2FstDtype; typedef std::vector<VerilatedFstCallInfo*> CallbackVec; private: void* m_fst; VerilatedAssertOneThread m_assertOne; ///< Assert only called from single thread bool m_fullDump; char m_scopeEscape; std::string m_module; CallbackVec m_callbacks; ///< Routines to perform dumping Code2SymbolType m_code2symbol; Local2FstDtype m_local2fstdtype; std::list<std::string> m_curScope; // CONSTRUCTORS VL_UNCOPYABLE(VerilatedFst); void declSymbol(vluint32_t code, const char* name, int dtypenum, fstVarDir vardir, fstVarType vartype, bool array, int arraynum, vluint32_t len); // helpers std::vector<char> m_valueStrBuffer; public: explicit VerilatedFst(void* fst=NULL); ~VerilatedFst() { if (m_fst == NULL) { fstWriterClose(m_fst); } } bool isOpen() const { return m_fst != NULL; } void open(const char* filename) VL_MT_UNSAFE; void flush() VL_MT_UNSAFE { fstWriterFlushContext(m_fst); } void close() VL_MT_UNSAFE { m_assertOne.check(); fstWriterClose(m_fst); m_fst = NULL; } void set_time_unit(const char* unitp) { fstWriterSetTimescaleFromString(m_fst, unitp); } void set_time_unit(const std::string& unit) { set_time_unit(unit.c_str()); } void set_time_resolution(const char* unitp) { if (unitp) {} } void set_time_resolution(const std::string& unit) { set_time_resolution(unit.c_str()); } // double timescaleToDouble(const char* unitp); // std::string doubleToTimescale(double value); /// Change character that splits scopes. Note whitespace are ALWAYS escapes. void scopeEscape(char flag) { m_scopeEscape = flag; } /// Is this an escape? bool isScopeEscape(char c) { return isspace(c) || c == m_scopeEscape; } /// Inside dumping routines, called each cycle to make the dump void dump(vluint64_t timeui); /// Inside dumping routines, declare callbacks for tracings void addCallback(VerilatedFstCallback_t initcb, VerilatedFstCallback_t fullcb, VerilatedFstCallback_t changecb, void* userthis) VL_MT_UNSAFE_ONE; /// Inside dumping routines, declare a module void module(const std::string& name); /// Inside dumping routines, declare a data type void declDTypeEnum(int dtypenum, const char* name, vluint32_t elements, unsigned int minValbits, const char** itemNamesp, const char** itemValuesp); /// Inside dumping routines, declare a signal void declBit(vluint32_t code, const char* name, int dtypenum, fstVarDir vardir, fstVarType vartype, bool array, int arraynum) { declSymbol(code, name, dtypenum, vardir, vartype, array, arraynum, 1); } void declBus(vluint32_t code, const char* name, int dtypenum, fstVarDir vardir, fstVarType vartype, bool array, int arraynum, int msb, int lsb) { declSymbol(code, name, dtypenum, vardir, vartype, array, arraynum, msb - lsb + 1); } void declDouble(vluint32_t code, const char* name, int dtypenum, fstVarDir vardir, fstVarType vartype, bool array, int arraynum) { declSymbol(code, name, dtypenum, vardir, vartype, array, arraynum, 2); } void declFloat(vluint32_t code, const char* name, int dtypenum, fstVarDir vardir, fstVarType vartype, bool array, int arraynum) { declSymbol(code, name, dtypenum, vardir, vartype, array, arraynum, 1); } void declQuad(vluint32_t code, const char* name, int dtypenum, fstVarDir vardir, fstVarType vartype, bool array, int arraynum, int msb, int lsb) { declSymbol(code, name, dtypenum, vardir, vartype, array, arraynum, msb - lsb + 1); } void declArray(vluint32_t code, const char* name, int dtypenum, fstVarDir vardir, fstVarType vartype, bool array, int arraynum, int msb, int lsb) { declSymbol(code, name, dtypenum, vardir, vartype, array, arraynum, msb - lsb + 1); } /// Inside dumping routines, dump one signal if it has changed void chgBit(vluint32_t code, const vluint32_t newval) { fstWriterEmitValueChange(m_fst, m_code2symbol[code], newval ? "1" : "0"); } void chgBus(vluint32_t code, const vluint32_t newval, int bits) { fstWriterEmitValueChange32(m_fst, m_code2symbol[code], bits, newval); } void chgDouble(vluint32_t code, const double newval) { double val = newval; fstWriterEmitValueChange(m_fst, m_code2symbol[code], &val); } void chgFloat(vluint32_t code, const float newval) { double val = (double)newval; fstWriterEmitValueChange(m_fst, m_code2symbol[code], &val); } void chgQuad(vluint32_t code, const vluint64_t newval, int bits) { fstWriterEmitValueChange64(m_fst, m_code2symbol[code], bits, newval); } void chgArray(vluint32_t code, const vluint32_t* newval, int bits) { fstWriterEmitValueChangeVec32(m_fst, m_code2symbol[code], bits, newval); } void fullBit(vluint32_t code, const vluint32_t newval) { chgBit(code, newval); } void fullBus(vluint32_t code, const vluint32_t newval, int bits) { chgBus(code, newval, bits); } void fullDouble(vluint32_t code, const double newval) { chgDouble(code, newval); } void fullFloat(vluint32_t code, const float newval) { chgFloat(code, newval); } void fullQuad(vluint32_t code, const vluint64_t newval, int bits) { chgQuad(code, newval, bits); } void fullArray(vluint32_t code, const vluint32_t* newval, int bits) { chgArray(code, newval, bits); } void declTriBit (vluint32_t code, const char* name, int arraynum); void declTriBus (vluint32_t code, const char* name, int arraynum, int msb, int lsb); void declTriQuad (vluint32_t code, const char* name, int arraynum, int msb, int lsb); void declTriArray (vluint32_t code, const char* name, int arraynum, int msb, int lsb); void fullTriBit(vluint32_t code, const vluint32_t newval, const vluint32_t newtri); void fullTriBus(vluint32_t code, const vluint32_t newval, const vluint32_t newtri, int bits); void fullTriQuad(vluint32_t code, const vluint64_t newval, const vluint32_t newtri, int bits); void fullTriArray(vluint32_t code, const vluint32_t* newvalp, const vluint32_t* newtrip, int bits); void fullBitX(vluint32_t code); void fullBusX(vluint32_t code, int bits); void fullQuadX(vluint32_t code, int bits); void fullArrayX(vluint32_t code, int bits); void chgTriBit(vluint32_t code, const vluint32_t newval, const vluint32_t newtri); void chgTriBus(vluint32_t code, const vluint32_t newval, const vluint32_t newtri, int bits); void chgTriQuad(vluint32_t code, const vluint64_t newval, const vluint32_t newtri, int bits); void chgTriArray(vluint32_t code, const vluint32_t* newvalp, const vluint32_t* newtrip, int bits); }; //============================================================================= // VerilatedFstC /// Create a FST dump file in C standalone (no SystemC) simulations. /// Also derived for use in SystemC simulations. /// Thread safety: Unless otherwise indicated, every function is VL_MT_UNSAFE_ONE class VerilatedFstC { VerilatedFst m_sptrace; ///< Trace file being created // CONSTRUCTORS VL_UNCOPYABLE(VerilatedFstC); public: explicit VerilatedFstC(void* filep=NULL) : m_sptrace(filep) {} ~VerilatedFstC() {} public: // ACCESSORS /// Is file open? bool isOpen() const { return m_sptrace.isOpen(); } // METHODS /// Open a new FST file void open(const char* filename) VL_MT_UNSAFE_ONE { m_sptrace.open(filename); } /// Close dump void close() VL_MT_UNSAFE_ONE { m_sptrace.close(); } /// Flush dump void flush() VL_MT_UNSAFE_ONE { m_sptrace.flush(); } /// Write one cycle of dump data void dump(vluint64_t timeui) { m_sptrace.dump(timeui); } /// Write one cycle of dump data - backward compatible and to reduce /// conversion warnings. It's better to use a vluint64_t time instead. void dump(double timestamp) { dump(static_cast<vluint64_t>(timestamp)); } void dump(vluint32_t timestamp) { dump(static_cast<vluint64_t>(timestamp)); } void dump(int timestamp) { dump(static_cast<vluint64_t>(timestamp)); } /// Set time units (s/ms, defaults to ns) /// See also VL_TIME_PRECISION, and VL_TIME_MULTIPLIER in verilated.h void set_time_unit(const char* unitp) { m_sptrace.set_time_unit(unitp); } void set_time_unit(const std::string& unit) { set_time_unit(unit.c_str()); } /// Set time resolution (s/ms, defaults to ns) /// See also VL_TIME_PRECISION, and VL_TIME_MULTIPLIER in verilated.h void set_time_resolution(const char* unitp) { m_sptrace.set_time_resolution(unitp); } void set_time_resolution(const std::string& unit) { set_time_resolution(unit.c_str()); } /// Internal class access inline VerilatedFst* spTrace() { return &m_sptrace; }; }; #endif // guard <|start_filename|>basic/lesson3/verilator/sim/vinc/verilated_save.cpp<|end_filename|> // -*- mode: C++; c-file-style: "cc-mode" -*- //============================================================================= // // THIS MODULE IS PUBLICLY LICENSED // // Copyright 2001-2020 by <NAME>. This program is free software; // you can redistribute it and/or modify it under the terms of either the GNU // Lesser General Public License Version 3 or the Perl Artistic License Version 2.0. // // This is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // //============================================================================= /// /// \file /// \brief C++ Tracing in VCD Format /// //============================================================================= #include "verilatedos.h" #include "verilated.h" #include "verilated_save.h" #include <cerrno> #include <fcntl.h> #if defined(_WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__) # include <io.h> #else # include <unistd.h> #endif #ifndef O_LARGEFILE // For example on WIN32 # define O_LARGEFILE 0 #endif #ifndef O_NONBLOCK # define O_NONBLOCK 0 #endif #ifndef O_CLOEXEC # define O_CLOEXEC 0 #endif // CONSTANTS static const char* const VLTSAVE_HEADER_STR = "verilatorsave01\n"; ///< Value of first bytes of each file static const char* const VLTSAVE_TRAILER_STR = "vltsaved"; ///< Value of last bytes of each file //============================================================================= //============================================================================= //============================================================================= // Searalization bool VerilatedDeserialize::readDiffers(const void* __restrict datap, size_t size) VL_MT_UNSAFE_ONE { bufferCheck(); const vluint8_t* __restrict dp = static_cast<const vluint8_t* __restrict>(datap); vluint8_t miss = 0; while (size--) { miss |= (*dp++ ^ *m_cp++); } return (miss!=0); } VerilatedDeserialize& VerilatedDeserialize::readAssert(const void* __restrict datap, size_t size) VL_MT_UNSAFE_ONE { if (VL_UNLIKELY(readDiffers(datap, size))) { std::string fn = filename(); std::string msg = "Can't deserialize save-restore file as was made from different model:" +filename(); VL_FATAL_MT(fn.c_str(), 0, "", msg.c_str()); close(); } return *this; // For function chaining } void VerilatedSerialize::header() VL_MT_UNSAFE_ONE { VerilatedSerialize& os = *this; // So can cut and paste standard << code below assert((strlen(VLTSAVE_HEADER_STR) & 7) == 0); // Keep aligned os.write(VLTSAVE_HEADER_STR, strlen(VLTSAVE_HEADER_STR)); // Verilated doesn't do it itself, as if we're not using save/restore // it doesn't need to compile this stuff in os.write(Verilated::serializedPtr(), Verilated::serializedSize()); } void VerilatedDeserialize::header() VL_MT_UNSAFE_ONE { VerilatedDeserialize& os = *this; // So can cut and paste standard >> code below if (VL_UNLIKELY(os.readDiffers(VLTSAVE_HEADER_STR, strlen(VLTSAVE_HEADER_STR)))) { std::string fn = filename(); std::string msg = std::string("Can't deserialize; file has wrong header signature: ") +filename(); VL_FATAL_MT(fn.c_str(), 0, "", msg.c_str()); close(); } os.read(Verilated::serializedPtr(), Verilated::serializedSize()); } void VerilatedSerialize::trailer() VL_MT_UNSAFE_ONE { VerilatedSerialize& os = *this; // So can cut and paste standard << code below assert((strlen(VLTSAVE_TRAILER_STR) & 7) == 0); // Keep aligned os.write(VLTSAVE_TRAILER_STR, strlen(VLTSAVE_TRAILER_STR)); } void VerilatedDeserialize::trailer() VL_MT_UNSAFE_ONE { VerilatedDeserialize& os = *this; // So can cut and paste standard >> code below if (VL_UNLIKELY(os.readDiffers(VLTSAVE_TRAILER_STR, strlen(VLTSAVE_TRAILER_STR)))) { std::string fn = filename(); std::string msg = std::string("Can't deserialize; file has wrong end-of-file signature: ") +filename(); VL_FATAL_MT(fn.c_str(), 0, "", msg.c_str()); close(); } } //============================================================================= //============================================================================= //============================================================================= // Opening/Closing void VerilatedSave::open(const char* filenamep) VL_MT_UNSAFE_ONE { m_assertOne.check(); if (isOpen()) return; VL_DEBUG_IF(VL_DBG_MSGF("- save: opening save file %s\n", filenamep);); if (filenamep[0]=='|') { assert(0); // Not supported yet. } else { // cppcheck-suppress duplicateExpression m_fd = ::open(filenamep, O_CREAT|O_WRONLY|O_TRUNC|O_LARGEFILE|O_NONBLOCK|O_CLOEXEC , 0666); if (m_fd<0) { // User code can check isOpen() m_isOpen = false; return; } } m_isOpen = true; m_filename = filenamep; m_cp = m_bufp; header(); } void VerilatedRestore::open(const char* filenamep) VL_MT_UNSAFE_ONE { m_assertOne.check(); if (isOpen()) return; VL_DEBUG_IF(VL_DBG_MSGF("- restore: opening restore file %s\n", filenamep);); if (filenamep[0]=='|') { assert(0); // Not supported yet. } else { // cppcheck-suppress duplicateExpression m_fd = ::open(filenamep, O_CREAT|O_RDONLY|O_LARGEFILE|O_CLOEXEC , 0666); if (m_fd<0) { // User code can check isOpen() m_isOpen = false; return; } } m_isOpen = true; m_filename = filenamep; m_cp = m_bufp; m_endp = m_bufp; header(); } void VerilatedSave::close() VL_MT_UNSAFE_ONE { if (!isOpen()) return; trailer(); flush(); m_isOpen = false; ::close(m_fd); // May get error, just ignore it } void VerilatedRestore::close() VL_MT_UNSAFE_ONE { if (!isOpen()) return; trailer(); flush(); m_isOpen = false; ::close(m_fd); // May get error, just ignore it } //============================================================================= // Buffer management void VerilatedSave::flush() VL_MT_UNSAFE_ONE { m_assertOne.check(); if (VL_UNLIKELY(!isOpen())) return; vluint8_t* wp = m_bufp; while (1) { ssize_t remaining = (m_cp - wp); if (remaining==0) break; errno = 0; ssize_t got = ::write(m_fd, wp, remaining); if (got>0) { wp += got; } else if (got < 0) { if (errno != EAGAIN && errno != EINTR) { // write failed, presume error (perhaps out of disk space) std::string msg = std::string(__FUNCTION__)+": "+strerror(errno); VL_FATAL_MT("", 0, "", msg.c_str()); close(); break; } } } m_cp = m_bufp; // Reset buffer } void VerilatedRestore::fill() VL_MT_UNSAFE_ONE { m_assertOne.check(); if (VL_UNLIKELY(!isOpen())) return; // Move remaining characters down to start of buffer. (No memcpy, overlaps allowed) vluint8_t* rp = m_bufp; for (vluint8_t* sp=m_cp; sp < m_endp;) *rp++ = *sp++; // Overlaps m_endp = m_bufp + (m_endp - m_cp); m_cp = m_bufp; // Reset buffer // Read into buffer starting at m_endp while (1) { ssize_t remaining = (m_bufp+bufferSize() - m_endp); if (remaining==0) break; errno = 0; ssize_t got = ::read(m_fd, m_endp, remaining); if (got>0) { m_endp += got; } else if (got < 0) { if (errno != EAGAIN && errno != EINTR) { // write failed, presume error (perhaps out of disk space) std::string msg = std::string(__FUNCTION__)+": "+strerror(errno); VL_FATAL_MT("", 0, "", msg.c_str()); close(); break; } } else { // got==0, EOF // Fill buffer from here to end with NULLs so reader's don't // need to check eof each character. while (m_endp < m_bufp+bufferSize()) *m_endp++ = '\0'; break; } } } //============================================================================= // Serialization of types <|start_filename|>basic/lesson4/boot_rom.c<|end_filename|> // boot_rom.c // Boot ROM for the Z80 system on a chip (SoC) // (c) 2015 <NAME> #include <stdlib.h> // for abs() // draw a pixel // At 160x100 pixel screen size a byte is sufficient to hold the x and // y coordinates- Video memory begins at address 0 and is write only. // The address space is shared with the ROM which is read only. void put_pixel(unsigned char x, unsigned char y, unsigned char color) { *((unsigned char*)(160*y+x)) = color; } // bresenham algorithm to draw a line void draw_line(unsigned char x, unsigned char y, unsigned char x2, unsigned char y2, unsigned char color) { unsigned char longest, shortest, numerator, i; char dx1 = (x<x2)?1:-1; char dy1 = (y<y2)?1:-1; char dx2, dy2; longest = abs(x2 - x); shortest = abs(y2 - y); if(longest<shortest) { longest = abs(y2 - y); shortest = abs(x2 - x); dx2 = 0; dy2 = dy1; } else { dx2 = dx1; dy2 = 0; } numerator = longest/2; for(i=0;i<=longest;i++) { put_pixel(x,y,color) ; if(numerator >= longest-shortest) { numerator += shortest ; numerator -= longest ; x += dx1; y += dy1; } else { numerator += shortest ; x += dx2; y += dy2; } } } void main() { int i; unsigned char color = 0; // clear screen for(i=0;i<16000;i++) *(char*)i = 0x00; // draw colorful lines forever ... while(1) { for(i=0;i<100;i++) draw_line(0,0,159,i,color++); for(i=159;i>=0;i--) draw_line(0,0,i,99,color++); for(i=0;i<160;i++) draw_line(0,99,i,0,color++); for(i=0;i<100;i++) draw_line(0,99,159,i,color++); for(i=99;i>=0;i--) draw_line(159,99,0,i,color++); for(i=0;i<160;i++) draw_line(159,99,i,0,color++); for(i=159;i>=0;i--) draw_line(159,0,i,99,color++); for(i=99;i>=0;i--) draw_line(159,0,0,i,color++); } } <|start_filename|>basic/lesson3/verilator/sim/vinc/verilated_config.h<|end_filename|> // -*- mode: C++; c-file-style: "cc-mode" -*- //************************************************************************* // // Copyright 2003-2020 by <NAME>. This program is free software; you can // redistribute it and/or modify it under the terms of either the GNU // Lesser General Public License Version 3 or the Perl Artistic License. // Version 2.0. // // Verilator is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // //************************************************************************* /// /// \file /// \brief Verilator: Auto version information include for all Verilated C files /// /// Code available from: https://verilator.org /// //************************************************************************* ///**** Product and Version name // Autoconf substitutes this with the strings from AC_INIT. #define VERILATOR_PRODUCT "Verilator" #define VERILATOR_VERSION "4.028 2020-02-06" <|start_filename|>basic/lesson3/verilator/sim/vinc/verilated_vcd_c.h<|end_filename|> // -*- mode: C++; c-file-style: "cc-mode" -*- //============================================================================= // // THIS MODULE IS PUBLICLY LICENSED // // Copyright 2001-2020 by <NAME>. This program is free software; // you can redistribute it and/or modify it under the terms of either the GNU // Lesser General Public License Version 3 or the Perl Artistic License Version 2.0. // // This is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // //============================================================================= /// /// \file /// \brief C++ Tracing in VCD Format /// //============================================================================= // SPDIFF_OFF #ifndef _VERILATED_VCD_C_H_ #define _VERILATED_VCD_C_H_ 1 #include "verilatedos.h" #include "verilated.h" #include <map> #include <string> #include <vector> class VerilatedVcd; class VerilatedVcdCallInfo; // SPDIFF_ON //============================================================================= // VerilatedFile /// File handling routines, which can be overrode for e.g. socket I/O class VerilatedVcdFile { private: int m_fd; ///< File descriptor we're writing to public: // METHODS VerilatedVcdFile() : m_fd(0) {} virtual ~VerilatedVcdFile() {} virtual bool open(const std::string& name) VL_MT_UNSAFE; virtual void close() VL_MT_UNSAFE; virtual ssize_t write(const char* bufp, ssize_t len) VL_MT_UNSAFE; }; //============================================================================= // VerilatedVcdSig /// Internal data on one signal being traced. class VerilatedVcdSig { protected: friend class VerilatedVcd; vluint32_t m_code; ///< VCD file code number int m_bits; ///< Size of value in bits VerilatedVcdSig(vluint32_t code, int bits) : m_code(code) , m_bits(bits) {} public: ~VerilatedVcdSig() {} }; //============================================================================= typedef void (*VerilatedVcdCallback_t)(VerilatedVcd* vcdp, void* userthis, vluint32_t code); //============================================================================= // VerilatedVcd /// Base class to create a Verilator VCD dump /// This is an internally used class - see VerilatedVcdC for what to call from applications class VerilatedVcd { private: VerilatedVcdFile* m_filep; ///< File we're writing to bool m_fileNewed; ///< m_filep needs destruction bool m_isOpen; ///< True indicates open file bool m_evcd; ///< True for evcd format std::string m_filename; ///< Filename we're writing to (if open) vluint64_t m_rolloverMB; ///< MB of file size to rollover at char m_scopeEscape; ///< Character to separate scope components int m_modDepth; ///< Depth of module hierarchy bool m_fullDump; ///< True indicates dump ignoring if changed vluint32_t m_nextCode; ///< Next code number to assign std::string m_modName; ///< Module name being traced now double m_timeRes; ///< Time resolution (ns/ms etc) double m_timeUnit; ///< Time units (ns/ms etc) vluint64_t m_timeLastDump; ///< Last time we did a dump char* m_wrBufp; ///< Output buffer char* m_wrFlushp; ///< Output buffer flush trigger location char* m_writep; ///< Write pointer into output buffer vluint64_t m_wrChunkSize; ///< Output buffer size vluint64_t m_wroteBytes; ///< Number of bytes written to this file vluint32_t* m_sigs_oldvalp; ///< Pointer to old signal values typedef std::vector<VerilatedVcdSig> SigVec; SigVec m_sigs; ///< Pointer to signal information typedef std::vector<VerilatedVcdCallInfo*> CallbackVec; CallbackVec m_callbacks; ///< Routines to perform dumping typedef std::map<std::string,std::string> NameMap; NameMap* m_namemapp; ///< List of names for the header VerilatedAssertOneThread m_assertOne; ///< Assert only called from single thread void bufferResize(vluint64_t minsize); void bufferFlush() VL_MT_UNSAFE_ONE; inline void bufferCheck() { // Flush the write buffer if there's not enough space left for new information // We only call this once per vector, so we need enough slop for a very wide "b###" line if (VL_UNLIKELY(m_writep > m_wrFlushp)) { bufferFlush(); } } void closePrev(); void closeErr(); void openNext(); void makeNameMap(); void deleteNameMap(); void printIndent(int level_change); void printStr(const char* str); void printQuad(vluint64_t n); void printTime(vluint64_t timeui); void declare(vluint32_t code, const char* name, const char* wirep, bool array, int arraynum, bool tri, bool bussed, int msb, int lsb); void dumpHeader(); void dumpPrep(vluint64_t timeui); void dumpFull(vluint64_t timeui); // cppcheck-suppress functionConst void dumpDone(); inline void printCode(vluint32_t code) { *m_writep++ = static_cast<char>('!' + code % 94); code /= 94; while (code) { code--; *m_writep++ = static_cast<char>('!' + code % 94); code /= 94; } } static std::string stringCode(vluint32_t code) VL_PURE { std::string out; out += static_cast<char>('!' + code % 94); code /= 94; while (code) { code--; out += static_cast<char>('!' + code % 94); code /= 94; } return out; } // CONSTRUCTORS VL_UNCOPYABLE(VerilatedVcd); public: explicit VerilatedVcd(VerilatedVcdFile* filep = NULL); ~VerilatedVcd(); // ACCESSORS /// Set size in megabytes after which new file should be created void rolloverMB(vluint64_t rolloverMB) { m_rolloverMB = rolloverMB; } /// Is file open? bool isOpen() const { return m_isOpen; } /// Change character that splits scopes. Note whitespace are ALWAYS escapes. void scopeEscape(char flag) { m_scopeEscape = flag; } /// Is this an escape? inline bool isScopeEscape(char c) { return isspace(c) || c == m_scopeEscape; } // METHODS void open(const char* filename) VL_MT_UNSAFE_ONE; ///< Open the file; call isOpen() to see if errors void openNext(bool incFilename); ///< Open next data-only file void close() VL_MT_UNSAFE_ONE; ///< Close the file /// Flush any remaining data to this file void flush() VL_MT_UNSAFE_ONE { bufferFlush(); } /// Flush any remaining data from all files static void flush_all() VL_MT_UNSAFE_ONE; void set_time_unit(const char* unitp); ///< Set time units (s/ms, defaults to ns) void set_time_unit(const std::string& unit) { set_time_unit(unit.c_str()); } void set_time_resolution(const char* unitp); ///< Set time resolution (s/ms, defaults to ns) void set_time_resolution(const std::string& unit) { set_time_resolution(unit.c_str()); } double timescaleToDouble(const char* unitp); std::string doubleToTimescale(double value); /// Inside dumping routines, called each cycle to make the dump void dump(vluint64_t timeui); /// Call dump with a absolute unscaled time in seconds void dumpSeconds(double secs) { dump(static_cast<vluint64_t>(secs * m_timeRes)); } /// Inside dumping routines, declare callbacks for tracings void addCallback(VerilatedVcdCallback_t initcb, VerilatedVcdCallback_t fullcb, VerilatedVcdCallback_t changecb, void* userthis) VL_MT_UNSAFE_ONE; /// Inside dumping routines, declare a module void module(const std::string& name); /// Inside dumping routines, declare a signal void declBit( vluint32_t code, const char* name, bool array, int arraynum); void declBus( vluint32_t code, const char* name, bool array, int arraynum, int msb, int lsb); void declQuad( vluint32_t code, const char* name, bool array, int arraynum, int msb, int lsb); void declArray( vluint32_t code, const char* name, bool array, int arraynum, int msb, int lsb); void declTriBit( vluint32_t code, const char* name, bool array, int arraynum); void declTriBus( vluint32_t code, const char* name, bool array, int arraynum, int msb, int lsb); void declTriQuad( vluint32_t code, const char* name, bool array, int arraynum, int msb, int lsb); void declTriArray(vluint32_t code, const char* name, bool array, int arraynum, int msb, int lsb); void declDouble( vluint32_t code, const char* name, bool array, int arraynum); void declFloat( vluint32_t code, const char* name, bool array, int arraynum); // ... other module_start for submodules (based on cell name) /// Inside dumping routines, dump one signal void fullBit(vluint32_t code, const vluint32_t newval) { // Note the &1, so we don't require clean input -- makes more common no change case faster m_sigs_oldvalp[code] = newval; *m_writep++=('0'+static_cast<char>(newval&1)); printCode(code); *m_writep++='\n'; bufferCheck(); } void fullBus(vluint32_t code, const vluint32_t newval, int bits) { m_sigs_oldvalp[code] = newval; *m_writep++='b'; for (int bit=bits-1; bit>=0; --bit) { *m_writep++=((newval&(1L<<bit))?'1':'0'); } *m_writep++=' '; printCode(code); *m_writep++='\n'; bufferCheck(); } void fullQuad(vluint32_t code, const vluint64_t newval, int bits) { (*(reinterpret_cast<vluint64_t*>(&m_sigs_oldvalp[code]))) = newval; *m_writep++='b'; for (int bit=bits-1; bit>=0; --bit) { *m_writep++ = ((newval & (VL_ULL(1) << bit)) ? '1' : '0'); } *m_writep++=' '; printCode(code); *m_writep++='\n'; bufferCheck(); } void fullArray(vluint32_t code, const vluint32_t* newval, int bits) { for (int word = 0; word < (((bits - 1) / 32) + 1); ++word) { m_sigs_oldvalp[code + word] = newval[word]; } *m_writep++ = 'b'; for (int bit = bits - 1; bit >= 0; --bit) { *m_writep++ = ((newval[(bit / 32)] & (1L << (bit & 0x1f))) ? '1' : '0'); } *m_writep ++= ' '; printCode(code); *m_writep ++= '\n'; bufferCheck(); } void fullArray(vluint32_t code, const vluint64_t* newval, int bits) { for (int word = 0; word < (((bits - 1) / 64) + 1); ++word) { m_sigs_oldvalp[code + word] = newval[word]; } *m_writep ++= 'b'; for (int bit = bits - 1; bit >= 0; --bit) { *m_writep++ = ((newval[(bit / 64)] & (VL_ULL(1) << (bit & 0x3f))) ? '1' : '0'); } *m_writep ++= ' '; printCode(code); *m_writep ++= '\n'; bufferCheck(); } void fullTriBit(vluint32_t code, const vluint32_t newval, const vluint32_t newtri) { m_sigs_oldvalp[code] = newval; m_sigs_oldvalp[code+1] = newtri; *m_writep++ = "01zz"[m_sigs_oldvalp[code] | (m_sigs_oldvalp[code+1]<<1)]; printCode(code); *m_writep++='\n'; bufferCheck(); } void fullTriBus(vluint32_t code, const vluint32_t newval, const vluint32_t newtri, int bits) { m_sigs_oldvalp[code] = newval; m_sigs_oldvalp[code+1] = newtri; *m_writep++='b'; for (int bit=bits-1; bit>=0; --bit) { *m_writep++ = "01zz"[((newval >> bit)&1) | (((newtri >> bit)&1)<<1)]; } *m_writep++=' '; printCode(code); *m_writep++='\n'; bufferCheck(); } void fullTriQuad(vluint32_t code, const vluint64_t newval, const vluint32_t newtri, int bits) { (*(reinterpret_cast<vluint64_t*>(&m_sigs_oldvalp[code]))) = newval; (*(reinterpret_cast<vluint64_t*>(&m_sigs_oldvalp[code+1]))) = newtri; *m_writep++='b'; for (int bit=bits-1; bit>=0; --bit) { *m_writep++ = "01zz"[((newval >> bit) & VL_ULL(1)) | (((newtri >> bit) & VL_ULL(1)) << VL_ULL(1))]; } *m_writep++=' '; printCode(code); *m_writep++='\n'; bufferCheck(); } void fullTriArray(vluint32_t code, const vluint32_t* newvalp, const vluint32_t* newtrip, int bits) { for (int word=0; word<(((bits-1)/32)+1); ++word) { m_sigs_oldvalp[code+word*2] = newvalp[word]; m_sigs_oldvalp[code+word*2+1] = newtrip[word]; } *m_writep++='b'; for (int bit=bits-1; bit>=0; --bit) { vluint32_t valbit = (newvalp[(bit/32)]>>(bit&0x1f)) & 1; vluint32_t tribit = (newtrip[(bit/32)]>>(bit&0x1f)) & 1; *m_writep++ = "01zz"[valbit | (tribit<<1)]; } *m_writep++=' '; printCode(code); *m_writep++='\n'; bufferCheck(); } void fullDouble(vluint32_t code, const double newval); void fullFloat(vluint32_t code, const float newval); /// Inside dumping routines, dump one signal as unknowns /// Presently this code doesn't change the oldval vector. /// Thus this is for special standalone applications that after calling /// fullBitX, must when then value goes non-X call fullBit. inline void fullBitX(vluint32_t code) { *m_writep++='x'; printCode(code); *m_writep++='\n'; bufferCheck(); } inline void fullBusX(vluint32_t code, int bits) { *m_writep++='b'; for (int bit=bits-1; bit>=0; --bit) { *m_writep++='x'; } *m_writep++=' '; printCode(code); *m_writep++='\n'; bufferCheck(); } inline void fullQuadX(vluint32_t code, int bits) { fullBusX(code, bits); } inline void fullArrayX(vluint32_t code, int bits) { fullBusX(code, bits); } /// Inside dumping routines, dump one signal if it has changed inline void chgBit(vluint32_t code, const vluint32_t newval) { vluint32_t diff = m_sigs_oldvalp[code] ^ newval; if (VL_UNLIKELY(diff)) { // Verilator 3.510 and newer provide clean input, so the below // is only for back compatibility if (VL_UNLIKELY(diff & 1)) { // Change after clean? fullBit(code, newval); } } } inline void chgBus(vluint32_t code, const vluint32_t newval, int bits) { vluint32_t diff = m_sigs_oldvalp[code] ^ newval; if (VL_UNLIKELY(diff)) { if (VL_UNLIKELY(bits == 32 || (diff & ((1U << bits) - 1)))) { fullBus(code, newval, bits); } } } inline void chgQuad(vluint32_t code, const vluint64_t newval, int bits) { vluint64_t diff = (*(reinterpret_cast<vluint64_t*>(&m_sigs_oldvalp[code]))) ^ newval; if (VL_UNLIKELY(diff)) { if (VL_UNLIKELY(bits == 64 || (diff & ((VL_ULL(1) << bits) - 1)))) { fullQuad(code, newval, bits); } } } inline void chgArray(vluint32_t code, const vluint32_t* newval, int bits) { for (int word = 0; word < (((bits - 1) / 32) + 1); ++word) { if (VL_UNLIKELY(m_sigs_oldvalp[code + word] ^ newval[word])) { fullArray(code, newval, bits); return; } } } inline void chgArray(vluint32_t code, const vluint64_t* newval, int bits) { for (int word = 0; word < (((bits - 1) / 64) + 1); ++word) { if (VL_UNLIKELY(m_sigs_oldvalp[code + word] ^ newval[word])) { fullArray(code, newval, bits); return; } } } inline void chgTriBit(vluint32_t code, const vluint32_t newval, const vluint32_t newtri) { vluint32_t diff = ((m_sigs_oldvalp[code] ^ newval) | (m_sigs_oldvalp[code+1] ^ newtri)); if (VL_UNLIKELY(diff)) { // Verilator 3.510 and newer provide clean input, so the below // is only for back compatibility if (VL_UNLIKELY(diff & 1)) { // Change after clean? fullTriBit(code, newval, newtri); } } } inline void chgTriBus(vluint32_t code, const vluint32_t newval, const vluint32_t newtri, int bits) { vluint32_t diff = ((m_sigs_oldvalp[code] ^ newval) | (m_sigs_oldvalp[code+1] ^ newtri)); if (VL_UNLIKELY(diff)) { if (VL_UNLIKELY(bits==32 || (diff & ((1U<<bits)-1) ))) { fullTriBus(code, newval, newtri, bits); } } } inline void chgTriQuad(vluint32_t code, const vluint64_t newval, const vluint32_t newtri, int bits) { vluint64_t diff = ( ((*(reinterpret_cast<vluint64_t*>(&m_sigs_oldvalp[code]))) ^ newval) | ((*(reinterpret_cast<vluint64_t*>(&m_sigs_oldvalp[code+1]))) ^ newtri)); if (VL_UNLIKELY(diff)) { if (VL_UNLIKELY(bits == 64 || (diff & ((VL_ULL(1) << bits) - 1)))) { fullTriQuad(code, newval, newtri, bits); } } } inline void chgTriArray(vluint32_t code, const vluint32_t* newvalp, const vluint32_t* newtrip, int bits) { for (int word=0; word<(((bits-1)/32)+1); ++word) { if (VL_UNLIKELY((m_sigs_oldvalp[code+word*2] ^ newvalp[word]) | (m_sigs_oldvalp[code+word*2+1] ^ newtrip[word]))) { fullTriArray(code,newvalp,newtrip,bits); return; } } } inline void chgDouble(vluint32_t code, const double newval) { // cppcheck-suppress invalidPointerCast if (VL_UNLIKELY((*(reinterpret_cast<double*>(&m_sigs_oldvalp[code]))) != newval)) { fullDouble(code, newval); } } inline void chgFloat(vluint32_t code, const float newval) { // cppcheck-suppress invalidPointerCast if (VL_UNLIKELY((*(reinterpret_cast<float*>(&m_sigs_oldvalp[code]))) != newval)) { fullFloat(code, newval); } } protected: // METHODS void evcd(bool flag) { m_evcd = flag; } }; //============================================================================= // VerilatedVcdC /// Create a VCD dump file in C standalone (no SystemC) simulations. /// Also derived for use in SystemC simulations. /// Thread safety: Unless otherwise indicated, every function is VL_MT_UNSAFE_ONE class VerilatedVcdC { VerilatedVcd m_sptrace; ///< Trace file being created // CONSTRUCTORS VL_UNCOPYABLE(VerilatedVcdC); public: explicit VerilatedVcdC(VerilatedVcdFile* filep = NULL) : m_sptrace(filep) {} ~VerilatedVcdC() {} public: // ACCESSORS /// Is file open? bool isOpen() const { return m_sptrace.isOpen(); } // METHODS /// Open a new VCD file /// This includes a complete header dump each time it is called, /// just as if this object was deleted and reconstructed. void open(const char* filename) VL_MT_UNSAFE_ONE { m_sptrace.open(filename); } /// Continue a VCD dump by rotating to a new file name /// The header is only in the first file created, this allows /// "cat" to be used to combine the header plus any number of data files. void openNext(bool incFilename = true) VL_MT_UNSAFE_ONE { m_sptrace.openNext(incFilename); } /// Set size in megabytes after which new file should be created void rolloverMB(size_t rolloverMB) { m_sptrace.rolloverMB(rolloverMB); } /// Close dump void close() VL_MT_UNSAFE_ONE { m_sptrace.close(); } /// Flush dump void flush() VL_MT_UNSAFE_ONE { m_sptrace.flush(); } /// Write one cycle of dump data void dump(vluint64_t timeui) { m_sptrace.dump(timeui); } /// Write one cycle of dump data - backward compatible and to reduce /// conversion warnings. It's better to use a vluint64_t time instead. void dump(double timestamp) { dump(static_cast<vluint64_t>(timestamp)); } void dump(vluint32_t timestamp) { dump(static_cast<vluint64_t>(timestamp)); } void dump(int timestamp) { dump(static_cast<vluint64_t>(timestamp)); } /// Set time units (s/ms, defaults to ns) /// See also VL_TIME_PRECISION, and VL_TIME_MULTIPLIER in verilated.h void set_time_unit(const char* unit) { m_sptrace.set_time_unit(unit); } void set_time_unit(const std::string& unit) { set_time_unit(unit.c_str()); } /// Set time resolution (s/ms, defaults to ns) /// See also VL_TIME_PRECISION, and VL_TIME_MULTIPLIER in verilated.h void set_time_resolution(const char* unit) { m_sptrace.set_time_resolution(unit); } void set_time_resolution(const std::string& unit) { set_time_resolution(unit.c_str()); } /// Internal class access inline VerilatedVcd* spTrace() { return &m_sptrace; } }; #endif // guard <|start_filename|>basic/lesson2/verilator/vinc/verilated.h<|end_filename|> // -*- mode: C++; c-file-style: "cc-mode" -*- //************************************************************************* // // Copyright 2003-2020 by <NAME>. This program is free software; you can // redistribute it and/or modify it under the terms of either the GNU // Lesser General Public License Version 3 or the Perl Artistic License. // Version 2.0. // // Verilator is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // //************************************************************************* /// /// \file /// \brief Verilator: Common include for all Verilated C files /// /// This file is included automatically by Verilator at the top of /// all C++ files it generates. It contains standard macros and /// classes required by the Verilated code. /// /// Code available from: https://verilator.org /// //************************************************************************* #ifndef _VERILATED_H_ #define _VERILATED_H_ 1 ///< Header Guard #include "verilatedos.h" #include <cassert> #include <cmath> #include <cstdarg> #include <cstdio> #include <cstdlib> #include <cstring> // <iostream> avoided to reduce compile time // <map> avoided and instead in verilated_heavy.h to reduce compile time // <string> avoided and instead in verilated_heavy.h to reduce compile time #ifdef VL_THREADED # include <atomic> # include <mutex> # include <thread> #endif // Allow user to specify their own include file #ifdef VL_VERILATED_INCLUDE # include VL_VERILATED_INCLUDE #endif //============================================================================= // Switches #if VM_TRACE // Verilator tracing requested # define WAVES 1 // Set backward compatibility flag #endif //========================================================================= // Basic types // P // Packed data of bit type (C/S/I/Q/W) typedef vluint8_t CData; ///< Verilated pack data, 1-8 bits typedef vluint16_t SData; ///< Verilated pack data, 9-16 bits typedef vluint32_t IData; ///< Verilated pack data, 17-32 bits typedef vluint64_t QData; ///< Verilated pack data, 33-64 bits typedef vluint32_t EData; ///< Verilated pack element of WData array typedef EData WData; ///< Verilated pack data, >64 bits, as an array // float F // No typedef needed; Verilator uses float // double D // No typedef needed; Verilator uses double // string N // No typedef needed; Verilator uses string typedef const WData* WDataInP; ///< Array input to a function typedef WData* WDataOutP; ///< Array output from a function typedef void (*VerilatedVoidCb)(void); class SpTraceVcd; class SpTraceVcdCFile; class VerilatedEvalMsgQueue; class VerilatedScopeNameMap; class VerilatedVar; class VerilatedVarNameMap; class VerilatedVcd; class VerilatedVcdC; class VerilatedFst; class VerilatedFstC; enum VerilatedVarType { VLVT_UNKNOWN=0, VLVT_PTR, // Pointer to something VLVT_UINT8, // AKA CData VLVT_UINT16, // AKA SData VLVT_UINT32, // AKA IData VLVT_UINT64, // AKA QData VLVT_WDATA, // AKA WData VLVT_STRING // C++ string }; enum VerilatedVarFlags { VLVD_0 = 0, // None VLVD_IN = 1, // == vpiInput VLVD_OUT = 2, // == vpiOutput VLVD_INOUT = 3, // == vpiInOut VLVD_NODIR = 5, // == vpiNoDirection VLVF_MASK_DIR = 7, // Bit mask for above directions // Flags VLVF_PUB_RD = (1<<8), // Public readable VLVF_PUB_RW = (1<<9), // Public writable VLVF_DPI_CLAY = (1<<10) // DPI compatible C standard layout }; //========================================================================= /// Mutex and threading support /// Return current thread ID (or 0), not super fast, cache if needed extern vluint32_t VL_THREAD_ID() VL_MT_SAFE; #if VL_THREADED #define VL_LOCK_SPINS 50000 /// Number of times to spin for a mutex before relaxing /// Mutex, wrapped to allow -fthread_safety checks class VL_CAPABILITY("mutex") VerilatedMutex { private: std::mutex m_mutex; // Mutex public: VerilatedMutex() {} ~VerilatedMutex() {} const VerilatedMutex& operator!() const { return *this; } // For -fthread_safety /// Acquire/lock mutex void lock() VL_ACQUIRE() { // Try to acquire the lock by spinning. If the wait is short, // avoids a trap to the OS plus OS scheduler overhead. if (VL_LIKELY(try_lock())) return; // Short circuit loop for (int i = 0; i < VL_LOCK_SPINS; ++i) { if (VL_LIKELY(try_lock())) return; VL_CPU_RELAX(); } // Spinning hasn't worked, pay the cost of blocking. m_mutex.lock(); } /// Release/unlock mutex void unlock() VL_RELEASE() { m_mutex.unlock(); } /// Try to acquire mutex. Returns true on success, and false on failure. bool try_lock() VL_TRY_ACQUIRE(true) { return m_mutex.try_lock(); } }; /// Lock guard for mutex (ala std::unique_lock), wrapped to allow -fthread_safety checks class VL_SCOPED_CAPABILITY VerilatedLockGuard { VL_UNCOPYABLE(VerilatedLockGuard); private: VerilatedMutex& m_mutexr; public: explicit VerilatedLockGuard(VerilatedMutex& mutexr) VL_ACQUIRE(mutexr) : m_mutexr(mutexr) { m_mutexr.lock(); } ~VerilatedLockGuard() VL_RELEASE() { m_mutexr.unlock(); } void lock() VL_ACQUIRE() { m_mutexr.lock(); } void unlock() VL_RELEASE() { m_mutexr.unlock(); } }; #else // !VL_THREADED /// Empty non-threaded mutex to avoid #ifdefs in consuming code class VerilatedMutex { public: void lock() {} void unlock() {} }; /// Empty non-threaded lock guard to avoid #ifdefs in consuming code class VerilatedLockGuard { VL_UNCOPYABLE(VerilatedLockGuard); public: explicit VerilatedLockGuard(VerilatedMutex&) {} ~VerilatedLockGuard() {} void lock() {} void unlock() {} }; #endif // VL_THREADED /// Remember the calling thread at construction time, and make sure later calls use same thread class VerilatedAssertOneThread { // MEMBERS #if defined(VL_THREADED) && defined(VL_DEBUG) vluint32_t m_threadid; /// Thread that is legal public: // CONSTRUCTORS /// The constructor establishes the thread id for all later calls. /// If necessary, a different class could be made that inits it otherwise. VerilatedAssertOneThread() : m_threadid(VL_THREAD_ID()) {} ~VerilatedAssertOneThread() { check(); } // METHODS /// Check that the current thread ID is the same as the construction thread ID void check() VL_MT_UNSAFE_ONE { if (VL_UNCOVERABLE(m_threadid != VL_THREAD_ID())) { fatal_different(); // LCOV_EXCL_LINE } } static void fatal_different() VL_MT_SAFE; #else // !VL_THREADED || !VL_DEBUG public: void check() {} #endif }; //========================================================================= /// Base class for all Verilated module classes class VerilatedScope; class VerilatedModule { VL_UNCOPYABLE(VerilatedModule); private: const char* m_namep; ///< Module name public: explicit VerilatedModule(const char* namep); ///< Create module with given hierarchy name ~VerilatedModule(); const char* name() const { return m_namep; } ///< Return name of module }; //========================================================================= // Declare nets #ifndef VL_SIG # define VL_SIG8(name, msb,lsb) CData name ///< Declare signal, 1-8 bits # define VL_SIG16(name, msb,lsb) SData name ///< Declare signal, 9-16 bits # define VL_SIG64(name, msb,lsb) QData name ///< Declare signal, 33-64 bits # define VL_SIG(name, msb,lsb) IData name ///< Declare signal, 17-32 bits # define VL_SIGW(name, msb,lsb, words) WData name[words] ///< Declare signal, 65+ bits # define VL_IN8(name, msb,lsb) CData name ///< Declare input signal, 1-8 bits # define VL_IN16(name, msb,lsb) SData name ///< Declare input signal, 9-16 bits # define VL_IN64(name, msb,lsb) QData name ///< Declare input signal, 33-64 bits # define VL_IN(name, msb,lsb) IData name ///< Declare input signal, 17-32 bits # define VL_INW(name, msb,lsb, words) WData name[words] ///< Declare input signal, 65+ bits # define VL_INOUT8(name, msb,lsb) CData name ///< Declare bidir signal, 1-8 bits # define VL_INOUT16(name, msb,lsb) SData name ///< Declare bidir signal, 9-16 bits # define VL_INOUT64(name, msb,lsb) QData name ///< Declare bidir signal, 33-64 bits # define VL_INOUT(name, msb,lsb) IData name ///< Declare bidir signal, 17-32 bits # define VL_INOUTW(name, msb,lsb, words) WData name[words] ///< Declare bidir signal, 65+ bits # define VL_OUT8(name, msb,lsb) CData name ///< Declare output signal, 1-8 bits # define VL_OUT16(name, msb,lsb) SData name ///< Declare output signal, 9-16 bits # define VL_OUT64(name, msb,lsb) QData name ///< Declare output signal, 33-64bits # define VL_OUT(name, msb,lsb) IData name ///< Declare output signal, 17-32 bits # define VL_OUTW(name, msb,lsb, words) WData name[words] ///< Declare output signal, 65+ bits # define VL_PIN_NOP(instname,pin,port) ///< Connect a pin, ala SP_PIN # define VL_CELL(instname,type) ///< Declare a cell, ala SP_CELL /// Declare a module, ala SC_MODULE # define VL_MODULE(modname) class modname : public VerilatedModule /// Constructor, ala SC_CTOR # define VL_CTOR(modname) modname(const char* __VCname="") /// Constructor declaration for C++, ala SP_CTOR_IMPL # define VL_CTOR_IMP(modname) modname::modname(const char* __VCname) : VerilatedModule(__VCname) /// Constructor declaration for SystemC, ala SP_CTOR_IMPL # define VL_SC_CTOR_IMP(modname) modname::modname(sc_module_name) #endif //========================================================================= // Functions overridable by user defines // (Internals however must use VL_PRINTF_MT, which calls these.) #ifndef VL_PRINTF # define VL_PRINTF printf ///< Print ala printf, called from main thread; may redefine if desired #endif #ifndef VL_VPRINTF # define VL_VPRINTF vprintf ///< Print ala vprintf, called from main thread; may redefine if desired #endif //=========================================================================== /// Verilator symbol table base class class VerilatedSyms { public: // But for internal use only #ifdef VL_THREADED VerilatedEvalMsgQueue* __Vm_evalMsgQp; #endif VerilatedSyms(); ~VerilatedSyms(); }; //=========================================================================== /// Verilator global class information class /// This class is initialized by main thread only. Reading post-init is thread safe. class VerilatedScope { public: typedef enum { SCOPE_MODULE, SCOPE_OTHER } Type; // Type of a scope, currently module is only interesting private: // Fastpath: VerilatedSyms* m_symsp; ///< Symbol table void** m_callbacksp; ///< Callback table pointer (Fastpath) int m_funcnumMax; ///< Maxium function number stored (Fastpath) // 4 bytes padding (on -m64), for rent. VerilatedVarNameMap* m_varsp; ///< Variable map const char* m_namep; ///< Scope name (Slowpath) const char* m_identifierp; ///< Identifier of scope (with escapes removed) Type m_type; ///< Type of the scope public: // But internals only - called from VerilatedModule's VerilatedScope(); ~VerilatedScope(); void configure(VerilatedSyms* symsp, const char* prefixp, const char* suffix, const char* identifier, const Type type) VL_MT_UNSAFE; void exportInsert(int finalize, const char* namep, void* cb) VL_MT_UNSAFE; void varInsert(int finalize, const char* namep, void* datap, VerilatedVarType vltype, int vlflags, int dims, ...) VL_MT_UNSAFE; // ACCESSORS const char* name() const { return m_namep; } const char* identifier() const { return m_identifierp; } inline VerilatedSyms* symsp() const { return m_symsp; } VerilatedVar* varFind(const char* namep) const VL_MT_SAFE_POSTINIT; VerilatedVarNameMap* varsp() const VL_MT_SAFE_POSTINIT { return m_varsp; } void scopeDump() const; void* exportFindError(int funcnum) const; static void* exportFindNullError(int funcnum) VL_MT_SAFE; static inline void* exportFind(const VerilatedScope* scopep, int funcnum) VL_MT_SAFE { if (VL_UNLIKELY(!scopep)) return exportFindNullError(funcnum); if (VL_LIKELY(funcnum < scopep->m_funcnumMax)) { // m_callbacksp must be declared, as Max'es are > 0 return scopep->m_callbacksp[funcnum]; } else { // LCOV_EXCL_LINE return scopep->exportFindError(funcnum); // LCOV_EXCL_LINE } } Type type() const { return m_type; } }; class VerilatedHierarchy { public: void add(VerilatedScope* fromp, VerilatedScope* top); }; //=========================================================================== /// Verilator global static information class class Verilated { // MEMBERS // Slow path variables static VerilatedMutex m_mutex; ///< Mutex for s_s/s_ns members, when VL_THREADED static VerilatedVoidCb s_flushCb; ///< Flush callback function static struct Serialized { // All these members serialized/deserialized // Fast path int s_debug; ///< See accessors... only when VL_DEBUG set bool s_calcUnusedSigs; ///< Waves file on, need all signals calculated bool s_gotFinish; ///< A $finish statement executed bool s_assertOn; ///< Assertions are enabled bool s_fatalOnVpiError; ///< Stop on vpi error/unsupported // Slow path int s_errorCount; ///< Number of errors int s_errorLimit; ///< Stop on error number int s_randReset; ///< Random reset: 0=all 0s, 1=all 1s, 2=random int s_randSeed; ///< Random seed: 0=random Serialized(); ~Serialized() {} } s_s; static struct NonSerialized { // Non-serialized information // These are reloaded from on command-line settings, so do not need to persist // Fast path vluint64_t s_profThreadsStart; ///< +prof+threads starting time vluint32_t s_profThreadsWindow; ///< +prof+threads window size // Slow path const char* s_profThreadsFilenamep; ///< +prof+threads filename NonSerialized(); ~NonSerialized(); } s_ns; // no need to be save-restored (serialized) the // assumption is that the restore is allowed to pass different arguments static struct CommandArgValues { VerilatedMutex m_argMutex; ///< Mutex for s_args members, when VL_THREADED int argc; const char** argv; CommandArgValues() : argc(0), argv(NULL) {} ~CommandArgValues() {} } s_args; // Not covered by mutex, as per-thread static VL_THREAD_LOCAL struct ThreadLocal { #ifdef VL_THREADED vluint32_t t_mtaskId; ///< Current mtask# executing on this thread vluint32_t t_endOfEvalReqd; ///< Messages may be pending, thread needs endOf-eval calls #endif const VerilatedScope* t_dpiScopep; ///< DPI context scope const char* t_dpiFilename; ///< DPI context filename int t_dpiLineno; ///< DPI context line number ThreadLocal(); ~ThreadLocal(); } t_s; private: // CONSTRUCTORS VL_UNCOPYABLE(Verilated); public: // METHODS - User called /// Select initial value of otherwise uninitialized signals. //// /// 0 = Set to zeros /// 1 = Set all bits to one /// 2 = Randomize all bits static void randReset(int val) VL_MT_SAFE; static int randReset() VL_MT_SAFE { return s_s.s_randReset; } ///< Return randReset value static void randSeed(int val) VL_MT_SAFE; static int randSeed() VL_MT_SAFE { return s_s.s_randSeed; } ///< Return randSeed value /// Enable debug of internal verilated code static void debug(int level) VL_MT_SAFE; #ifdef VL_DEBUG /// Return debug level /// When multithreaded this may not immediately react to another thread /// changing the level (no mutex) static inline int debug() VL_MT_SAFE { return s_s.s_debug; } #else static inline int debug() VL_PURE { return 0; } ///< Return constant 0 debug level, so C++'s optimizer rips up #endif /// Enable calculation of unused signals static void calcUnusedSigs(bool flag) VL_MT_SAFE; static bool calcUnusedSigs() VL_MT_SAFE { ///< Return calcUnusedSigs value return s_s.s_calcUnusedSigs; } /// Current number of errors/assertions static void errorCount(int val) VL_MT_SAFE; static void errorCountInc() VL_MT_SAFE; static int errorCount() VL_MT_SAFE { return s_s.s_errorCount; } /// Set number of errors/assertions before stop static void errorLimit(int val) VL_MT_SAFE; static int errorLimit() VL_MT_SAFE { return s_s.s_errorLimit; } /// Did the simulation $finish? static void gotFinish(bool flag) VL_MT_SAFE; static bool gotFinish() VL_MT_SAFE { return s_s.s_gotFinish; } ///< Return if got a $finish /// Allow traces to at some point be enabled (disables some optimizations) static void traceEverOn(bool flag) VL_MT_SAFE { if (flag) { calcUnusedSigs(flag); } } /// Enable/disable assertions static void assertOn(bool flag) VL_MT_SAFE; static bool assertOn() VL_MT_SAFE { return s_s.s_assertOn; } /// Enable/disable vpi fatal static void fatalOnVpiError(bool flag) VL_MT_SAFE; static bool fatalOnVpiError() VL_MT_SAFE { return s_s.s_fatalOnVpiError; } /// --prof-threads related settings static void profThreadsStart(vluint64_t flag) VL_MT_SAFE; static vluint64_t profThreadsStart() VL_MT_SAFE { return s_ns.s_profThreadsStart; } static void profThreadsWindow(vluint64_t flag) VL_MT_SAFE; static vluint32_t profThreadsWindow() VL_MT_SAFE { return s_ns.s_profThreadsWindow; } static void profThreadsFilenamep(const char* flagp) VL_MT_SAFE; static const char* profThreadsFilenamep() VL_MT_SAFE { return s_ns.s_profThreadsFilenamep; } /// Flush callback for VCD waves static void flushCb(VerilatedVoidCb cb) VL_MT_SAFE; static void flushCall() VL_MT_SAFE; /// Record command line arguments, for retrieval by $test$plusargs/$value$plusargs, /// and for parsing +verilator+ run-time arguments. /// This should be called before the first model is created. static void commandArgs(int argc, const char** argv) VL_MT_SAFE; static void commandArgs(int argc, char** argv) VL_MT_SAFE { commandArgs(argc, const_cast<const char**>(argv)); } static void commandArgsAdd(int argc, const char** argv); static CommandArgValues* getCommandArgs() VL_MT_SAFE { return &s_args; } /// Match plusargs with a given prefix. Returns static char* valid only for a single call static const char* commandArgsPlusMatch(const char* prefixp) VL_MT_SAFE; /// Produce name & version for (at least) VPI static const char* productName() VL_PURE; static const char* productVersion() VL_PURE; /// Convenience OS utilities static void mkdir(const char* dirname) VL_MT_UNSAFE; /// When multithreaded, quiesce the model to prepare for trace/saves/coverage /// This may only be called when no locks are held. static void quiesce() VL_MT_SAFE; /// For debugging, print much of the Verilator internal state. /// The output of this function may change in future /// releases - contact the authors before production use. static void internalsDump() VL_MT_SAFE; /// For debugging, print text list of all scope names with /// dpiImport/Export context. This function may change in future /// releases - contact the authors before production use. static void scopesDump() VL_MT_SAFE; public: // METHODS - INTERNAL USE ONLY (but public due to what uses it) // Internal: Create a new module name by concatenating two strings static const char* catName(const char* n1, const char* n2, const char* delimiter = "."); // Returns static data // Internal: Throw signal assertion static void overWidthError(const char* signame) VL_MT_SAFE; // Internal: Find scope static const VerilatedScope* scopeFind(const char* namep) VL_MT_SAFE; static const VerilatedScopeNameMap* scopeNameMap() VL_MT_SAFE; // Internal: Get and set DPI context static const VerilatedScope* dpiScope() VL_MT_SAFE { return t_s.t_dpiScopep; } static void dpiScope(const VerilatedScope* scopep) VL_MT_SAFE { t_s.t_dpiScopep = scopep; } static void dpiContext(const VerilatedScope* scopep, const char* filenamep, int lineno) VL_MT_SAFE { t_s.t_dpiScopep = scopep; t_s.t_dpiFilename = filenamep; t_s.t_dpiLineno = lineno; } static void dpiClearContext() VL_MT_SAFE { t_s.t_dpiScopep = NULL; } static bool dpiInContext() VL_MT_SAFE { return t_s.t_dpiScopep != NULL; } static const char* dpiFilenamep() VL_MT_SAFE { return t_s.t_dpiFilename; } static int dpiLineno() VL_MT_SAFE { return t_s.t_dpiLineno; } static int exportFuncNum(const char* namep) VL_MT_SAFE; static size_t serializedSize() VL_PURE { return sizeof(s_s); } static void* serializedPtr() VL_MT_UNSAFE { return &s_s; } // Unsafe, for Serialize only #ifdef VL_THREADED /// Set the mtaskId, called when an mtask starts static void mtaskId(vluint32_t id) VL_MT_SAFE { t_s.t_mtaskId = id; } static vluint32_t mtaskId() VL_MT_SAFE { return t_s.t_mtaskId; } static void endOfEvalReqdInc() VL_MT_SAFE { ++t_s.t_endOfEvalReqd; } static void endOfEvalReqdDec() VL_MT_SAFE { --t_s.t_endOfEvalReqd; } /// Called at end of each thread mtask, before finishing eval static void endOfThreadMTask(VerilatedEvalMsgQueue* evalMsgQp) VL_MT_SAFE { if (VL_UNLIKELY(t_s.t_endOfEvalReqd)) { endOfThreadMTaskGuts(evalMsgQp); } } /// Called at end of eval loop static void endOfEval(VerilatedEvalMsgQueue* evalMsgQp) VL_MT_SAFE { // It doesn't work to set endOfEvalReqd on the threadpool thread // and then check it on the eval thread since it's thread local. // It should be ok to call into endOfEvalGuts, it returns immediately // if there are no transactions. endOfEvalGuts(evalMsgQp); } #endif private: #ifdef VL_THREADED static void endOfThreadMTaskGuts(VerilatedEvalMsgQueue* evalMsgQp) VL_MT_SAFE; static void endOfEvalGuts(VerilatedEvalMsgQueue* evalMsgQp) VL_MT_SAFE; #endif }; //========================================================================= // Extern functions -- User may override -- See verilated.cpp /// Routine to call for $finish /// User code may wish to replace this function, to do so, define VL_USER_FINISH. /// This code does not have to be thread safe. /// Verilator internal code must call VL_FINISH_MT instead, which eventually calls this. extern void vl_finish(const char* filename, int linenum, const char* hier); /// Routine to call for $stop /// User code may wish to replace this function, to do so, define VL_USER_STOP. /// This code does not have to be thread safe. /// Verilator internal code must call VL_FINISH_MT instead, which eventually calls this. extern void vl_stop(const char* filename, int linenum, const char* hier); /// Routine to call for a couple of fatal messages /// User code may wish to replace this function, to do so, define VL_USER_FATAL. /// This code does not have to be thread safe. /// Verilator internal code must call VL_FINISH_MT instead, which eventually calls this. extern void vl_fatal(const char* filename, int linenum, const char* hier, const char* msg); //========================================================================= // Extern functions -- Slow path /// Multithread safe wrapper for calls to $finish extern void VL_FINISH_MT(const char* filename, int linenum, const char* hier) VL_MT_SAFE; /// Multithread safe wrapper for calls to $stop extern void VL_STOP_MT(const char* filename, int linenum, const char* hier, bool maybe = true) VL_MT_SAFE; /// Multithread safe wrapper to call for a couple of fatal messages extern void VL_FATAL_MT(const char* filename, int linenum, const char* hier, const char* msg) VL_MT_SAFE; /// Print a string, multithread safe. Eventually VL_PRINTF will get called. #ifdef VL_THREADED extern void VL_PRINTF_MT(const char* formatp, ...) VL_ATTR_PRINTF(1) VL_MT_SAFE; #else # define VL_PRINTF_MT VL_PRINTF // The following parens will take care of themselves #endif /// Print a debug message from internals with standard prefix, with printf style format extern void VL_DBG_MSGF(const char* formatp, ...) VL_ATTR_PRINTF(1) VL_MT_SAFE; extern IData VL_RANDOM_I(int obits); ///< Randomize a signal extern QData VL_RANDOM_Q(int obits); ///< Randomize a signal extern WDataOutP VL_RANDOM_W(int obits, WDataOutP outwp); ///< Randomize a signal /// Init time only, so slow is fine extern IData VL_RAND_RESET_I(int obits); ///< Random reset a signal extern QData VL_RAND_RESET_Q(int obits); ///< Random reset a signal extern WDataOutP VL_RAND_RESET_W(int obits, WDataOutP outwp); ///< Random reset a signal extern WDataOutP VL_ZERO_RESET_W(int obits, WDataOutP outwp); ///< Zero reset a signal (slow - else use VL_ZERO_W) #if VL_THREADED /// Return high-precision counter for profiling, or 0x0 if not available inline QData VL_RDTSC_Q() { vluint64_t val; VL_RDTSC(val); return val; } #endif /// Math extern WDataOutP _vl_moddiv_w(int lbits, WDataOutP owp, WDataInP lwp, WDataInP rwp, bool is_modulus); /// File I/O extern IData VL_FGETS_IXI(int obits, void* destp, IData fpi); extern IData VL_FOPEN_S(const char* filenamep, const char* modep); extern IData VL_FOPEN_WI(int fnwords, WDataInP filenamep, IData mode); extern IData VL_FOPEN_QI(QData filename, IData mode); inline IData VL_FOPEN_II(IData filename, IData mode) VL_MT_SAFE { return VL_FOPEN_QI(filename, mode); } extern void VL_FCLOSE_I(IData fdi); extern IData VL_FREAD_I(int width, int array_lsb, int array_size, void* memp, IData fpi, IData start, IData count); extern void VL_WRITEF(const char* formatp, ...); extern void VL_FWRITEF(IData fpi, const char* formatp, ...); extern IData VL_FSCANF_IX(IData fpi, const char* formatp, ...); extern IData VL_SSCANF_IIX(int lbits, IData ld, const char* formatp, ...); extern IData VL_SSCANF_IQX(int lbits, QData ld, const char* formatp, ...); extern IData VL_SSCANF_IWX(int lbits, WDataInP lwp, const char* formatp, ...); extern void VL_SFORMAT_X(int obits, CData& destr, const char* formatp, ...); extern void VL_SFORMAT_X(int obits, SData& destr, const char* formatp, ...); extern void VL_SFORMAT_X(int obits, IData& destr, const char* formatp, ...); extern void VL_SFORMAT_X(int obits, QData& destr, const char* formatp, ...); extern void VL_SFORMAT_X(int obits, void* destp, const char* formatp, ...); extern IData VL_SYSTEM_IW(int lhswords, WDataInP lhsp); extern IData VL_SYSTEM_IQ(QData lhs); inline IData VL_SYSTEM_II(IData lhs) VL_MT_SAFE { return VL_SYSTEM_IQ(lhs); } extern IData VL_TESTPLUSARGS_I(const char* formatp); extern const char* vl_mc_scan_plusargs(const char* prefixp); // PLIish //========================================================================= // Base macros /// Return true if data[bit] set; not 0/1 return, but 0/non-zero return. #define VL_BITISSET_I(data,bit) ((data) & (VL_UL(1) << VL_BITBIT_I(bit))) #define VL_BITISSET_Q(data,bit) ((data) & (VL_ULL(1) << VL_BITBIT_Q(bit))) #define VL_BITISSET_E(data,bit) ((data) & (VL_EUL(1) << VL_BITBIT_E(bit))) #define VL_BITISSET_W(data,bit) ((data)[VL_BITWORD_E(bit)] & (VL_EUL(1) << VL_BITBIT_E(bit))) #define VL_BITISSETLIMIT_W(data,width,bit) (((bit) < (width)) && VL_BITISSET_W(data,bit)) /// Shift appropriate word by bit. Does not account for wrapping between two words #define VL_BITRSHIFT_W(data,bit) ((data)[VL_BITWORD_E(bit)] >> VL_BITBIT_E(bit)) /// Create two 32-bit words from quadword /// WData is always at least 2 words; does not clean upper bits #define VL_SET_WQ(owp,data) { (owp)[0] = static_cast<IData>(data); \ (owp)[1] = static_cast<IData>((data) >> VL_EDATASIZE); } #define VL_SET_WI(owp,data) { (owp)[0] = static_cast<IData>(data); (owp)[1] = 0; } #define VL_SET_QW(lwp) \ ( (static_cast<QData>((lwp)[0])) \ | (static_cast<QData>((lwp)[1]) << (static_cast<QData>(VL_EDATASIZE)) )) #define _VL_SET_QII(ld,rd) ((static_cast<QData>(ld)<<VL_ULL(32)) | static_cast<QData>(rd)) /// Return FILE* from IData extern FILE* VL_CVT_I_FP(IData lhs); // Use a union to avoid cast-to-different-size warnings /// Return void* from QData static inline void* VL_CVT_Q_VP(QData lhs) VL_PURE { union { void* fp; QData q; } u; u.q=lhs; return u.fp; } /// Return QData from void* static inline QData VL_CVT_VP_Q(void* fp) VL_PURE { union { void* fp; QData q; } u; u.q=0; u.fp=fp; return u.q; } /// Return double from QData (bits, not numerically) static inline double VL_CVT_D_Q(QData lhs) VL_PURE { union { double d; QData q; } u; u.q=lhs; return u.d; } /// Return QData from double (bits, not numerically) static inline QData VL_CVT_Q_D(double lhs) VL_PURE { union { double d; QData q; } u; u.d=lhs; return u.q; } /// Return double from QData (numeric) static inline double VL_ITOR_D_I(IData lhs) VL_PURE { return static_cast<double>(static_cast<vlsint32_t>(lhs)); } /// Return QData from double (numeric) static inline IData VL_RTOI_I_D(double lhs) VL_PURE { return static_cast<vlsint32_t>(VL_TRUNC(lhs)); } /// Return QData from double (numeric) static inline IData VL_RTOIROUND_I_D(double lhs) VL_PURE { return static_cast<vlsint32_t>(VL_ROUND(lhs)); } // Sign extend such that if MSB set, we get ffff_ffff, else 0s // (Requires clean input) #define VL_SIGN_I(nbits,lhs) ((lhs) >> VL_BITBIT_I((nbits) - VL_UL(1))) #define VL_SIGN_Q(nbits,lhs) ((lhs) >> VL_BITBIT_Q((nbits) - VL_ULL(1))) #define VL_SIGN_E(nbits,lhs) ((lhs) >> VL_BITBIT_E((nbits) - VL_EUL(1))) #define VL_SIGN_W(nbits,rwp) \ ((rwp)[VL_BITWORD_E((nbits) - VL_EUL(1))] >> VL_BITBIT_E((nbits) - VL_EUL(1))) #define VL_SIGNONES_E(nbits, lhs) (-(VL_SIGN_E(nbits, lhs))) // Sign bit extended up to MSB, doesn't include unsigned portion // Optimization bug in GCC 3.3 returns different bitmasks to later states for static inline IData VL_EXTENDSIGN_I(int lbits, IData lhs) VL_PURE { return (-((lhs)&(VL_UL(1)<<(lbits-1)))); } static inline QData VL_EXTENDSIGN_Q(int lbits, QData lhs) VL_PURE { return (-((lhs)&(VL_ULL(1)<<(lbits-1)))); } // Debugging prints extern void _VL_DEBUG_PRINT_W(int lbits, WDataInP iwp); //========================================================================= // Pli macros extern int VL_TIME_STR_CONVERT(const char* strp) VL_PURE; #ifndef VL_TIME_PRECISION # ifdef VL_TIME_PRECISION_STR # define VL_TIME_PRECISION VL_TIME_STR_CONVERT(VL_STRINGIFY(VL_TIME_PRECISION_STR)) # else # define VL_TIME_PRECISION (-12) ///< Timescale units only for for VPI return - picoseconds # endif #endif #ifndef VL_TIME_UNIT # ifdef VL_TIME_UNIT_STR # define VL_TIME_UNIT VL_TIME_STR_CONVERT(VL_STRINGIFY(VL_TIME_PRECISION_STR)) # else # define VL_TIME_UNIT (-12) ///< Timescale units only for for VPI return - picoseconds # endif #endif #ifndef VL_TIME_MULTIPLIER # define VL_TIME_MULTIPLIER 1 #endif /// Return current simulation time #if defined(SYSTEMC_VERSION) && (SYSTEMC_VERSION>20011000) # define VL_TIME_I() (static_cast<IData>(sc_time_stamp().to_default_time_units()*VL_TIME_MULTIPLIER)) # define VL_TIME_Q() (static_cast<QData>(sc_time_stamp().to_default_time_units()*VL_TIME_MULTIPLIER)) # define VL_TIME_D() (static_cast<double>(sc_time_stamp().to_default_time_units()*VL_TIME_MULTIPLIER)) #else # define VL_TIME_I() (static_cast<IData>(sc_time_stamp()*VL_TIME_MULTIPLIER)) # define VL_TIME_Q() (static_cast<QData>(sc_time_stamp()*VL_TIME_MULTIPLIER)) # define VL_TIME_D() (static_cast<double>(sc_time_stamp()*VL_TIME_MULTIPLIER)) extern double sc_time_stamp(); #endif /// Evaluate expression if debug enabled #ifdef VL_DEBUG # define VL_DEBUG_IF(text) {if (VL_UNLIKELY(Verilated::debug())) {text}} #else # define VL_DEBUG_IF(text) #endif /// Collect coverage analysis for this line #ifndef SP_AUTO_COVER3 # define SP_AUTO_COVER3(what,file,line) #endif //========================================================================= // Functional macros/routines // These all take the form // VL_func_IW(bits, bits, op, op) // VL_func_WW(bits, bits, out, op, op) // The I/W indicates if it's a integer or wide for the output and each operand. // The bits indicate the bit width of the output and each operand. // If wide output, a temporary storage location is specified. //=================================================================== // SETTING OPERATORS // Output clean // EMIT_RULE: VL_CLEAN: oclean=clean; obits=lbits; #define VL_CLEAN_II(obits,lbits,lhs) ((lhs) & VL_MASK_I(obits)) #define VL_CLEAN_QQ(obits,lbits,lhs) ((lhs) & VL_MASK_Q(obits)) // EMIT_RULE: VL_ASSIGNCLEAN: oclean=clean; obits==lbits; #define VL_ASSIGNCLEAN_W(obits,owp,lwp) VL_CLEAN_WW((obits), (obits), (owp), (lwp)) static inline WDataOutP _VL_CLEAN_INPLACE_W(int obits, WDataOutP owp) VL_MT_SAFE { int words = VL_WORDS_I(obits); owp[words-1] &= VL_MASK_E(obits); return owp; } static inline WDataOutP VL_CLEAN_WW(int obits, int, WDataOutP owp, WDataInP lwp) VL_MT_SAFE { int words = VL_WORDS_I(obits); for (int i=0; (i < (words-1)); ++i) owp[i] = lwp[i]; owp[words-1] = lwp[words-1] & VL_MASK_E(obits); return owp; } static inline WDataOutP VL_ZERO_W(int obits, WDataOutP owp) VL_MT_SAFE { int words = VL_WORDS_I(obits); for (int i=0; i < words; ++i) owp[i] = 0; return owp; } static inline WDataOutP VL_ALLONES_W(int obits, WDataOutP owp) VL_MT_SAFE { int words = VL_WORDS_I(obits); for (int i = 0; i < (words - 1); ++i) owp[i] = ~VL_EUL(0); owp[words-1] = VL_MASK_E(obits); return owp; } // EMIT_RULE: VL_ASSIGN: oclean=rclean; obits==lbits; // For now, we always have a clean rhs. // Note: If a ASSIGN isn't clean, use VL_ASSIGNCLEAN instead to do the same thing. static inline WDataOutP VL_ASSIGN_W(int obits, WDataOutP owp, WDataInP lwp) VL_MT_SAFE { int words = VL_WORDS_I(obits); for (int i=0; i < words; ++i) owp[i] = lwp[i]; return owp; } // EMIT_RULE: VL_ASSIGNBIT: rclean=clean; static inline void VL_ASSIGNBIT_II(int, int bit, CData& lhsr, IData rhs) VL_PURE { lhsr = ((lhsr & ~(VL_UL(1)<<VL_BITBIT_I(bit))) | (rhs<<VL_BITBIT_I(bit))); } static inline void VL_ASSIGNBIT_II(int, int bit, SData& lhsr, IData rhs) VL_PURE { lhsr = ((lhsr & ~(VL_UL(1)<<VL_BITBIT_I(bit))) | (rhs<<VL_BITBIT_I(bit))); } static inline void VL_ASSIGNBIT_II(int, int bit, IData& lhsr, IData rhs) VL_PURE { lhsr = ((lhsr & ~(VL_UL(1)<<VL_BITBIT_I(bit))) | (rhs<<VL_BITBIT_I(bit))); } static inline void VL_ASSIGNBIT_QI(int, int bit, QData& lhsr, QData rhs) VL_PURE { lhsr = ((lhsr & ~(VL_ULL(1)<<VL_BITBIT_Q(bit))) | (static_cast<QData>(rhs) << VL_BITBIT_Q(bit))); } static inline void VL_ASSIGNBIT_WI(int, int bit, WDataOutP owp, IData rhs) VL_MT_SAFE { EData orig = owp[VL_BITWORD_E(bit)]; owp[VL_BITWORD_E(bit)] = ((orig & ~(VL_EUL(1) << VL_BITBIT_E(bit))) | (static_cast<EData>(rhs) << VL_BITBIT_E(bit))); } // Alternative form that is an instruction faster when rhs is constant one. static inline void VL_ASSIGNBIT_IO(int, int bit, CData& lhsr, IData) VL_PURE { lhsr = (lhsr | (VL_UL(1) << VL_BITBIT_I(bit))); } static inline void VL_ASSIGNBIT_IO(int, int bit, SData& lhsr, IData) VL_PURE { lhsr = (lhsr | (VL_UL(1) << VL_BITBIT_I(bit))); } static inline void VL_ASSIGNBIT_IO(int, int bit, IData& lhsr, IData) VL_PURE { lhsr = (lhsr | (VL_UL(1) << VL_BITBIT_I(bit))); } static inline void VL_ASSIGNBIT_QO(int, int bit, QData& lhsr, IData) VL_PURE { lhsr = (lhsr | (VL_ULL(1) << VL_BITBIT_Q(bit))); } static inline void VL_ASSIGNBIT_WO(int, int bit, WDataOutP owp, IData) VL_MT_SAFE { EData orig = owp[VL_BITWORD_E(bit)]; owp[VL_BITWORD_E(bit)] = (orig | (VL_EUL(1) << VL_BITBIT_E(bit))); } //=================================================================== // SYSTEMC OPERATORS // Copying verilog format to systemc integers and bit vectors. // Get a SystemC variable #define VL_ASSIGN_ISI(obits,vvar,svar) { (vvar) = VL_CLEAN_II((obits), (obits), (svar).read()); } #define VL_ASSIGN_QSQ(obits,vvar,svar) { (vvar) = VL_CLEAN_QQ((obits), (obits), (svar).read()); } #define VL_ASSIGN_ISW(obits,od,svar) { \ (od) = ((svar).read().get_word(0)) & VL_MASK_I(obits); \ } #define VL_ASSIGN_QSW(obits,od,svar) { \ (od) = ((static_cast<QData>((svar).read().get_word(1)))<<VL_IDATASIZE \ | (svar).read().get_word(0)) \ & VL_MASK_Q(obits); \ } #define VL_ASSIGN_WSW(obits,owp,svar) { \ int words = VL_WORDS_I(obits); \ for (int i=0; i < words; ++i) (owp)[i] = (svar).read().get_word(i); \ (owp)[words-1] &= VL_MASK_E(obits); \ } #define VL_ASSIGN_ISU(obits,vvar,svar) { (vvar) = VL_CLEAN_II((obits), (obits), (svar).read().to_uint()); } #define VL_ASSIGN_QSU(obits,vvar,svar) { (vvar) = VL_CLEAN_QQ((obits), (obits), (svar).read().to_uint64()); } #define VL_ASSIGN_WSB(obits,owp,svar) { \ int words = VL_WORDS_I(obits); \ sc_biguint<(obits)> _butemp = (svar).read(); \ for (int i=0; i < words; ++i) { \ int msb = ((i + 1) * VL_IDATASIZE) - 1; \ msb = (msb >= (obits)) ? ((obits)-1) : msb; \ (owp)[i] = _butemp.range(msb, i * VL_IDATASIZE).to_uint(); \ } \ (owp)[words-1] &= VL_MASK_E(obits); \ } // Copying verilog format from systemc integers and bit vectors. // Set a SystemC variable #define VL_ASSIGN_SII(obits,svar,vvar) { (svar).write(vvar); } #define VL_ASSIGN_SQQ(obits,svar,vvar) { (svar).write(vvar); } #define VL_ASSIGN_SWI(obits,svar,rd) { \ sc_bv<(obits)> _bvtemp; \ _bvtemp.set_word(0, (rd)); \ (svar).write(_bvtemp); \ } #define VL_ASSIGN_SWQ(obits,svar,rd) { \ sc_bv<(obits)> _bvtemp; \ _bvtemp.set_word(0, static_cast<IData>(rd)); \ _bvtemp.set_word(1, static_cast<IData>((rd) >> VL_IDATASIZE)); \ (svar).write(_bvtemp); \ } #define VL_ASSIGN_SWW(obits,svar,rwp) { \ sc_bv<(obits)> _bvtemp; \ for (int i=0; i < VL_WORDS_I(obits); ++i) _bvtemp.set_word(i, (rwp)[i]); \ (svar).write(_bvtemp); \ } #define VL_ASSIGN_SUI(obits,svar,rd) { (svar).write(rd); } #define VL_ASSIGN_SUQ(obits,svar,rd) { (svar).write(rd); } #define VL_ASSIGN_SBI(obits,svar,rd) { (svar).write(rd); } #define VL_ASSIGN_SBQ(obits,svar,rd) { (svar).write(rd); } #define VL_ASSIGN_SBW(obits,svar,rwp) { \ sc_biguint<(obits)> _butemp; \ for (int i=0; i < VL_WORDS_I(obits); ++i) { \ int msb = ((i + 1) * VL_IDATASIZE) - 1; \ msb = (msb >= (obits)) ? ((obits)-1) : msb; \ _butemp.range(msb, i * VL_IDATASIZE) = (rwp)[i]; \ } \ (svar).write(_butemp); \ } //=================================================================== // Extending sizes // CAREFUL, we're width changing, so obits!=lbits // Right must be clean because otherwise size increase would pick up bad bits // EMIT_RULE: VL_EXTEND: oclean=clean; rclean==clean; #define VL_EXTEND_II(obits,lbits,lhs) ((lhs)) #define VL_EXTEND_QI(obits,lbits,lhs) (static_cast<QData>(lhs)) #define VL_EXTEND_QQ(obits,lbits,lhs) ((lhs)) static inline WDataOutP VL_EXTEND_WI(int obits, int, WDataOutP owp, IData ld) VL_MT_SAFE { // Note for extracts that obits != lbits owp[0] = ld; for (int i = 1; i < VL_WORDS_I(obits); ++i) owp[i] = 0; return owp; } static inline WDataOutP VL_EXTEND_WQ(int obits, int, WDataOutP owp, QData ld) VL_MT_SAFE { VL_SET_WQ(owp, ld); for (int i = VL_WQ_WORDS_E; i < VL_WORDS_I(obits); ++i) owp[i] = 0; return owp; } static inline WDataOutP VL_EXTEND_WW(int obits, int lbits, WDataOutP owp, WDataInP lwp) VL_MT_SAFE { for (int i = 0; i < VL_WORDS_I(lbits); ++i) owp[i] = lwp[i]; for (int i = VL_WORDS_I(lbits); i < VL_WORDS_I(obits); ++i) owp[i] = 0; return owp; } // EMIT_RULE: VL_EXTENDS: oclean=*dirty*; obits=lbits; // Sign extension; output dirty static inline IData VL_EXTENDS_II(int, int lbits, IData lhs) VL_PURE { return VL_EXTENDSIGN_I(lbits, lhs) | lhs; } static inline QData VL_EXTENDS_QI(int, int lbits, QData lhs/*Q_as_need_extended*/) VL_PURE { return VL_EXTENDSIGN_Q(lbits, lhs) | lhs; } static inline QData VL_EXTENDS_QQ(int, int lbits, QData lhs) VL_PURE { return VL_EXTENDSIGN_Q(lbits, lhs) | lhs; } static inline WDataOutP VL_EXTENDS_WI(int obits, int lbits, WDataOutP owp, IData ld) VL_MT_SAFE { EData sign = VL_SIGNONES_E(lbits, static_cast<EData>(ld)); owp[0] = ld | (sign & ~VL_MASK_E(lbits)); for (int i = 1; i < VL_WORDS_I(obits); ++i) owp[i] = sign; return owp; } static inline WDataOutP VL_EXTENDS_WQ(int obits, int lbits, WDataOutP owp, QData ld) VL_MT_SAFE { VL_SET_WQ(owp, ld); EData sign = VL_SIGNONES_E(lbits, owp[1]); owp[1] |= sign & ~VL_MASK_E(lbits); for (int i = VL_WQ_WORDS_E; i < VL_WORDS_I(obits); ++i) owp[i] = sign; return owp; } static inline WDataOutP VL_EXTENDS_WW(int obits, int lbits, WDataOutP owp, WDataInP lwp) VL_MT_SAFE { for (int i = 0; i < VL_WORDS_I(lbits)-1; ++i) owp[i] = lwp[i]; int lmsw = VL_WORDS_I(lbits) - 1; EData sign = VL_SIGNONES_E(lbits, lwp[lmsw]); owp[lmsw] = lwp[lmsw] | (sign & ~VL_MASK_E(lbits)); for (int i = VL_WORDS_I(lbits); i < VL_WORDS_I(obits); ++i) owp[i] = sign; return owp; } //=================================================================== // REDUCTION OPERATORS // EMIT_RULE: VL_REDAND: oclean=clean; lclean==clean; obits=1; #define VL_REDAND_II(obits,lbits,lhs) ((lhs) == VL_MASK_I(lbits)) #define VL_REDAND_IQ(obits,lbits,lhs) ((lhs) == VL_MASK_Q(lbits)) static inline IData VL_REDAND_IW(int, int lbits, WDataInP lwp) VL_MT_SAFE { int words = VL_WORDS_I(lbits); EData combine = lwp[0]; for (int i = 1; i < words - 1; ++i) combine &= lwp[i]; combine &= ~VL_MASK_E(lbits) | lwp[words-1]; return ((~combine)==0); } // EMIT_RULE: VL_REDOR: oclean=clean; lclean==clean; obits=1; #define VL_REDOR_I(lhs) ((lhs)!=0) #define VL_REDOR_Q(lhs) ((lhs)!=0) static inline IData VL_REDOR_W(int words, WDataInP lwp) VL_MT_SAFE { EData equal = 0; for (int i=0; i < words; ++i) equal |= lwp[i]; return (equal != 0); } // EMIT_RULE: VL_REDXOR: oclean=dirty; obits=1; static inline IData VL_REDXOR_2(IData r) VL_PURE { // Experiments show VL_REDXOR_2 is faster than __builtin_parityl r=(r^(r>>1)); return r; } static inline IData VL_REDXOR_4(IData r) VL_PURE { #if defined(__GNUC__) && (__GNUC__ >= 4) && !defined(VL_NO_BUILTINS) return __builtin_parityl(r); #else r=(r^(r>>1)); r=(r^(r>>2)); return r; #endif } static inline IData VL_REDXOR_8(IData r) VL_PURE { #if defined(__GNUC__) && (__GNUC__ >= 4) && !defined(VL_NO_BUILTINS) return __builtin_parityl(r); #else r=(r^(r>>1)); r=(r^(r>>2)); r=(r^(r>>4)); return r; #endif } static inline IData VL_REDXOR_16(IData r) VL_PURE { #if defined(__GNUC__) && (__GNUC__ >= 4) && !defined(VL_NO_BUILTINS) return __builtin_parityl(r); #else r=(r^(r>>1)); r=(r^(r>>2)); r=(r^(r>>4)); r=(r^(r>>8)); return r; #endif } static inline IData VL_REDXOR_32(IData r) VL_PURE { #if defined(__GNUC__) && (__GNUC__ >= 4) && !defined(VL_NO_BUILTINS) return __builtin_parityl(r); #else r=(r^(r>>1)); r=(r^(r>>2)); r=(r^(r>>4)); r=(r^(r>>8)); r=(r^(r>>16)); return r; #endif } static inline IData VL_REDXOR_64(QData r) VL_PURE { #if defined(__GNUC__) && (__GNUC__ >= 4) && !defined(VL_NO_BUILTINS) return __builtin_parityll(r); #else r=(r^(r>>1)); r=(r^(r>>2)); r=(r^(r>>4)); r=(r^(r>>8)); r=(r^(r>>16)); r=(r^(r>>32)); return static_cast<IData>(r); #endif } static inline IData VL_REDXOR_W(int words, WDataInP lwp) VL_MT_SAFE { EData r = lwp[0]; for (int i=1; i < words; ++i) r ^= lwp[i]; return VL_REDXOR_32(r); } // EMIT_RULE: VL_COUNTONES_II: oclean = false; lhs clean static inline IData VL_COUNTONES_I(IData lhs) VL_PURE { // This is faster than __builtin_popcountl IData r = lhs - ((lhs >> 1) & 033333333333) - ((lhs >> 2) & 011111111111); r = (r + (r>>3)) & 030707070707; r = (r + (r>>6)); r = (r + (r>>12) + (r>>24)) & 077; return r; } static inline IData VL_COUNTONES_Q(QData lhs) VL_PURE { return VL_COUNTONES_I(static_cast<IData>(lhs)) + VL_COUNTONES_I(static_cast<IData>(lhs>>32)); } #define VL_COUNTONES_E VL_COUNTONES_I static inline IData VL_COUNTONES_W(int words, WDataInP lwp) VL_MT_SAFE { EData r = 0; for (int i = 0; i < words; ++i) r += VL_COUNTONES_E(lwp[i]); return r; } static inline IData VL_ONEHOT_I(IData lhs) VL_PURE { return (((lhs & (lhs-1))==0) & (lhs!=0)); } static inline IData VL_ONEHOT_Q(QData lhs) VL_PURE { return (((lhs & (lhs-1))==0) & (lhs!=0)); } static inline IData VL_ONEHOT_W(int words, WDataInP lwp) VL_MT_SAFE { EData one = 0; for (int i=0; (i < words); ++i) { if (lwp[i]) { if (one) return 0; one = 1; if (lwp[i] & (lwp[i]-1)) return 0; } } return one; } static inline IData VL_ONEHOT0_I(IData lhs) VL_PURE { return ((lhs & (lhs-1))==0); } static inline IData VL_ONEHOT0_Q(QData lhs) VL_PURE { return ((lhs & (lhs-1))==0); } static inline IData VL_ONEHOT0_W(int words, WDataInP lwp) VL_MT_SAFE { bool one = false; for (int i=0; (i < words); ++i) { if (lwp[i]) { if (one) return 0; one = true; if (lwp[i] & (lwp[i]-1)) return 0; } } return 1; } static inline IData VL_CLOG2_I(IData lhs) VL_PURE { // There are faster algorithms, or fls GCC4 builtins, but rarely used if (VL_UNLIKELY(!lhs)) return 0; lhs--; int shifts = 0; for (; lhs!=0; ++shifts) lhs = lhs >> 1; return shifts; } static inline IData VL_CLOG2_Q(QData lhs) VL_PURE { if (VL_UNLIKELY(!lhs)) return 0; lhs--; int shifts = 0; for (; lhs!=0; ++shifts) lhs = lhs >> VL_ULL(1); return shifts; } static inline IData VL_CLOG2_W(int words, WDataInP lwp) VL_MT_SAFE { EData adjust = (VL_COUNTONES_W(words, lwp) == 1) ? 0 : 1; for (int i=words-1; i>=0; --i) { if (VL_UNLIKELY(lwp[i])) { // Shorter worst case if predict not taken for (int bit = VL_EDATASIZE - 1; bit >= 0; --bit) { if (VL_UNLIKELY(VL_BITISSET_E(lwp[i], bit))) { return i * VL_EDATASIZE + bit + adjust; } } // Can't get here - one bit must be set } } return 0; } static inline IData VL_MOSTSETBITP1_W(int words, WDataInP lwp) VL_MT_SAFE { // MSB set bit plus one; similar to FLS. 0=value is zero for (int i=words-1; i>=0; --i) { if (VL_UNLIKELY(lwp[i])) { // Shorter worst case if predict not taken for (int bit = VL_EDATASIZE - 1; bit >= 0; --bit) { if (VL_UNLIKELY(VL_BITISSET_E(lwp[i], bit))) { return i * VL_EDATASIZE + bit + 1; } } // Can't get here - one bit must be set } } return 0; } //=================================================================== // SIMPLE LOGICAL OPERATORS // EMIT_RULE: VL_AND: oclean=lclean||rclean; obits=lbits; lbits==rbits; static inline WDataOutP VL_AND_W(int words, WDataOutP owp, WDataInP lwp, WDataInP rwp) VL_MT_SAFE { for (int i=0; (i < words); ++i) owp[i] = (lwp[i] & rwp[i]); return owp; } // EMIT_RULE: VL_OR: oclean=lclean&&rclean; obits=lbits; lbits==rbits; static inline WDataOutP VL_OR_W(int words, WDataOutP owp, WDataInP lwp, WDataInP rwp) VL_MT_SAFE { for (int i=0; (i < words); ++i) owp[i] = (lwp[i] | rwp[i]); return owp; } // EMIT_RULE: VL_CHANGEXOR: oclean=1; obits=32; lbits==rbits; static inline IData VL_CHANGEXOR_W(int words, WDataInP lwp, WDataInP rwp) VL_MT_SAFE { IData od = 0; for (int i=0; (i < words); ++i) od |= (lwp[i] ^ rwp[i]); return(od); } // EMIT_RULE: VL_XOR: oclean=lclean&&rclean; obits=lbits; lbits==rbits; static inline WDataOutP VL_XOR_W(int words, WDataOutP owp, WDataInP lwp, WDataInP rwp) VL_MT_SAFE { for (int i=0; (i < words); ++i) owp[i] = (lwp[i] ^ rwp[i]); return owp; } // EMIT_RULE: VL_XNOR: oclean=dirty; obits=lbits; lbits==rbits; static inline WDataOutP VL_XNOR_W(int words, WDataOutP owp, WDataInP lwp, WDataInP rwp) VL_MT_SAFE { for (int i=0; (i < words); ++i) owp[i] = (lwp[i] ^ ~rwp[i]); return owp; } // EMIT_RULE: VL_NOT: oclean=dirty; obits=lbits; static inline WDataOutP VL_NOT_W(int words, WDataOutP owp, WDataInP lwp) VL_MT_SAFE { for (int i=0; i < words; ++i) owp[i] = ~(lwp[i]); return owp; } //========================================================================= // Logical comparisons // EMIT_RULE: VL_EQ: oclean=clean; lclean==clean; rclean==clean; obits=1; lbits==rbits; // EMIT_RULE: VL_NEQ: oclean=clean; lclean==clean; rclean==clean; obits=1; lbits==rbits; // EMIT_RULE: VL_LT: oclean=clean; lclean==clean; rclean==clean; obits=1; lbits==rbits; // EMIT_RULE: VL_GT: oclean=clean; lclean==clean; rclean==clean; obits=1; lbits==rbits; // EMIT_RULE: VL_GTE: oclean=clean; lclean==clean; rclean==clean; obits=1; lbits==rbits; // EMIT_RULE: VL_LTE: oclean=clean; lclean==clean; rclean==clean; obits=1; lbits==rbits; #define VL_NEQ_W(words,lwp,rwp) (!VL_EQ_W(words,lwp,rwp)) #define VL_LT_W(words,lwp,rwp) (_VL_CMP_W(words,lwp,rwp)<0) #define VL_LTE_W(words,lwp,rwp) (_VL_CMP_W(words,lwp,rwp)<=0) #define VL_GT_W(words,lwp,rwp) (_VL_CMP_W(words,lwp,rwp)>0) #define VL_GTE_W(words,lwp,rwp) (_VL_CMP_W(words,lwp,rwp)>=0) // Output clean, <lhs> AND <rhs> MUST BE CLEAN static inline IData VL_EQ_W(int words, WDataInP lwp, WDataInP rwp) VL_MT_SAFE { EData nequal = 0; for (int i=0; (i < words); ++i) nequal |= (lwp[i] ^ rwp[i]); return (nequal==0); } // Internal usage static inline int _VL_CMP_W(int words, WDataInP lwp, WDataInP rwp) VL_MT_SAFE { for (int i=words-1; i>=0; --i) { if (lwp[i] > rwp[i]) return 1; if (lwp[i] < rwp[i]) return -1; } return(0); // == } #define VL_LTS_IWW(obits,lbits,rbbits,lwp,rwp) (_VL_CMPS_W(lbits,lwp,rwp)<0) #define VL_LTES_IWW(obits,lbits,rbits,lwp,rwp) (_VL_CMPS_W(lbits,lwp,rwp)<=0) #define VL_GTS_IWW(obits,lbits,rbits,lwp,rwp) (_VL_CMPS_W(lbits,lwp,rwp)>0) #define VL_GTES_IWW(obits,lbits,rbits,lwp,rwp) (_VL_CMPS_W(lbits,lwp,rwp)>=0) static inline IData VL_GTS_III(int, int lbits, int, IData lhs, IData rhs) VL_PURE { // For lbits==32, this becomes just a single instruction, otherwise ~5. // GCC 3.3.4 sign extension bugs on AMD64 architecture force us to use quad logic vlsint64_t lhs_signed = VL_EXTENDS_QQ(64, lbits, lhs); // Q for gcc vlsint64_t rhs_signed = VL_EXTENDS_QQ(64, lbits, rhs); // Q for gcc return lhs_signed > rhs_signed; } static inline IData VL_GTS_IQQ(int, int lbits, int, QData lhs, QData rhs) VL_PURE { vlsint64_t lhs_signed = VL_EXTENDS_QQ(64, lbits, lhs); vlsint64_t rhs_signed = VL_EXTENDS_QQ(64, lbits, rhs); return lhs_signed > rhs_signed; } static inline IData VL_GTES_III(int, int lbits, int, IData lhs, IData rhs) VL_PURE { vlsint64_t lhs_signed = VL_EXTENDS_QQ(64, lbits, lhs); // Q for gcc vlsint64_t rhs_signed = VL_EXTENDS_QQ(64, lbits, rhs); // Q for gcc return lhs_signed >= rhs_signed; } static inline IData VL_GTES_IQQ(int, int lbits, int, QData lhs, QData rhs) VL_PURE { vlsint64_t lhs_signed = VL_EXTENDS_QQ(64, lbits, lhs); vlsint64_t rhs_signed = VL_EXTENDS_QQ(64, lbits, rhs); return lhs_signed >= rhs_signed; } static inline IData VL_LTS_III(int, int lbits, int, IData lhs, IData rhs) VL_PURE { vlsint64_t lhs_signed = VL_EXTENDS_QQ(64, lbits, lhs); // Q for gcc vlsint64_t rhs_signed = VL_EXTENDS_QQ(64, lbits, rhs); // Q for gcc return lhs_signed < rhs_signed; } static inline IData VL_LTS_IQQ(int, int lbits, int, QData lhs, QData rhs) VL_PURE { vlsint64_t lhs_signed = VL_EXTENDS_QQ(64, lbits, lhs); vlsint64_t rhs_signed = VL_EXTENDS_QQ(64, lbits, rhs); return lhs_signed < rhs_signed; } static inline IData VL_LTES_III(int, int lbits, int, IData lhs, IData rhs) VL_PURE { vlsint64_t lhs_signed = VL_EXTENDS_QQ(64, lbits, lhs); // Q for gcc vlsint64_t rhs_signed = VL_EXTENDS_QQ(64, lbits, rhs); // Q for gcc return lhs_signed <= rhs_signed; } static inline IData VL_LTES_IQQ(int, int lbits, int, QData lhs, QData rhs) VL_PURE { vlsint64_t lhs_signed = VL_EXTENDS_QQ(64, lbits, lhs); vlsint64_t rhs_signed = VL_EXTENDS_QQ(64, lbits, rhs); return lhs_signed <= rhs_signed; } static inline int _VL_CMPS_W(int lbits, WDataInP lwp, WDataInP rwp) VL_MT_SAFE { int words = VL_WORDS_I(lbits); int i = words-1; // We need to flip sense if negative comparison EData lsign = VL_SIGN_E(lbits, lwp[i]); EData rsign = VL_SIGN_E(lbits, rwp[i]); if (!lsign && rsign) return 1; // + > - if (lsign && !rsign) return -1; // - < + for (; i>=0; --i) { if (lwp[i] > rwp[i]) return 1; if (lwp[i] < rwp[i]) return -1; } return(0); // == } //========================================================================= // Math // Optimization bug in GCC 2.96 and presumably all-pre GCC 3 versions need this workaround, // we can't just //# define VL_NEGATE_I(data) (-(data)) static inline IData VL_NEGATE_I(IData data) VL_PURE { return -data; } static inline QData VL_NEGATE_Q(QData data) VL_PURE { return -data; } static inline EData VL_NEGATE_E(EData data) VL_PURE { return -data; } static inline WDataOutP VL_NEGATE_W(int words, WDataOutP owp, WDataInP lwp) VL_MT_SAFE { EData carry = 1; for (int i = 0; i < words; ++i) { owp[i] = ~lwp[i] + carry; carry = (owp[i] < ~lwp[i]); } return owp; } // EMIT_RULE: VL_MUL: oclean=dirty; lclean==clean; rclean==clean; // EMIT_RULE: VL_DIV: oclean=dirty; lclean==clean; rclean==clean; // EMIT_RULE: VL_MODDIV: oclean=dirty; lclean==clean; rclean==clean; #define VL_DIV_III(lbits,lhs,rhs) (((rhs)==0)?0:(lhs)/(rhs)) #define VL_DIV_QQQ(lbits,lhs,rhs) (((rhs)==0)?0:(lhs)/(rhs)) #define VL_DIV_WWW(lbits,owp,lwp,rwp) (_vl_moddiv_w(lbits,owp,lwp,rwp,0)) #define VL_MODDIV_III(lbits,lhs,rhs) (((rhs)==0)?0:(lhs)%(rhs)) #define VL_MODDIV_QQQ(lbits,lhs,rhs) (((rhs)==0)?0:(lhs)%(rhs)) #define VL_MODDIV_WWW(lbits,owp,lwp,rwp) (_vl_moddiv_w(lbits,owp,lwp,rwp,1)) static inline WDataOutP VL_ADD_W(int words, WDataOutP owp, WDataInP lwp, WDataInP rwp) VL_MT_SAFE { QData carry = 0; for (int i = 0; i < words; ++i) { carry = carry + static_cast<QData>(lwp[i]) + static_cast<QData>(rwp[i]); owp[i] = (carry & VL_ULL(0xffffffff)); carry = (carry >> VL_ULL(32)) & VL_ULL(0xffffffff); } // Last output word is dirty return owp; } static inline WDataOutP VL_SUB_W(int words, WDataOutP owp, WDataInP lwp, WDataInP rwp) VL_MT_SAFE { QData carry = 0; for (int i = 0; i < words; ++i) { carry = (carry + static_cast<QData>(lwp[i]) + static_cast<QData>(static_cast<IData>(~rwp[i]))); if (i == 0) ++carry; // Negation of rwp owp[i] = (carry & VL_ULL(0xffffffff)); carry = (carry >> VL_ULL(32)) & VL_ULL(0xffffffff); } // Last output word is dirty return owp; } static inline WDataOutP VL_MUL_W(int words, WDataOutP owp, WDataInP lwp, WDataInP rwp) VL_MT_SAFE { for (int i=0; i<words; ++i) owp[i] = 0; for (int lword=0; lword<words; ++lword) { for (int rword=0; rword<words; ++rword) { QData mul = static_cast<QData>(lwp[lword]) * static_cast<QData>(rwp[rword]); for (int qword=lword+rword; qword<words; ++qword) { mul += static_cast<QData>(owp[qword]); owp[qword] = (mul & VL_ULL(0xffffffff)); mul = (mul >> VL_ULL(32)) & VL_ULL(0xffffffff); } } } // Last output word is dirty return owp; } static inline IData VL_MULS_III(int, int lbits, int, IData lhs, IData rhs) VL_PURE { vlsint32_t lhs_signed = VL_EXTENDS_II(32, lbits, lhs); vlsint32_t rhs_signed = VL_EXTENDS_II(32, lbits, rhs); return lhs_signed * rhs_signed; } static inline QData VL_MULS_QQQ(int, int lbits, int, QData lhs, QData rhs) VL_PURE { vlsint64_t lhs_signed = VL_EXTENDS_QQ(64, lbits, lhs); vlsint64_t rhs_signed = VL_EXTENDS_QQ(64, lbits, rhs); return lhs_signed * rhs_signed; } static inline WDataOutP VL_MULS_WWW(int, int lbits, int, WDataOutP owp, WDataInP lwp, WDataInP rwp) VL_MT_SAFE { int words = VL_WORDS_I(lbits); // cppcheck-suppress variableScope WData lwstore[VL_MULS_MAX_WORDS]; // Fixed size, as MSVC++ doesn't allow [words] here // cppcheck-suppress variableScope WData rwstore[VL_MULS_MAX_WORDS]; WDataInP lwusp = lwp; WDataInP rwusp = rwp; EData lneg = VL_SIGN_E(lbits, lwp[words - 1]); if (lneg) { // Negate lhs lwusp = lwstore; VL_NEGATE_W(words, lwstore, lwp); lwstore[words - 1] &= VL_MASK_E(lbits); // Clean it } EData rneg = VL_SIGN_E(lbits, rwp[words - 1]); if (rneg) { // Negate rhs rwusp = rwstore; VL_NEGATE_W(words, rwstore, rwp); rwstore[words - 1] &= VL_MASK_E(lbits); // Clean it } VL_MUL_W(words, owp, lwusp, rwusp); owp[words - 1] &= VL_MASK_E( lbits); // Clean. Note it's ok for the multiply to overflow into the sign bit if ((lneg ^ rneg) & 1) { // Negate output (not using NEGATE, as owp==lwp) QData carry = 0; for (int i = 0; i < words; ++i) { carry = carry + static_cast<QData>(static_cast<IData>(~owp[i])); if (i == 0) ++carry; // Negation of temp2 owp[i] = (carry & VL_ULL(0xffffffff)); carry = (carry >> VL_ULL(32)) & VL_ULL(0xffffffff); } // Not needed: owp[words-1] |= 1<<VL_BITBIT_E(lbits-1); // Set sign bit } // Last output word is dirty return owp; } static inline IData VL_DIVS_III(int lbits, IData lhs, IData rhs) VL_PURE { if (VL_UNLIKELY(rhs == 0)) return 0; vlsint32_t lhs_signed = VL_EXTENDS_II(VL_IDATASIZE, lbits, lhs); vlsint32_t rhs_signed = VL_EXTENDS_II(VL_IDATASIZE, lbits, rhs); return lhs_signed / rhs_signed; } static inline QData VL_DIVS_QQQ(int lbits, QData lhs, QData rhs) VL_PURE { if (VL_UNLIKELY(rhs == 0)) return 0; vlsint64_t lhs_signed = VL_EXTENDS_QQ(VL_QUADSIZE, lbits, lhs); vlsint64_t rhs_signed = VL_EXTENDS_QQ(VL_QUADSIZE, lbits, rhs); return lhs_signed / rhs_signed; } static inline IData VL_MODDIVS_III(int lbits, IData lhs, IData rhs) VL_PURE { if (VL_UNLIKELY(rhs == 0)) return 0; vlsint32_t lhs_signed = VL_EXTENDS_II(VL_IDATASIZE, lbits, lhs); vlsint32_t rhs_signed = VL_EXTENDS_II(VL_IDATASIZE, lbits, rhs); return lhs_signed % rhs_signed; } static inline QData VL_MODDIVS_QQQ(int lbits, QData lhs, QData rhs) VL_PURE { if (VL_UNLIKELY(rhs == 0)) return 0; vlsint64_t lhs_signed = VL_EXTENDS_QQ(VL_QUADSIZE, lbits, lhs); vlsint64_t rhs_signed = VL_EXTENDS_QQ(VL_QUADSIZE, lbits, rhs); return lhs_signed % rhs_signed; } static inline WDataOutP VL_DIVS_WWW(int lbits, WDataOutP owp, WDataInP lwp, WDataInP rwp) VL_MT_SAFE { int words = VL_WORDS_I(lbits); EData lsign = VL_SIGN_E(lbits, lwp[words - 1]); EData rsign = VL_SIGN_E(lbits, rwp[words - 1]); // cppcheck-suppress variableScope WData lwstore[VL_MULS_MAX_WORDS]; // Fixed size, as MSVC++ doesn't allow [words] here // cppcheck-suppress variableScope WData rwstore[VL_MULS_MAX_WORDS]; WDataInP ltup = lwp; WDataInP rtup = rwp; if (lsign) { ltup = _VL_CLEAN_INPLACE_W(lbits, VL_NEGATE_W(VL_WORDS_I(lbits), lwstore, lwp)); } if (rsign) { rtup = _VL_CLEAN_INPLACE_W(lbits, VL_NEGATE_W(VL_WORDS_I(lbits), rwstore, rwp)); } if ((lsign && !rsign) || (!lsign && rsign)) { WData qNoSign[VL_MULS_MAX_WORDS]; VL_DIV_WWW(lbits, qNoSign, ltup, rtup); _VL_CLEAN_INPLACE_W(lbits, VL_NEGATE_W(VL_WORDS_I(lbits), owp, qNoSign)); return owp; } else { return VL_DIV_WWW(lbits, owp, ltup, rtup); } } static inline WDataOutP VL_MODDIVS_WWW(int lbits, WDataOutP owp, WDataInP lwp, WDataInP rwp) VL_MT_SAFE { int words = VL_WORDS_I(lbits); EData lsign = VL_SIGN_E(lbits, lwp[words - 1]); EData rsign = VL_SIGN_E(lbits, rwp[words - 1]); // cppcheck-suppress variableScope WData lwstore[VL_MULS_MAX_WORDS]; // Fixed size, as MSVC++ doesn't allow [words] here // cppcheck-suppress variableScope WData rwstore[VL_MULS_MAX_WORDS]; WDataInP ltup = lwp; WDataInP rtup = rwp; if (lsign) { ltup = _VL_CLEAN_INPLACE_W(lbits, VL_NEGATE_W(VL_WORDS_I(lbits), lwstore, lwp)); } if (rsign) { rtup = _VL_CLEAN_INPLACE_W(lbits, VL_NEGATE_W(VL_WORDS_I(lbits), rwstore, rwp)); } if (lsign) { // Only dividend sign matters for modulus WData qNoSign[VL_MULS_MAX_WORDS]; VL_MODDIV_WWW(lbits, qNoSign, ltup, rtup); _VL_CLEAN_INPLACE_W(lbits, VL_NEGATE_W(VL_WORDS_I(lbits), owp, qNoSign)); return owp; } else { return VL_MODDIV_WWW(lbits, owp, ltup, rtup); } } #define VL_POW_IIQ(obits, lbits, rbits, lhs, rhs) VL_POW_QQQ(obits, lbits, rbits, lhs, rhs) #define VL_POW_IIW(obits, lbits, rbits, lhs, rwp) VL_POW_QQW(obits, lbits, rbits, lhs, rwp) #define VL_POW_QQI(obits, lbits, rbits, lhs, rhs) VL_POW_QQQ(obits, lbits, rbits, lhs, rhs) #define VL_POW_WWI(obits, lbits, rbits, owp, lwp, rhs) \ VL_POW_WWQ(obits, lbits, rbits, owp, lwp, rhs) static inline IData VL_POW_III(int, int, int rbits, IData lhs, IData rhs) VL_PURE { if (VL_UNLIKELY(rhs == 0)) return 1; if (VL_UNLIKELY(lhs == 0)) return 0; IData power = lhs; IData out = 1; for (int i = 0; i < rbits; ++i) { if (i > 0) power = power * power; if (rhs & (VL_ULL(1) << i)) out *= power; } return out; } static inline QData VL_POW_QQQ(int, int, int rbits, QData lhs, QData rhs) VL_PURE { if (VL_UNLIKELY(rhs == 0)) return 1; if (VL_UNLIKELY(lhs == 0)) return 0; QData power = lhs; QData out = VL_ULL(1); for (int i = 0; i < rbits; ++i) { if (i > 0) power = power * power; if (rhs & (VL_ULL(1) << i)) out *= power; } return out; } WDataOutP VL_POW_WWW(int obits, int, int rbits, WDataOutP owp, WDataInP lwp, WDataInP rwp); WDataOutP VL_POW_WWQ(int obits, int, int rbits, WDataOutP owp, WDataInP lwp, QData rhs); QData VL_POW_QQW(int obits, int, int rbits, QData lhs, WDataInP rwp); #define VL_POWSS_IIQ(obits,lbits,rbits,lhs,rhs,lsign,rsign) \ VL_POWSS_QQQ(obits,lbits,rbits,lhs,rhs,lsign,rsign) #define VL_POWSS_IIQ(obits,lbits,rbits,lhs,rhs,lsign,rsign) \ VL_POWSS_QQQ(obits,lbits,rbits,lhs,rhs,lsign,rsign) #define VL_POWSS_IIW(obits,lbits,rbits,lhs,rwp,lsign,rsign) \ VL_POWSS_QQW(obits,lbits,rbits,lhs,rwp,lsign,rsign) #define VL_POWSS_QQI(obits,lbits,rbits,lhs,rhs,lsign,rsign) \ VL_POWSS_QQQ(obits,lbits,rbits,lhs,rhs,lsign,rsign) #define VL_POWSS_WWI(obits,lbits,rbits,owp,lwp,rhs,lsign,rsign) \ VL_POWSS_WWQ(obits,lbits,rbits,owp,lwp,rhs,lsign,rsign) static inline IData VL_POWSS_III(int obits, int, int rbits, IData lhs, IData rhs, bool lsign, bool rsign) VL_MT_SAFE { if (VL_UNLIKELY(rhs == 0)) return 1; if (rsign && VL_SIGN_I(rbits, rhs)) { if (lhs == 0) return 0; // "X" else if (lhs == 1) return 1; else if (lsign && lhs == VL_MASK_I(obits)) { // -1 if (rhs & 1) return VL_MASK_I(obits); // -1^odd=-1 else return 1; // -1^even=1 } return 0; } return VL_POW_III(obits, rbits, rbits, lhs, rhs); } static inline QData VL_POWSS_QQQ(int obits, int, int rbits, QData lhs, QData rhs, bool lsign, bool rsign) VL_MT_SAFE { if (VL_UNLIKELY(rhs == 0)) return 1; if (rsign && VL_SIGN_Q(rbits, rhs)) { if (lhs == 0) return 0; // "X" else if (lhs == 1) return 1; else if (lsign && lhs == VL_MASK_Q(obits)) { // -1 if (rhs & 1) return VL_MASK_Q(obits); // -1^odd=-1 else return 1; // -1^even=1 } return 0; } return VL_POW_QQQ(obits, rbits, rbits, lhs, rhs); } WDataOutP VL_POWSS_WWW(int obits, int, int rbits, WDataOutP owp, WDataInP lwp, WDataInP rwp, bool lsign, bool rsign); WDataOutP VL_POWSS_WWQ(int obits, int, int rbits, WDataOutP owp, WDataInP lwp, QData rhs, bool lsign, bool rsign); QData VL_POWSS_QQW(int obits, int, int rbits, QData lhs, WDataInP rwp, bool lsign, bool rsign); //=================================================================== // Concat/replication // INTERNAL: Stuff LHS bit 0++ into OUTPUT at specified offset // ld may be "dirty", output is clean static inline void _VL_INSERT_II(int, CData& lhsr, IData ld, int hbit, int lbit) VL_PURE { IData insmask = (VL_MASK_I(hbit - lbit + 1)) << lbit; lhsr = (lhsr & ~insmask) | ((ld << lbit) & insmask); } static inline void _VL_INSERT_II(int, SData& lhsr, IData ld, int hbit, int lbit) VL_PURE { IData insmask = (VL_MASK_I(hbit - lbit + 1)) << lbit; lhsr = (lhsr & ~insmask) | ((ld << lbit) & insmask); } static inline void _VL_INSERT_II(int, IData& lhsr, IData ld, int hbit, int lbit) VL_PURE { IData insmask = (VL_MASK_I(hbit - lbit + 1)) << lbit; lhsr = (lhsr & ~insmask) | ((ld << lbit) & insmask); } static inline void _VL_INSERT_QQ(int, QData& lhsr, QData ld, int hbit, int lbit) VL_PURE { QData insmask = (VL_MASK_Q(hbit - lbit + 1)) << lbit; lhsr = (lhsr & ~insmask) | ((ld << lbit) & insmask); } static inline void _VL_INSERT_WI(int, WDataOutP owp, IData ld, int hbit, int lbit) VL_MT_SAFE { int hoffset = VL_BITBIT_E(hbit); int loffset = VL_BITBIT_E(lbit); if (hoffset == VL_SIZEBITS_E && loffset == 0) { // Fast and common case, word based insertion owp[VL_BITWORD_E(lbit)] = ld; } else { int hword = VL_BITWORD_E(hbit); int lword = VL_BITWORD_E(lbit); EData lde = static_cast<EData>(ld); if (hword == lword) { // know < EData bits because above checks it EData insmask = (VL_MASK_E(hoffset - loffset + 1)) << loffset; owp[lword] = (owp[lword] & ~insmask) | ((lde << loffset) & insmask); } else { EData hinsmask = (VL_MASK_E(hoffset - 0 + 1)) << 0; EData linsmask = (VL_MASK_E((VL_EDATASIZE - 1) - loffset + 1)) << loffset; int nbitsonright = VL_EDATASIZE - loffset; // bits that end up in lword owp[lword] = (owp[lword] & ~linsmask) | ((lde << loffset) & linsmask); owp[hword] = (owp[hword] & ~hinsmask) | ((lde >> nbitsonright) & hinsmask); } } } // INTERNAL: Stuff large LHS bit 0++ into OUTPUT at specified offset // lwp may be "dirty" static inline void _VL_INSERT_WW(int, WDataOutP owp, WDataInP lwp, int hbit, int lbit) VL_MT_SAFE { int hoffset = hbit & VL_SIZEBITS_E; int loffset = lbit & VL_SIZEBITS_E; int lword = VL_BITWORD_E(lbit); int words = VL_WORDS_I(hbit - lbit + 1); if (hoffset == VL_SIZEBITS_E && loffset == 0) { // Fast and common case, word based insertion for (int i=0; i<words; ++i) { owp[lword+i] = lwp[i]; } } else if (loffset==0) { // Non-32bit, but nicely aligned, so stuff all but the last word for (int i=0; i<(words-1); ++i) { owp[lword+i] = lwp[i]; } // Know it's not a full word as above fast case handled it EData hinsmask = (VL_MASK_E(hoffset - 0 + 1)); owp[lword + words - 1] = (owp[words + lword - 1] & ~hinsmask) | (lwp[words - 1] & hinsmask); } else { EData hinsmask = (VL_MASK_E(hoffset - 0 + 1)) << 0; EData linsmask = (VL_MASK_E((VL_EDATASIZE - 1) - loffset + 1)) << loffset; int nbitsonright = VL_EDATASIZE - loffset; // bits that end up in lword (know loffset!=0) // Middle words int hword = VL_BITWORD_E(hbit); for (int i=0; i<words; ++i) { { // Lower word int oword = lword+i; EData d = lwp[i] << loffset; EData od = (owp[oword] & ~linsmask) | (d & linsmask); if (oword == hword) owp[oword] = (owp[oword] & ~hinsmask) | (od & hinsmask); else owp[oword] = od; } { // Upper word int oword = lword+i+1; if (oword <= hword) { EData d = lwp[i] >> nbitsonright; EData od = (d & ~linsmask) | (owp[oword] & linsmask); if (oword == hword) owp[oword] = (owp[oword] & ~hinsmask) | (od & hinsmask); else owp[oword] = od; } } } } } static inline void _VL_INSERT_WQ(int obits, WDataOutP owp, QData ld, int hbit, int lbit) VL_MT_SAFE { WData lwp[VL_WQ_WORDS_E]; VL_SET_WQ(lwp, ld); _VL_INSERT_WW(obits, owp, lwp, hbit, lbit); } // EMIT_RULE: VL_REPLICATE: oclean=clean>width32, dirty<=width32; lclean=clean; rclean==clean; // RHS MUST BE CLEAN CONSTANT. #define VL_REPLICATE_IOI(obits,lbits,rbits, ld, rep) (-(ld)) // Iff lbits==1 #define VL_REPLICATE_QOI(obits,lbits,rbits, ld, rep) (-(static_cast<QData>(ld))) // Iff lbits==1 static inline IData VL_REPLICATE_III(int, int lbits, int, IData ld, IData rep) VL_PURE { IData returndata = ld; for (unsigned i=1; i < rep; ++i){ returndata = returndata << lbits; returndata |= ld; } return returndata; } static inline QData VL_REPLICATE_QII(int, int lbits, int, IData ld, IData rep) VL_PURE { QData returndata = ld; for (unsigned i=1; i < rep; ++i){ returndata = returndata << lbits; returndata |= static_cast<QData>(ld); } return returndata; } static inline WDataOutP VL_REPLICATE_WII(int obits, int lbits, int, WDataOutP owp, IData ld, IData rep) VL_MT_SAFE { owp[0] = ld; for (unsigned i=1; i < rep; ++i){ _VL_INSERT_WI(obits, owp, ld, i*lbits+lbits-1, i*lbits); } return owp; } static inline WDataOutP VL_REPLICATE_WQI(int obits, int lbits, int, WDataOutP owp, QData ld, IData rep) VL_MT_SAFE { VL_SET_WQ(owp, ld); for (unsigned i=1; i < rep; ++i){ _VL_INSERT_WQ(obits, owp, ld, i*lbits+lbits-1, i*lbits); } return owp; } static inline WDataOutP VL_REPLICATE_WWI(int obits, int lbits, int, WDataOutP owp, WDataInP lwp, IData rep) VL_MT_SAFE { for (int i=0; i < VL_WORDS_I(lbits); ++i) owp[i] = lwp[i]; for (unsigned i=1; i < rep; ++i){ _VL_INSERT_WW(obits, owp, lwp, i*lbits+lbits-1, i*lbits); } return owp; } // Left stream operator. Output will always be clean. LHS and RHS must be clean. // Special "fast" versions for slice sizes that are a power of 2. These use // shifts and masks to execute faster than the slower for-loop approach where a // subset of bits is copied in during each iteration. static inline IData VL_STREAML_FAST_III(int, int lbits, int, IData ld, IData rd_log2) VL_PURE { // Pre-shift bits in most-significant slice: // // If lbits is not a multiple of the slice size (i.e., lbits % rd != 0), // then we end up with a "gap" in our reversed result. For example, if we // have a 5-bit Verlilog signal (lbits=5) in an 8-bit C data type: // // ld = ---43210 // // (where numbers are the Verilog signal bit numbers and '-' is an unused bit). // Executing the switch statement below with a slice size of two (rd=2, // rd_log2=1) produces: // // ret = 1032-400 // // Pre-shifting the bits in the most-significant slice allows us to avoid // this gap in the shuffled data: // // ld_adjusted = --4-3210 // ret = 10324--- IData ret = ld; if (rd_log2) { vluint32_t lbitsFloor = lbits & ~VL_MASK_I(rd_log2); // max multiple of rd <= lbits vluint32_t lbitsRem = lbits - lbitsFloor; // number of bits in most-sig slice (MSS) IData msbMask = VL_MASK_I(lbitsRem) << lbitsFloor; // mask to sel only bits in MSS ret = (ret & ~msbMask) | ((ret & msbMask) << ((VL_UL(1) << rd_log2) - lbitsRem)); } switch (rd_log2) { case 0: ret = ((ret >> 1) & VL_UL(0x55555555)) | ((ret & VL_UL(0x55555555)) << 1); // FALLTHRU case 1: ret = ((ret >> 2) & VL_UL(0x33333333)) | ((ret & VL_UL(0x33333333)) << 2); // FALLTHRU case 2: ret = ((ret >> 4) & VL_UL(0x0f0f0f0f)) | ((ret & VL_UL(0x0f0f0f0f)) << 4); // FALLTHRU case 3: ret = ((ret >> 8) & VL_UL(0x00ff00ff)) | ((ret & VL_UL(0x00ff00ff)) << 8); // FALLTHRU case 4: ret = ((ret >> 16) | (ret << 16)); } return ret >> (VL_IDATASIZE - lbits); } static inline QData VL_STREAML_FAST_QQI(int, int lbits, int, QData ld, IData rd_log2) VL_PURE { // Pre-shift bits in most-significant slice (see comment in VL_STREAML_FAST_III) QData ret = ld; if (rd_log2) { vluint32_t lbitsFloor = lbits & ~VL_MASK_I(rd_log2); vluint32_t lbitsRem = lbits - lbitsFloor; QData msbMask = VL_MASK_Q(lbitsRem) << lbitsFloor; ret = (ret & ~msbMask) | ((ret & msbMask) << ((VL_ULL(1) << rd_log2) - lbitsRem)); } switch (rd_log2) { case 0: ret = (((ret >> 1) & VL_ULL(0x5555555555555555)) | ((ret & VL_ULL(0x5555555555555555)) << 1)); // FALLTHRU case 1: ret = (((ret >> 2) & VL_ULL(0x3333333333333333)) | ((ret & VL_ULL(0x3333333333333333)) << 2)); // FALLTHRU case 2: ret = (((ret >> 4) & VL_ULL(0x0f0f0f0f0f0f0f0f)) | ((ret & VL_ULL(0x0f0f0f0f0f0f0f0f)) << 4)); // FALLTHRU case 3: ret = (((ret >> 8) & VL_ULL(0x00ff00ff00ff00ff)) | ((ret & VL_ULL(0x00ff00ff00ff00ff)) << 8)); // FALLTHRU case 4: ret = (((ret >> 16) & VL_ULL(0x0000ffff0000ffff)) | ((ret & VL_ULL(0x0000ffff0000ffff)) << 16)); // FALLTHRU case 5: ret = ((ret >> 32) | (ret << 32)); } return ret >> (VL_QUADSIZE - lbits); } // Regular "slow" streaming operators static inline IData VL_STREAML_III(int, int lbits, int, IData ld, IData rd) VL_PURE { IData ret = 0; // Slice size should never exceed the lhs width IData mask = VL_MASK_I(rd); for (int istart = 0; istart < lbits; istart += rd) { int ostart = lbits - rd - istart; ostart = ostart > 0 ? ostart : 0; ret |= ((ld >> istart) & mask) << ostart; } return ret; } static inline QData VL_STREAML_QQI(int, int lbits, int, QData ld, IData rd) VL_PURE { QData ret = 0; // Slice size should never exceed the lhs width QData mask = VL_MASK_Q(rd); for (int istart=0; istart<lbits; istart+=rd) { int ostart = lbits-rd-istart; ostart = ostart > 0 ? ostart : 0; ret |= ((ld >> istart) & mask) << ostart; } return ret; } static inline WDataOutP VL_STREAML_WWI(int, int lbits, int, WDataOutP owp, WDataInP lwp, IData rd) VL_MT_SAFE { VL_ZERO_W(lbits, owp); // Slice size should never exceed the lhs width int ssize = (rd < static_cast<IData>(lbits)) ? rd : (static_cast<IData>(lbits)); for (int istart=0; istart<lbits; istart+=rd) { int ostart = lbits-rd-istart; ostart = ostart > 0 ? ostart : 0; for (int sbit=0; sbit<ssize && sbit<lbits-istart; ++sbit) { // Extract a single bit from lwp and shift it to the correct // location for owp. EData bit = (VL_BITRSHIFT_W(lwp, (istart + sbit)) & 1) << VL_BITBIT_E(ostart + sbit); owp[VL_BITWORD_E(ostart + sbit)] |= bit; } } return owp; } // Because concats are common and wide, it's valuable to always have a clean output. // Thus we specify inputs must be clean, so we don't need to clean the output. // Note the bit shifts are always constants, so the adds in these constify out. // Casts required, as args may be 8 bit entities, and need to shift to appropriate output size #define VL_CONCAT_III(obits,lbits,rbits,ld,rd) \ (static_cast<IData>(ld)<<(rbits) | static_cast<IData>(rd)) #define VL_CONCAT_QII(obits,lbits,rbits,ld,rd) \ (static_cast<QData>(ld)<<(rbits) | static_cast<QData>(rd)) #define VL_CONCAT_QIQ(obits,lbits,rbits,ld,rd) \ (static_cast<QData>(ld)<<(rbits) | static_cast<QData>(rd)) #define VL_CONCAT_QQI(obits,lbits,rbits,ld,rd) \ (static_cast<QData>(ld)<<(rbits) | static_cast<QData>(rd)) #define VL_CONCAT_QQQ(obits,lbits,rbits,ld,rd) \ (static_cast<QData>(ld)<<(rbits) | static_cast<QData>(rd)) static inline WDataOutP VL_CONCAT_WII(int obits, int lbits, int rbits, WDataOutP owp, IData ld, IData rd) VL_MT_SAFE { owp[0] = rd; for (int i=1; i < VL_WORDS_I(obits); ++i) owp[i] = 0; _VL_INSERT_WI(obits, owp, ld, rbits+lbits-1, rbits); return owp; } static inline WDataOutP VL_CONCAT_WWI(int obits, int lbits, int rbits, WDataOutP owp, WDataInP lwp, IData rd) VL_MT_SAFE { owp[0] = rd; for (int i=1; i < VL_WORDS_I(obits); ++i) owp[i] = 0; _VL_INSERT_WW(obits, owp, lwp, rbits+lbits-1, rbits); return owp; } static inline WDataOutP VL_CONCAT_WIW(int obits, int lbits, int rbits, WDataOutP owp, IData ld, WDataInP rwp) VL_MT_SAFE { for (int i=0; i < VL_WORDS_I(rbits); ++i) owp[i] = rwp[i]; for (int i=VL_WORDS_I(rbits); i < VL_WORDS_I(obits); ++i) owp[i] = 0; _VL_INSERT_WI(obits, owp, ld, rbits+lbits-1, rbits); return owp; } static inline WDataOutP VL_CONCAT_WIQ(int obits, int lbits, int rbits, WDataOutP owp, IData ld, QData rd) VL_MT_SAFE { VL_SET_WQ(owp, rd); for (int i = VL_WQ_WORDS_E; i < VL_WORDS_I(obits); ++i) owp[i] = 0; _VL_INSERT_WI(obits, owp, ld, rbits+lbits-1, rbits); return owp; } static inline WDataOutP VL_CONCAT_WQI(int obits, int lbits, int rbits, WDataOutP owp, QData ld, IData rd) VL_MT_SAFE { owp[0] = rd; for (int i=1; i < VL_WORDS_I(obits); ++i) owp[i] = 0; _VL_INSERT_WQ(obits, owp, ld, rbits+lbits-1, rbits); return owp; } static inline WDataOutP VL_CONCAT_WQQ(int obits, int lbits, int rbits, WDataOutP owp, QData ld, QData rd) VL_MT_SAFE { VL_SET_WQ(owp, rd); for (int i = VL_WQ_WORDS_E; i < VL_WORDS_I(obits); ++i) owp[i] = 0; _VL_INSERT_WQ(obits, owp, ld, rbits+lbits-1, rbits); return owp; } static inline WDataOutP VL_CONCAT_WWQ(int obits, int lbits, int rbits, WDataOutP owp, WDataInP lwp, QData rd) VL_MT_SAFE { VL_SET_WQ(owp, rd); for (int i = VL_WQ_WORDS_E; i < VL_WORDS_I(obits); ++i) owp[i] = 0; _VL_INSERT_WW(obits, owp, lwp, rbits+lbits-1, rbits); return owp; } static inline WDataOutP VL_CONCAT_WQW(int obits, int lbits, int rbits, WDataOutP owp, QData ld, WDataInP rwp) VL_MT_SAFE { for (int i=0; i < VL_WORDS_I(rbits); ++i) owp[i] = rwp[i]; for (int i=VL_WORDS_I(rbits); i < VL_WORDS_I(obits); ++i) owp[i] = 0; _VL_INSERT_WQ(obits, owp, ld, rbits+lbits-1, rbits); return owp; } static inline WDataOutP VL_CONCAT_WWW(int obits, int lbits, int rbits, WDataOutP owp, WDataInP lwp, WDataInP rwp) VL_MT_SAFE { for (int i=0; i < VL_WORDS_I(rbits); ++i) owp[i] = rwp[i]; for (int i=VL_WORDS_I(rbits); i < VL_WORDS_I(obits); ++i) owp[i] = 0; _VL_INSERT_WW(obits, owp, lwp, rbits+lbits-1, rbits); return owp; } //=================================================================== // Shifts // Static shift, used by internal functions // The output is the same as the input - it overlaps! static inline void _VL_SHIFTL_INPLACE_W(int obits, WDataOutP iowp, IData rd/*1 or 4*/) VL_MT_SAFE { int words = VL_WORDS_I(obits); EData linsmask = VL_MASK_E(rd); for (int i=words-1; i>=1; --i) { iowp[i] = ((iowp[i]<<rd) & ~linsmask) | ((iowp[i-1] >> (VL_EDATASIZE - rd)) & linsmask); } iowp[0] = ((iowp[0]<<rd) & ~linsmask); iowp[VL_WORDS_I(obits)-1] &= VL_MASK_E(obits); } // EMIT_RULE: VL_SHIFTL: oclean=lclean; rclean==clean; // Important: Unlike most other funcs, the shift might well be a computed // expression. Thus consider this when optimizing. (And perhaps have 2 funcs?) static inline WDataOutP VL_SHIFTL_WWI(int obits, int, int, WDataOutP owp, WDataInP lwp, IData rd) VL_MT_SAFE { int word_shift = VL_BITWORD_E(rd); int bit_shift = VL_BITBIT_E(rd); if (rd >= static_cast<IData>(obits)) { // rd may be huge with MSB set for (int i=0; i < VL_WORDS_I(obits); ++i) owp[i] = 0; } else if (bit_shift==0) { // Aligned word shift (<<0,<<32,<<64 etc) for (int i=0; i < word_shift; ++i) owp[i] = 0; for (int i=word_shift; i < VL_WORDS_I(obits); ++i) owp[i] = lwp[i-word_shift]; } else { for (int i=0; i < VL_WORDS_I(obits); ++i) owp[i] = 0; _VL_INSERT_WW(obits, owp, lwp, obits-1, rd); } return owp; } static inline WDataOutP VL_SHIFTL_WWW(int obits, int lbits, int rbits, WDataOutP owp, WDataInP lwp, WDataInP rwp) VL_MT_SAFE { for (int i=1; i < VL_WORDS_I(rbits); ++i) { if (VL_UNLIKELY(rwp[i])) { // Huge shift 1>>32 or more return VL_ZERO_W(obits, owp); } } return VL_SHIFTL_WWI(obits, lbits, 32, owp, lwp, rwp[0]); } static inline IData VL_SHIFTL_IIW(int obits, int, int rbits, IData lhs, WDataInP rwp) VL_MT_SAFE { for (int i=1; i < VL_WORDS_I(rbits); ++i) { if (VL_UNLIKELY(rwp[i])) { // Huge shift 1>>32 or more return 0; } } return VL_CLEAN_II(obits, obits, lhs<<rwp[0]); } static inline QData VL_SHIFTL_QQW(int obits, int, int rbits, QData lhs, WDataInP rwp) VL_MT_SAFE { for (int i=1; i < VL_WORDS_I(rbits); ++i) { if (VL_UNLIKELY(rwp[i])) { // Huge shift 1>>32 or more return 0; } } // Above checks rwp[1]==0 so not needed in below shift return VL_CLEAN_QQ(obits, obits, lhs<<(static_cast<QData>(rwp[0]))); } // EMIT_RULE: VL_SHIFTR: oclean=lclean; rclean==clean; // Important: Unlike most other funcs, the shift might well be a computed // expression. Thus consider this when optimizing. (And perhaps have 2 funcs?) static inline WDataOutP VL_SHIFTR_WWI(int obits, int, int, WDataOutP owp, WDataInP lwp, IData rd) VL_MT_SAFE { int word_shift = VL_BITWORD_E(rd); // Maybe 0 int bit_shift = VL_BITBIT_E(rd); if (rd >= static_cast<IData>(obits)) { // rd may be huge with MSB set for (int i=0; i < VL_WORDS_I(obits); ++i) owp[i] = 0; } else if (bit_shift==0) { // Aligned word shift (>>0,>>32,>>64 etc) int copy_words = (VL_WORDS_I(obits)-word_shift); for (int i=0; i < copy_words; ++i) owp[i] = lwp[i+word_shift]; for (int i=copy_words; i < VL_WORDS_I(obits); ++i) owp[i] = 0; } else { int loffset = rd & VL_SIZEBITS_E; int nbitsonright = VL_EDATASIZE - loffset; // bits that end up in lword (know loffset!=0) // Middle words int words = VL_WORDS_I(obits-rd); for (int i=0; i<words; ++i) { owp[i] = lwp[i+word_shift]>>loffset; int upperword = i+word_shift+1; if (upperword < VL_WORDS_I(obits)) { owp[i] |= lwp[upperword]<< nbitsonright; } } for (int i=words; i<VL_WORDS_I(obits); ++i) owp[i]=0; } return owp; } static inline WDataOutP VL_SHIFTR_WWW(int obits, int lbits, int rbits, WDataOutP owp, WDataInP lwp, WDataInP rwp) VL_MT_SAFE { for (int i=1; i < VL_WORDS_I(rbits); ++i) { if (VL_UNLIKELY(rwp[i])) { // Huge shift 1>>32 or more return VL_ZERO_W(obits, owp); } } return VL_SHIFTR_WWI(obits, lbits, 32, owp, lwp, rwp[0]); } static inline IData VL_SHIFTR_IIW(int obits, int, int rbits, IData lhs, WDataInP rwp) VL_MT_SAFE { for (int i = 1; i < VL_WORDS_I(rbits); ++i) { if (VL_UNLIKELY(rwp[i])) { // Huge shift 1>>32 or more return 0; } } return VL_CLEAN_II(obits, obits, lhs >> rwp[0]); } static inline QData VL_SHIFTR_QQW(int obits, int, int rbits, QData lhs, WDataInP rwp) VL_MT_SAFE { for (int i = 1; i < VL_WORDS_I(rbits); ++i) { if (VL_UNLIKELY(rwp[i])) { // Huge shift 1>>32 or more return 0; } } // Above checks rwp[1]==0 so not needed in below shift return VL_CLEAN_QQ(obits, obits, lhs >> (static_cast<QData>(rwp[0]))); } // EMIT_RULE: VL_SHIFTRS: oclean=false; lclean=clean, rclean==clean; static inline IData VL_SHIFTRS_III(int obits, int lbits, int, IData lhs, IData rhs) VL_PURE { // Note the C standard does not specify the >> operator as a arithmetic shift! // IEEE says signed if output signed, but bit position from lbits; // must use lbits for sign; lbits might != obits, // an EXTEND(SHIFTRS(...)) can became a SHIFTRS(...) within same 32/64 bit word length IData sign = -(lhs >> (lbits-1)); // ffff_ffff if negative IData signext = ~(VL_MASK_I(lbits) >> rhs); // One with bits where we've shifted "past" return (lhs >> rhs) | (sign & VL_CLEAN_II(obits, obits, signext)); } static inline QData VL_SHIFTRS_QQI(int obits, int lbits, int, QData lhs, IData rhs) VL_PURE { QData sign = -(lhs >> (lbits-1)); QData signext = ~(VL_MASK_Q(lbits) >> rhs); return (lhs >> rhs) | (sign & VL_CLEAN_QQ(obits, obits, signext)); } static inline IData VL_SHIFTRS_IQI(int obits, int lbits, int rbits, QData lhs, IData rhs) VL_PURE { return static_cast<IData>(VL_SHIFTRS_QQI(obits, lbits, rbits, lhs, rhs)); } static inline WDataOutP VL_SHIFTRS_WWI(int obits, int lbits, int, WDataOutP owp, WDataInP lwp, IData rd) VL_MT_SAFE { int word_shift = VL_BITWORD_E(rd); int bit_shift = VL_BITBIT_E(rd); int lmsw = VL_WORDS_I(obits)-1; EData sign = VL_SIGNONES_E(lbits, lwp[lmsw]); if (rd >= static_cast<IData>(obits)) { // Shifting past end, sign in all of lbits for (int i=0; i <= lmsw; ++i) owp[i] = sign; owp[lmsw] &= VL_MASK_E(lbits); } else if (bit_shift==0) { // Aligned word shift (>>0,>>32,>>64 etc) int copy_words = (VL_WORDS_I(obits)-word_shift); for (int i=0; i < copy_words; ++i) owp[i] = lwp[i+word_shift]; if (copy_words >= 0) owp[copy_words - 1] |= ~VL_MASK_E(obits) & sign; for (int i = copy_words; i < VL_WORDS_I(obits); ++i) owp[i] = sign; owp[lmsw] &= VL_MASK_E(lbits); } else { int loffset = rd & VL_SIZEBITS_E; int nbitsonright = VL_EDATASIZE - loffset; // bits that end up in lword (know loffset!=0) // Middle words int words = VL_WORDS_I(obits-rd); for (int i=0; i<words; ++i) { owp[i] = lwp[i+word_shift]>>loffset; int upperword = i+word_shift+1; if (upperword < VL_WORDS_I(obits)) { owp[i] |= lwp[upperword]<< nbitsonright; } } if (words) owp[words - 1] |= sign & ~VL_MASK_E(obits - loffset); for (int i = words; i < VL_WORDS_I(obits); ++i) owp[i] = sign; owp[lmsw] &= VL_MASK_E(lbits); } return owp; } static inline WDataOutP VL_SHIFTRS_WWW(int obits, int lbits, int rbits, WDataOutP owp, WDataInP lwp, WDataInP rwp) VL_MT_SAFE { EData overshift = 0; // Huge shift 1>>32 or more for (int i = 1; i < VL_WORDS_I(rbits); ++i) { overshift |= rwp[i]; } if (VL_UNLIKELY(overshift)) { int lmsw = VL_WORDS_I(obits) - 1; EData sign = VL_SIGNONES_E(lbits, lwp[lmsw]); for (int j = 0; j <= lmsw; ++j) owp[j] = sign; owp[lmsw] &= VL_MASK_E(lbits); return owp; } return VL_SHIFTRS_WWI(obits, lbits, 32, owp, lwp, rwp[0]); } static inline IData VL_SHIFTRS_IIW(int obits, int lbits, int rbits, IData lhs, WDataInP rwp) VL_MT_SAFE { EData overshift = 0; // Huge shift 1>>32 or more for (int i = 1; i < VL_WORDS_I(rbits); ++i) { overshift |= rwp[i]; } if (VL_UNLIKELY(overshift)) { IData sign = -(lhs >> (lbits-1)); // ffff_ffff if negative return VL_CLEAN_II(obits, obits, sign); } return VL_SHIFTRS_III(obits, lbits, 32, lhs, rwp[0]); } static inline QData VL_SHIFTRS_QQW(int obits, int lbits, int rbits, QData lhs, WDataInP rwp) VL_MT_SAFE { EData overshift = 0; // Huge shift 1>>32 or more for (int i = 1; i < VL_WORDS_I(rbits); ++i) { overshift |= rwp[i]; } if (VL_UNLIKELY(overshift)) { QData sign = -(lhs >> (lbits-1)); // ffff_ffff if negative return VL_CLEAN_QQ(obits, obits, sign); } return VL_SHIFTRS_QQI(obits, lbits, 32, lhs, rwp[0]); } static inline IData VL_SHIFTRS_IIQ(int obits, int lbits, int rbits, IData lhs, QData rhs) VL_PURE { WData rwp[VL_WQ_WORDS_E]; VL_SET_WQ(rwp, rhs); return VL_SHIFTRS_IIW(obits, lbits, rbits, lhs, rwp); } static inline QData VL_SHIFTRS_QQQ(int obits, int lbits, int rbits, QData lhs, QData rhs) VL_PURE { WData rwp[VL_WQ_WORDS_E]; VL_SET_WQ(rwp, rhs); return VL_SHIFTRS_QQW(obits, lbits, rbits, lhs, rwp); } //=================================================================== // Bit selection // EMIT_RULE: VL_BITSEL: oclean=dirty; rclean==clean; #define VL_BITSEL_IIII(obits,lbits,rbits,zbits,lhs,rhs) ((lhs)>>(rhs)) #define VL_BITSEL_QIII(obits,lbits,rbits,zbits,lhs,rhs) ((lhs)>>(rhs)) #define VL_BITSEL_QQII(obits,lbits,rbits,zbits,lhs,rhs) ((lhs)>>(rhs)) #define VL_BITSEL_IQII(obits,lbits,rbits,zbits,lhs,rhs) (static_cast<IData>((lhs)>>(rhs))) static inline IData VL_BITSEL_IWII(int, int lbits, int, int, WDataInP lwp, IData rd) VL_MT_SAFE { int word = VL_BITWORD_E(rd); if (VL_UNLIKELY(rd > static_cast<IData>(lbits))) { return ~0; // Spec says you can go outside the range of a array. Don't coredump if so. // We return all 1's as that's more likely to find bugs (?) than 0's. } else { return (lwp[word] >> VL_BITBIT_E(rd)); } } // EMIT_RULE: VL_RANGE: oclean=lclean; out=dirty // <msb> & <lsb> MUST BE CLEAN (currently constant) #define VL_SEL_IIII(obits,lbits,rbits,tbits,lhs,lsb,width) ((lhs)>>(lsb)) #define VL_SEL_QQII(obits,lbits,rbits,tbits,lhs,lsb,width) ((lhs)>>(lsb)) #define VL_SEL_IQII(obits,lbits,rbits,tbits,lhs,lsb,width) (static_cast<IData>((lhs)>>(lsb))) static inline IData VL_SEL_IWII(int, int lbits, int, int, WDataInP lwp, IData lsb, IData width) VL_MT_SAFE { int msb = lsb+width-1; if (VL_UNLIKELY(msb>lbits)) { return ~0; // Spec says you can go outside the range of a array. Don't coredump if so. } else if (VL_BITWORD_E(msb) == VL_BITWORD_E(static_cast<int>(lsb))) { return VL_BITRSHIFT_W(lwp, lsb); } else { // 32 bit extraction may span two words int nbitsfromlow = VL_EDATASIZE - VL_BITBIT_E(lsb); // bits that come from low word return ((lwp[VL_BITWORD_E(msb)] << nbitsfromlow) | VL_BITRSHIFT_W(lwp, lsb)); } } static inline QData VL_SEL_QWII(int, int lbits, int, int, WDataInP lwp, IData lsb, IData width) VL_MT_SAFE { int msb = lsb+width-1; if (VL_UNLIKELY(msb>lbits)) { return ~0; // Spec says you can go outside the range of a array. Don't coredump if so. } else if (VL_BITWORD_E(msb) == VL_BITWORD_E(static_cast<int>(lsb))) { return VL_BITRSHIFT_W(lwp, lsb); } else if (VL_BITWORD_E(msb) == 1 + VL_BITWORD_E(static_cast<int>(lsb))) { int nbitsfromlow = VL_EDATASIZE - VL_BITBIT_E(lsb); QData hi = (lwp[VL_BITWORD_E(msb)]); QData lo = VL_BITRSHIFT_W(lwp, lsb); return (hi << nbitsfromlow) | lo; } else { // 64 bit extraction may span three words int nbitsfromlow = VL_EDATASIZE - VL_BITBIT_E(lsb); QData hi = (lwp[VL_BITWORD_E(msb)]); QData mid = (lwp[VL_BITWORD_E(lsb) + 1]); QData lo = VL_BITRSHIFT_W(lwp, lsb); return (hi << (nbitsfromlow + VL_EDATASIZE)) | (mid << nbitsfromlow) | lo; } } static inline WDataOutP VL_SEL_WWII(int obits, int lbits, int, int, WDataOutP owp, WDataInP lwp, IData lsb, IData width) VL_MT_SAFE { int msb = lsb+width-1; int word_shift = VL_BITWORD_E(lsb); if (VL_UNLIKELY(msb>lbits)) { // Outside bounds, for (int i=0; i<VL_WORDS_I(obits)-1; ++i) owp[i] = ~0; owp[VL_WORDS_I(obits) - 1] = VL_MASK_E(obits); } else if (VL_BITBIT_E(lsb) == 0) { // Just a word extract for (int i=0; i<VL_WORDS_I(obits); ++i) owp[i] = lwp[i+word_shift]; } else { // Not a _VL_INSERT because the bits come from any bit number and goto bit 0 int loffset = lsb & VL_SIZEBITS_E; int nbitsfromlow = VL_EDATASIZE - loffset; // bits that end up in lword (know loffset!=0) // Middle words int words = VL_WORDS_I(msb-lsb+1); for (int i=0; i<words; ++i) { owp[i] = lwp[i+word_shift]>>loffset; int upperword = i+word_shift+1; if (upperword <= static_cast<int>(VL_BITWORD_E(msb))) { owp[i] |= lwp[upperword] << nbitsfromlow; } } for (int i=words; i<VL_WORDS_I(obits); ++i) owp[i]=0; } return owp; } //====================================================================== // Range assignments // EMIT_RULE: VL_ASSIGNRANGE: rclean=dirty; static inline void VL_ASSIGNSEL_IIII(int obits, int lsb, CData& lhsr, IData rhs) VL_PURE { _VL_INSERT_II(obits, lhsr, rhs, lsb+obits-1, lsb); } static inline void VL_ASSIGNSEL_IIII(int obits, int lsb, SData& lhsr, IData rhs) VL_PURE { _VL_INSERT_II(obits, lhsr, rhs, lsb+obits-1, lsb); } static inline void VL_ASSIGNSEL_IIII(int obits, int lsb, IData& lhsr, IData rhs) VL_PURE { _VL_INSERT_II(obits, lhsr, rhs, lsb+obits-1, lsb); } static inline void VL_ASSIGNSEL_QIII(int obits, int lsb, QData& lhsr, IData rhs) VL_PURE { _VL_INSERT_QQ(obits, lhsr, rhs, lsb+obits-1, lsb); } static inline void VL_ASSIGNSEL_QQII(int obits, int lsb, QData& lhsr, QData rhs) VL_PURE { _VL_INSERT_QQ(obits, lhsr, rhs, lsb+obits-1, lsb); } static inline void VL_ASSIGNSEL_QIIQ(int obits, int lsb, QData& lhsr, QData rhs) VL_PURE { _VL_INSERT_QQ(obits, lhsr, rhs, lsb+obits-1, lsb); } //static inline void VL_ASSIGNSEL_IIIW(int obits, int lsb, IData& lhsr, WDataInP rwp) VL_MT_SAFE { // Illegal, as lhs width >= rhs width static inline void VL_ASSIGNSEL_WIII(int obits, int lsb, WDataOutP owp, IData rhs) VL_MT_SAFE { _VL_INSERT_WI(obits, owp, rhs, lsb+obits-1, lsb); } static inline void VL_ASSIGNSEL_WIIQ(int obits, int lsb, WDataOutP owp, QData rhs) VL_MT_SAFE { _VL_INSERT_WQ(obits, owp, rhs, lsb+obits-1, lsb); } static inline void VL_ASSIGNSEL_WIIW(int obits, int lsb, WDataOutP owp, WDataInP rwp) VL_MT_SAFE { _VL_INSERT_WW(obits, owp, rwp, lsb+obits-1, lsb); } //====================================================================== // Triops static inline WDataOutP VL_COND_WIWW(int obits, int, int, int, WDataOutP owp, int cond, WDataInP w1p, WDataInP w2p) VL_MT_SAFE { int words = VL_WORDS_I(obits); for (int i=0; i < words; ++i) owp[i] = cond ? w1p[i] : w2p[i]; return owp; } //====================================================================== // Constification // VL_CONST_W_#X(int obits, WDataOutP owp, IData data0, .... IData data(#-1)) // Sets wide vector words to specified constant words. // These macros are used when o might represent more words then are given as constants, // hence all upper words must be zeroed. // If changing the number of functions here, also change EMITCINLINES_NUM_CONSTW #define _END(obits,wordsSet) \ for(int i=(wordsSet);i<VL_WORDS_I(obits);++i) o[i] = 0; \ return o static inline WDataOutP VL_CONST_W_1X(int obits, WDataOutP o, EData d0) VL_MT_SAFE { o[0]=d0; _END(obits,1); } static inline WDataOutP VL_CONST_W_2X(int obits, WDataOutP o, EData d1, EData d0) VL_MT_SAFE { o[0]=d0; o[1]=d1; _END(obits,2); } static inline WDataOutP VL_CONST_W_3X(int obits, WDataOutP o, EData d2, EData d1, EData d0) VL_MT_SAFE { o[0]=d0; o[1]=d1; o[2]=d2; _END(obits,3); } static inline WDataOutP VL_CONST_W_4X(int obits, WDataOutP o, EData d3, EData d2, EData d1, EData d0) VL_MT_SAFE { o[0]=d0; o[1]=d1; o[2]=d2; o[3]=d3; _END(obits,4); } static inline WDataOutP VL_CONST_W_5X(int obits, WDataOutP o, EData d4, EData d3, EData d2, EData d1, EData d0) VL_MT_SAFE { o[0]=d0; o[1]=d1; o[2]=d2; o[3]=d3; o[4]=d4; _END(obits,5); } static inline WDataOutP VL_CONST_W_6X(int obits, WDataOutP o, EData d5, EData d4, EData d3, EData d2, EData d1, EData d0) VL_MT_SAFE { o[0]=d0; o[1]=d1; o[2]=d2; o[3]=d3; o[4]=d4; o[5]=d5; _END(obits,6); } static inline WDataOutP VL_CONST_W_7X(int obits, WDataOutP o, EData d6, EData d5, EData d4, EData d3, EData d2, EData d1, EData d0) VL_MT_SAFE { o[0]=d0; o[1]=d1; o[2]=d2; o[3]=d3; o[4]=d4; o[5]=d5; o[6]=d6; _END(obits,7); } static inline WDataOutP VL_CONST_W_8X(int obits, WDataOutP o, EData d7, EData d6, EData d5, EData d4, EData d3, EData d2, EData d1, EData d0) VL_MT_SAFE { o[0]=d0; o[1]=d1; o[2]=d2; o[3]=d3; o[4]=d4; o[5]=d5; o[6]=d6; o[7]=d7; _END(obits,8); } // static inline WDataOutP VL_CONSTHI_W_1X(int obits, int lsb, WDataOutP obase, EData d0) VL_MT_SAFE { WDataOutP o = obase + VL_WORDS_I(lsb); o[0]=d0; _END(obits,1); } static inline WDataOutP VL_CONSTHI_W_2X(int obits, int lsb, WDataOutP obase, EData d1, EData d0) VL_MT_SAFE { WDataOutP o = obase + VL_WORDS_I(lsb); o[0]=d0; o[1]=d1; _END(obits,2); } static inline WDataOutP VL_CONSTHI_W_3X(int obits, int lsb, WDataOutP obase, EData d2, EData d1, EData d0) VL_MT_SAFE { WDataOutP o = obase + VL_WORDS_I(lsb); o[0]=d0; o[1]=d1; o[2]=d2; _END(obits,3); } static inline WDataOutP VL_CONSTHI_W_4X(int obits, int lsb, WDataOutP obase, EData d3, EData d2, EData d1, EData d0) VL_MT_SAFE { WDataOutP o = obase + VL_WORDS_I(lsb); o[0]=d0; o[1]=d1; o[2]=d2; o[3]=d3; _END(obits,4); } static inline WDataOutP VL_CONSTHI_W_5X(int obits, int lsb, WDataOutP obase, EData d4, EData d3, EData d2, EData d1, EData d0) VL_MT_SAFE { WDataOutP o = obase + VL_WORDS_I(lsb); o[0]=d0; o[1]=d1; o[2]=d2; o[3]=d3; o[4]=d4; _END(obits,5); } static inline WDataOutP VL_CONSTHI_W_6X(int obits, int lsb, WDataOutP obase, EData d5, EData d4, EData d3, EData d2, EData d1, EData d0) VL_MT_SAFE { WDataOutP o = obase + VL_WORDS_I(lsb); o[0]=d0; o[1]=d1; o[2]=d2; o[3]=d3; o[4]=d4; o[5]=d5; _END(obits,6); } static inline WDataOutP VL_CONSTHI_W_7X(int obits, int lsb, WDataOutP obase, EData d6, EData d5, EData d4, EData d3, EData d2, EData d1, EData d0) VL_MT_SAFE { WDataOutP o = obase + VL_WORDS_I(lsb); o[0]=d0; o[1]=d1; o[2]=d2; o[3]=d3; o[4]=d4; o[5]=d5; o[6]=d6; _END(obits,7); } static inline WDataOutP VL_CONSTHI_W_8X(int obits, int lsb, WDataOutP obase, EData d7, EData d6, EData d5, EData d4, EData d3, EData d2, EData d1, EData d0) VL_MT_SAFE { WDataOutP o = obase + VL_WORDS_I(lsb); o[0]=d0; o[1]=d1; o[2]=d2; o[3]=d3; o[4]=d4; o[5]=d5; o[6]=d6; o[7]=d7; _END(obits,8); } #undef _END // Partial constant, lower words of vector wider than 8*32, starting at bit number lsb static inline void VL_CONSTLO_W_8X(int lsb, WDataOutP obase, EData d7, EData d6, EData d5, EData d4, EData d3, EData d2, EData d1, EData d0) VL_MT_SAFE { WDataOutP o = obase + VL_WORDS_I(lsb); o[0]=d0; o[1]=d1; o[2]=d2; o[3]=d3; o[4]=d4; o[5]=d5; o[6]=d6; o[7]=d7; } //====================================================================== #endif // Guard <|start_filename|>basic/lesson3/verilator/sim/vinc/verilated_dpi.cpp<|end_filename|> // -*- mode: C++; c-file-style: "cc-mode" -*- //************************************************************************* // // Copyright 2009-2020 by <NAME>. This program is free software; you can // redistribute it and/or modify it under the terms of either the GNU // Lesser General Public License Version 3 or the Perl Artistic License. // Version 2.0. // // Verilator is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // //========================================================================= /// /// \file /// \brief Verilator: DPI implementation code /// /// This file must be compiled and linked against all objects /// created from Verilator or called by Verilator that use the DPI. /// /// Code available from: https://verilator.org /// //========================================================================= #define _VERILATED_DPI_CPP_ #include "verilatedos.h" #include "verilated_dpi.h" #include "verilated_imp.h" // On MSVC++ we need svdpi.h to declare exports, not imports #define DPI_PROTOTYPES #undef XXTERN #define XXTERN DPI_EXTERN DPI_DLLESPEC #undef EETERN #define EETERN DPI_EXTERN DPI_DLLESPEC #include "vltstd/svdpi.h" //====================================================================== // Internal macros // Not supported yet #define _VL_SVDPI_UNIMP() \ VL_FATAL_MT(__FILE__, __LINE__, "", \ (std::string("%%Error: Unsupported DPI function: ")+VL_FUNC).c_str()) #define _VL_SVDPI_WARN(message...) \ VL_PRINTF_MT(message) // Function requires a "context" in the import declaration #define _VL_SVDPI_CONTEXT_WARN() \ _VL_SVDPI_WARN("%%Warning: DPI C Function called by Verilog DPI import with missing 'context' keyword.\n"); //====================================================================== //====================================================================== //====================================================================== // DPI ROUTINES const char* svDpiVersion() { return "1800-2005"; } //====================================================================== // Bit-select utility functions. svBit svGetBitselBit(const svBitVecVal* sp, int bit) { return VL_BITRSHIFT_W(sp,bit) & 1; } svLogic svGetBitselLogic(const svLogicVecVal* sp, int bit) { // Not VL_BITRSHIFT_W as sp is a different structure type // Verilator doesn't support X/Z so only aval return (((sp[VL_BITWORD_I(bit)].aval >> VL_BITBIT_I(bit)) & 1) | (((sp[VL_BITWORD_I(bit)].bval >> VL_BITBIT_I(bit)) & 1)<<1)); } void svPutBitselBit(svBitVecVal* dp, int bit, svBit s) { VL_ASSIGNBIT_WI(32, bit, dp, s); } void svPutBitselLogic(svLogicVecVal* dp, int bit, svLogic s) { // Verilator doesn't support X/Z so only aval dp[VL_BITWORD_I(bit)].aval = ((dp[VL_BITWORD_I(bit)].aval & ~(VL_UL(1)<<VL_BITBIT_I(bit))) | ((s&1)<<VL_BITBIT_I(bit))); dp[VL_BITWORD_I(bit)].bval = ((dp[VL_BITWORD_I(bit)].bval & ~(VL_UL(1)<<VL_BITBIT_I(bit))) | ((s&2)>>1<<VL_BITBIT_I(bit))); } void svGetPartselBit(svBitVecVal* dp, const svBitVecVal* sp, int lsb, int width) { // See also VL_SEL_WWI int msb = lsb+width-1; int word_shift = VL_BITWORD_I(lsb); if (VL_BITBIT_I(lsb)==0) { // Just a word extract for (int i=0; i<VL_WORDS_I(width); ++i) dp[i] = sp[i+word_shift]; } else { int loffset = lsb & VL_SIZEBITS_I; int nbitsfromlow = 32-loffset; // bits that end up in lword (know loffset!=0) // Middle words int words = VL_WORDS_I(msb-lsb+1); for (int i=0; i<words; ++i) { dp[i] = sp[i+word_shift]>>loffset; int upperword = i+word_shift+1; if (upperword <= static_cast<int>(VL_BITWORD_I(msb))) { dp[i] |= sp[upperword] << nbitsfromlow; } } } // Clean result dp[VL_WORDS_I(width)-1] &= VL_MASK_I(width); } void svGetPartselLogic(svLogicVecVal* dp, const svLogicVecVal* sp, int lsb, int width) { int msb = lsb+width-1; int word_shift = VL_BITWORD_I(lsb); if (VL_BITBIT_I(lsb)==0) { // Just a word extract for (int i=0; i<VL_WORDS_I(width); ++i) dp[i] = sp[i+word_shift]; } else { int loffset = lsb & VL_SIZEBITS_I; int nbitsfromlow = 32-loffset; // bits that end up in lword (know loffset!=0) // Middle words int words = VL_WORDS_I(msb-lsb+1); for (int i=0; i<words; ++i) { dp[i].aval = sp[i+word_shift].aval >> loffset; dp[i].bval = sp[i+word_shift].bval >> loffset; int upperword = i+word_shift+1; if (upperword <= static_cast<int>(VL_BITWORD_I(msb))) { dp[i].aval |= sp[upperword].aval << nbitsfromlow; dp[i].bval |= sp[upperword].bval << nbitsfromlow; } } } // Clean result dp[VL_WORDS_I(width)-1].aval &= VL_MASK_I(width); dp[VL_WORDS_I(width)-1].bval &= VL_MASK_I(width); } void svPutPartselBit(svBitVecVal* dp, const svBitVecVal s, int lbit, int width) { // See also _VL_INSERT_WI int hbit = lbit+width-1; int hoffset = VL_BITBIT_I(hbit); int loffset = VL_BITBIT_I(lbit); if (hoffset==VL_SIZEBITS_I && loffset==0) { // Fast and common case, word based insertion dp[VL_BITWORD_I(lbit)] = s; } else { int hword = VL_BITWORD_I(hbit); int lword = VL_BITWORD_I(lbit); if (hword==lword) { // know < 32 bits because above checks it IData insmask = (VL_MASK_I(hoffset-loffset+1))<<loffset; dp[lword] = (dp[lword] & ~insmask) | ((s<<loffset) & insmask); } else { IData hinsmask = (VL_MASK_I(hoffset-0+1))<<0; IData linsmask = (VL_MASK_I(31-loffset+1))<<loffset; int nbitsonright = 32-loffset; // bits that end up in lword dp[lword] = (dp[lword] & ~linsmask) | ((s<<loffset) & linsmask); dp[hword] = (dp[hword] & ~hinsmask) | ((s>>nbitsonright) & hinsmask); } } } // cppcheck-suppress passedByValue void svPutPartselLogic(svLogicVecVal* dp, const svLogicVecVal s, int lbit, int width) { int hbit = lbit+width-1; int hoffset = VL_BITBIT_I(hbit); int loffset = VL_BITBIT_I(lbit); if (hoffset==VL_SIZEBITS_I && loffset==0) { // Fast and common case, word based insertion dp[VL_BITWORD_I(lbit)].aval = s.aval; dp[VL_BITWORD_I(lbit)].bval = s.bval; } else { int hword = VL_BITWORD_I(hbit); int lword = VL_BITWORD_I(lbit); if (hword==lword) { // know < 32 bits because above checks it IData insmask = (VL_MASK_I(hoffset-loffset+1))<<loffset; dp[lword].aval = (dp[lword].aval & ~insmask) | ((s.aval<<loffset) & insmask); dp[lword].bval = (dp[lword].bval & ~insmask) | ((s.bval<<loffset) & insmask); } else { IData hinsmask = (VL_MASK_I(hoffset-0+1))<<0; IData linsmask = (VL_MASK_I(31-loffset+1))<<loffset; int nbitsonright = 32-loffset; // bits that end up in lword dp[lword].aval = (dp[lword].aval & ~linsmask) | ((s.aval<<loffset) & linsmask); dp[lword].bval = (dp[lword].bval & ~linsmask) | ((s.bval<<loffset) & linsmask); dp[hword].aval = (dp[hword].aval & ~hinsmask) | ((s.aval>>nbitsonright) & hinsmask); dp[hword].bval = (dp[hword].bval & ~hinsmask) | ((s.bval>>nbitsonright) & hinsmask); } } } //====================================================================== // Open array internals static inline const VerilatedDpiOpenVar* _vl_openhandle_varp(const svOpenArrayHandle h) { if (VL_UNLIKELY(!h)) { VL_FATAL_MT(__FILE__, __LINE__, "", "%%Error: DPI svOpenArrayHandle function called with NULL handle"); } const VerilatedDpiOpenVar* varp = reinterpret_cast<const VerilatedDpiOpenVar*>(h); if (VL_UNLIKELY(!varp->magicOk())) { VL_FATAL_MT(__FILE__, __LINE__, "", "%%Error: DPI svOpenArrayHandle function called with non-Verilator handle"); } return varp; } //====================================================================== // Open array querying functions int svLeft(const svOpenArrayHandle h, int d) { return _vl_openhandle_varp(h)->left(d); } int svRight(const svOpenArrayHandle h, int d) { return _vl_openhandle_varp(h)->right(d); } int svLow(const svOpenArrayHandle h, int d) { return _vl_openhandle_varp(h)->low(d); } int svHigh(const svOpenArrayHandle h, int d) { return _vl_openhandle_varp(h)->high(d); } int svIncrement(const svOpenArrayHandle h, int d) { return _vl_openhandle_varp(h)->increment(d); } int svSize(const svOpenArrayHandle h, int d) { return _vl_openhandle_varp(h)->elements(d); } int svDimensions(const svOpenArrayHandle h) { return _vl_openhandle_varp(h)->udims(); } /// Return pointer to open array data, or NULL if not in IEEE standard C layout void* svGetArrayPtr(const svOpenArrayHandle h) { const VerilatedDpiOpenVar* varp = _vl_openhandle_varp(h); if (VL_UNLIKELY(!varp->isDpiStdLayout())) return NULL; return varp->datap(); } /// Return size of open array, or 0 if not in IEEE standard C layout int svSizeOfArray(const svOpenArrayHandle h) { const VerilatedDpiOpenVar* varp = _vl_openhandle_varp(h); if (VL_UNLIKELY(!varp->isDpiStdLayout())) return 0; // Truncate 64 bits to int; DPI is limited to 4GB return static_cast<int>(varp->totalSize()); } //====================================================================== // Open array access internals static void* _vl_sv_adjusted_datap(const VerilatedDpiOpenVar* varp, int nargs, int indx1, int indx2, int indx3) { void* datap = varp->datap(); if (VL_UNLIKELY(nargs != varp->udims())) { _VL_SVDPI_WARN("%%Warning: DPI svOpenArrayHandle function called on" " %d dimensional array using %d dimensional function.\n", varp->udims(), nargs); return NULL; } if (nargs>=1) { datap = varp->datapAdjustIndex(datap, 1, indx1); if (VL_UNLIKELY(!datap)) { _VL_SVDPI_WARN("%%Warning: DPI svOpenArrayHandle function index 1 out of bounds; %d outside [%d:%d].\n", indx1, varp->left(1), varp->right(1)); return NULL; } } if (nargs>=2) { datap = varp->datapAdjustIndex(datap, 2, indx2); if (VL_UNLIKELY(!datap)) { _VL_SVDPI_WARN("%%Warning: DPI svOpenArrayHandle function index 2 out of bounds; %d outside [%d:%d].\n", indx2, varp->left(2), varp->right(2)); return NULL; } } if (nargs>=3) { datap = varp->datapAdjustIndex(datap, 3, indx3); if (VL_UNLIKELY(!datap)) { _VL_SVDPI_WARN("%%Warning: DPI svOpenArrayHandle function index 3 out of bounds; %d outside [%d:%d].\n", indx1, varp->left(3), varp->right(3)); return NULL; } } return datap; } static int _vl_sv_adjusted_bit(const VerilatedDpiOpenVar* varp, int indx) { if (VL_UNLIKELY(indx < varp->low(0) || indx > varp->high(0))) { _VL_SVDPI_WARN("%%Warning: DPI svOpenArrayHandle function packed index out of bounds; %d outside [%d:%d].\n", indx, varp->left(0), varp->right(0)); return 0; } return indx - varp->low(0); } /// Return pointer to simulator open array element, or NULL if outside range static void* _vl_svGetArrElemPtr(const svOpenArrayHandle h, int nargs, int indx1, int indx2, int indx3) VL_MT_SAFE { const VerilatedDpiOpenVar* varp = _vl_openhandle_varp(h); if (VL_UNLIKELY(!varp->isDpiStdLayout())) return NULL; void* datap = _vl_sv_adjusted_datap(varp, nargs, indx1, indx2, indx3); return datap; } /// Copy to user bit array from simulator open array static void _vl_svGetBitArrElemVecVal(svBitVecVal* d, const svOpenArrayHandle s, int nargs, int indx1, int indx2, int indx3) VL_MT_SAFE { const VerilatedDpiOpenVar* varp = _vl_openhandle_varp(s); void* datap = _vl_sv_adjusted_datap(varp, nargs, indx1, indx2, indx3); if (VL_UNLIKELY(!datap)) return; switch (varp->vltype()) { case VLVT_UINT8: d[0] = *(reinterpret_cast<CData*>(datap)); return; case VLVT_UINT16: d[0] = *(reinterpret_cast<SData*>(datap)); return; case VLVT_UINT32: d[0] = *(reinterpret_cast<IData*>(datap)); return; case VLVT_UINT64: { WData lwp[2]; VL_SET_WQ(lwp, *(reinterpret_cast<QData*>(datap))); d[0] = lwp[0]; d[1] = lwp[1]; break; } case VLVT_WDATA: { WDataOutP wdatap = (reinterpret_cast<WDataOutP>(datap)); for (int i=0; i<VL_WORDS_I(varp->packed().elements()); ++i) d[i] = wdatap[i]; return; } default: _VL_SVDPI_WARN("%%Warning: DPI svOpenArrayHandle function unsupported datatype (%d).\n", varp->vltype()); return; } } /// Copy to user logic array from simulator open array static void _vl_svGetLogicArrElemVecVal(svLogicVecVal* d, const svOpenArrayHandle s, int nargs, int indx1, int indx2, int indx3) VL_MT_SAFE { const VerilatedDpiOpenVar* varp = _vl_openhandle_varp(s); void* datap = _vl_sv_adjusted_datap(varp, nargs, indx1, indx2, indx3); if (VL_UNLIKELY(!datap)) return; switch (varp->vltype()) { case VLVT_UINT8: d[0].aval = *(reinterpret_cast<CData*>(datap)); d[0].bval=0; return; case VLVT_UINT16: d[0].aval = *(reinterpret_cast<SData*>(datap)); d[0].bval=0; return; case VLVT_UINT32: d[0].aval = *(reinterpret_cast<IData*>(datap)); d[0].bval=0; return; case VLVT_UINT64: { WData lwp[2]; VL_SET_WQ(lwp, *(reinterpret_cast<QData*>(datap))); d[0].aval = lwp[0]; d[0].bval=0; d[1].aval = lwp[1]; d[0].bval=0; break; } case VLVT_WDATA: { WDataOutP wdatap = (reinterpret_cast<WDataOutP>(datap)); for (int i=0; i<VL_WORDS_I(varp->packed().elements()); ++i) { d[i].aval = wdatap[i]; d[i].bval = 0; } return; } default: _VL_SVDPI_WARN("%%Warning: DPI svOpenArrayHandle function unsupported datatype (%d).\n", varp->vltype()); return; } } /// Copy to simulator open array from from user bit array static void _vl_svPutBitArrElemVecVal(const svOpenArrayHandle d, const svBitVecVal* s, int nargs, int indx1, int indx2, int indx3) VL_MT_SAFE { const VerilatedDpiOpenVar* varp = _vl_openhandle_varp(d); void* datap = _vl_sv_adjusted_datap(varp, nargs, indx1, indx2, indx3); if (VL_UNLIKELY(!datap)) return; switch (varp->vltype()) { case VLVT_UINT8: *(reinterpret_cast<CData*>(datap)) = s[0]; return; case VLVT_UINT16: *(reinterpret_cast<SData*>(datap)) = s[0]; return; case VLVT_UINT32: *(reinterpret_cast<IData*>(datap)) = s[0]; return; case VLVT_UINT64: *(reinterpret_cast<QData*>(datap)) = _VL_SET_QII(s[1], s[0]); break; case VLVT_WDATA: { WDataOutP wdatap = (reinterpret_cast<WDataOutP>(datap)); for (int i=0; i<VL_WORDS_I(varp->packed().elements()); ++i) wdatap[i] = s[i]; return; } default: _VL_SVDPI_WARN("%%Warning: DPI svOpenArrayHandle function unsupported datatype (%d).\n", varp->vltype()); return; } } /// Copy to simulator open array from from user logic array static void _vl_svPutLogicArrElemVecVal(const svOpenArrayHandle d, const svLogicVecVal* s, int nargs, int indx1, int indx2, int indx3) VL_MT_SAFE { const VerilatedDpiOpenVar* varp = _vl_openhandle_varp(d); void* datap = _vl_sv_adjusted_datap(varp, nargs, indx1, indx2, indx3); if (VL_UNLIKELY(!datap)) return; switch (varp->vltype()) { case VLVT_UINT8: *(reinterpret_cast<CData*>(datap)) = s[0].aval; return; case VLVT_UINT16: *(reinterpret_cast<SData*>(datap)) = s[0].aval; return; case VLVT_UINT32: *(reinterpret_cast<IData*>(datap)) = s[0].aval; return; case VLVT_UINT64: *(reinterpret_cast<QData*>(datap)) = _VL_SET_QII(s[1].aval, s[0].aval); break; case VLVT_WDATA: { WDataOutP wdatap = (reinterpret_cast<WDataOutP>(datap)); for (int i=0; i<VL_WORDS_I(varp->packed().elements()); ++i) wdatap[i] = s[i].aval; return; } default: _VL_SVDPI_WARN("%%Warning: DPI svOpenArrayHandle function unsupported datatype (%d).\n", varp->vltype()); return; } } /// Return bit from simulator open array static svBit _vl_svGetBitArrElem(const svOpenArrayHandle s, int nargs, int indx1, int indx2, int indx3, int indx4) VL_MT_SAFE { // One extra index supported, as need bit number const VerilatedDpiOpenVar* varp = _vl_openhandle_varp(s); void* datap; int lsb; if (varp->packed().elements()) { datap = _vl_sv_adjusted_datap(varp, nargs-1, indx1, indx2, indx3); lsb = _vl_sv_adjusted_bit(varp, ((nargs==1) ? indx1 : (nargs==2) ? indx2 : (nargs==3) ? indx3 : indx4)); } else { datap = _vl_sv_adjusted_datap(varp, nargs, indx1, indx2, indx3); lsb = 0; } if (VL_UNLIKELY(!datap)) return 0; switch (varp->vltype()) { case VLVT_UINT8: return (*(reinterpret_cast<CData*>(datap)) >> lsb) & 1; case VLVT_UINT16: return (*(reinterpret_cast<SData*>(datap)) >> lsb) & 1; case VLVT_UINT32: return (*(reinterpret_cast<IData*>(datap)) >> lsb) & 1; case VLVT_UINT64: return (*(reinterpret_cast<QData*>(datap)) >> static_cast<QData>(lsb)) & VL_ULL(1); case VLVT_WDATA: { WDataOutP wdatap = (reinterpret_cast<WDataOutP>(datap)); return VL_BITRSHIFT_W(wdatap, lsb) & 1; } default: _VL_SVDPI_WARN("%%Warning: DPI svOpenArrayHandle function unsupported datatype (%d).\n", varp->vltype()); return 0; } } /// Update simulator open array from bit static void _vl_svPutBitArrElem(const svOpenArrayHandle d, svBit value, int nargs, int indx1, int indx2, int indx3, int indx4) VL_MT_SAFE { // One extra index supported, as need bit number value &= 1; // Make sure clean const VerilatedDpiOpenVar* varp = _vl_openhandle_varp(d); void* datap; int lsb; if (varp->packed().elements()) { datap = _vl_sv_adjusted_datap(varp, nargs-1, indx1, indx2, indx3); lsb = _vl_sv_adjusted_bit(varp, ((nargs==1) ? indx1 : (nargs==2) ? indx2 : (nargs==3) ? indx3 : indx4)); } else { datap = _vl_sv_adjusted_datap(varp, nargs, indx1, indx2, indx3); lsb = 0; } if (VL_UNLIKELY(!datap)) return; switch (varp->vltype()) { case VLVT_UINT8: VL_ASSIGNBIT_II(-1, lsb, *(reinterpret_cast<CData*>(datap)), value); return; case VLVT_UINT16: VL_ASSIGNBIT_II(-1, lsb, *(reinterpret_cast<SData*>(datap)), value); return; case VLVT_UINT32: VL_ASSIGNBIT_II(-1, lsb, *(reinterpret_cast<IData*>(datap)), value); return; case VLVT_UINT64: VL_ASSIGNBIT_QI(-1, lsb, *(reinterpret_cast<QData*>(datap)), value); return; case VLVT_WDATA: VL_ASSIGNBIT_WI(-1, lsb, (reinterpret_cast<WDataOutP>(datap)), value); return; default: _VL_SVDPI_WARN("%%Warning: DPI svOpenArrayHandle function unsupported datatype (%d).\n", varp->vltype()); return; } } //====================================================================== // DPI accessors that simply call above functions void* svGetArrElemPtr(const svOpenArrayHandle h, int indx1, ...) { const VerilatedDpiOpenVar* varp = _vl_openhandle_varp(h); void* datap; va_list ap; va_start(ap, indx1); // va_arg is a macro, so need temporaries as used below switch (varp->udims()) { case 1: datap = _vl_svGetArrElemPtr(h, 1, indx1, 0, 0); break; case 2: { int indx2=va_arg(ap,int); datap = _vl_svGetArrElemPtr(h, 2, indx1, indx2, 0); break; } case 3: { int indx2=va_arg(ap,int); int indx3=va_arg(ap,int); datap = _vl_svGetArrElemPtr(h, 3, indx1, indx2, indx3); break; } default: datap = _vl_svGetArrElemPtr(h, -1, 0, 0, 0); break; // Will error } va_end(ap); return datap; } void* svGetArrElemPtr1(const svOpenArrayHandle h, int indx1) { return _vl_svGetArrElemPtr(h, 1, indx1, 0, 0); } void* svGetArrElemPtr2(const svOpenArrayHandle h, int indx1, int indx2) { return _vl_svGetArrElemPtr(h, 2, indx1, indx2, 0); } void* svGetArrElemPtr3(const svOpenArrayHandle h, int indx1, int indx2, int indx3) { return _vl_svGetArrElemPtr(h, 3, indx1, indx2, indx3); } void svPutBitArrElemVecVal(const svOpenArrayHandle d, const svBitVecVal* s, int indx1, ...) { const VerilatedDpiOpenVar* varp = _vl_openhandle_varp(d); va_list ap; va_start(ap, indx1); switch (varp->udims()) { case 1: _vl_svPutBitArrElemVecVal(d, s, 1, indx1, 0, 0); break; case 2: { int indx2=va_arg(ap,int); _vl_svPutBitArrElemVecVal(d, s, 2, indx1, indx2, 0); break; } case 3: { int indx2=va_arg(ap,int); int indx3=va_arg(ap,int); _vl_svPutBitArrElemVecVal(d, s, 3, indx1, indx2, indx3); break; } default: _vl_svPutBitArrElemVecVal(d, s, -1, 0, 0, 0); break; // Will error } va_end(ap); } void svPutBitArrElem1VecVal(const svOpenArrayHandle d, const svBitVecVal* s, int indx1) { _vl_svPutBitArrElemVecVal(d, s, 1, indx1, 0, 0); } void svPutBitArrElem2VecVal(const svOpenArrayHandle d, const svBitVecVal* s, int indx1, int indx2) { _vl_svPutBitArrElemVecVal(d, s, 2, indx1, indx2, 0); } void svPutBitArrElem3VecVal(const svOpenArrayHandle d, const svBitVecVal* s, int indx1, int indx2, int indx3) { _vl_svPutBitArrElemVecVal(d, s, 3, indx1, indx2, indx3); } void svPutLogicArrElemVecVal(const svOpenArrayHandle d, const svLogicVecVal* s, int indx1, ...) { const VerilatedDpiOpenVar* varp = _vl_openhandle_varp(d); va_list ap; va_start(ap, indx1); switch (varp->udims()) { case 1: _vl_svPutLogicArrElemVecVal(d, s, 1, indx1, 0, 0); break; case 2: { int indx2=va_arg(ap,int); _vl_svPutLogicArrElemVecVal(d, s, 2, indx1, indx2, 0); break; } case 3: { int indx2=va_arg(ap,int); int indx3=va_arg(ap,int); _vl_svPutLogicArrElemVecVal(d, s, 3, indx1, indx2, indx3); break; } default: _vl_svPutLogicArrElemVecVal(d, s, -1, 0, 0, 0); break; // Will error } va_end(ap); } void svPutLogicArrElem1VecVal(const svOpenArrayHandle d, const svLogicVecVal* s, int indx1) { _vl_svPutLogicArrElemVecVal(d, s, 1, indx1, 0, 0); } void svPutLogicArrElem2VecVal(const svOpenArrayHandle d, const svLogicVecVal* s, int indx1, int indx2) { _vl_svPutLogicArrElemVecVal(d, s, 2, indx1, indx2, 0); } void svPutLogicArrElem3VecVal(const svOpenArrayHandle d, const svLogicVecVal* s, int indx1, int indx2, int indx3) { _vl_svPutLogicArrElemVecVal(d, s, 3, indx1, indx2, indx3); } //====================================================================== // From simulator storage into user space void svGetBitArrElemVecVal(svBitVecVal* d, const svOpenArrayHandle s, int indx1, ...) { const VerilatedDpiOpenVar* varp = _vl_openhandle_varp(s); va_list ap; va_start(ap, indx1); switch (varp->udims()) { case 1: _vl_svGetBitArrElemVecVal(d, s, 1, indx1, 0, 0); break; case 2: { int indx2=va_arg(ap,int); _vl_svGetBitArrElemVecVal(d, s, 2, indx1, indx2, 0); break; } case 3: { int indx2=va_arg(ap,int); int indx3=va_arg(ap,int); _vl_svGetBitArrElemVecVal(d, s, 3, indx1, indx2, indx3); break; } default: _vl_svGetBitArrElemVecVal(d, s, -1, 0, 0, 0); break; // Will error } va_end(ap); } void svGetBitArrElem1VecVal(svBitVecVal* d, const svOpenArrayHandle s, int indx1) { _vl_svGetBitArrElemVecVal(d, s, 1, indx1, 0, 0); } void svGetBitArrElem2VecVal(svBitVecVal* d, const svOpenArrayHandle s, int indx1, int indx2) { _vl_svGetBitArrElemVecVal(d, s, 2, indx1, indx2, 0); } void svGetBitArrElem3VecVal(svBitVecVal* d, const svOpenArrayHandle s, int indx1, int indx2, int indx3) { _vl_svGetBitArrElemVecVal(d, s, 3, indx1, indx2, indx3); } void svGetLogicArrElemVecVal(svLogicVecVal* d, const svOpenArrayHandle s, int indx1, ...) { const VerilatedDpiOpenVar* varp = _vl_openhandle_varp(s); va_list ap; va_start(ap, indx1); switch (varp->udims()) { case 1: _vl_svGetLogicArrElemVecVal(d, s, 1, indx1, 0, 0); break; case 2: { int indx2=va_arg(ap,int); _vl_svGetLogicArrElemVecVal(d, s, 2, indx1, indx2, 0); break; } case 3: { int indx2=va_arg(ap,int); int indx3=va_arg(ap,int); _vl_svGetLogicArrElemVecVal(d, s, 3, indx1, indx2, indx3); break; } default: _vl_svGetLogicArrElemVecVal(d, s, -1, 0, 0, 0); break; // Will error } va_end(ap); } void svGetLogicArrElem1VecVal(svLogicVecVal* d, const svOpenArrayHandle s, int indx1) { _vl_svGetLogicArrElemVecVal(d, s, 1, indx1, 0, 0); } void svGetLogicArrElem2VecVal(svLogicVecVal* d, const svOpenArrayHandle s, int indx1, int indx2) { _vl_svGetLogicArrElemVecVal(d, s, 2, indx1, indx2, 0); } void svGetLogicArrElem3VecVal(svLogicVecVal* d, const svOpenArrayHandle s, int indx1, int indx2, int indx3) { _vl_svGetLogicArrElemVecVal(d, s, 3, indx1, indx2, indx3); } svBit svGetBitArrElem(const svOpenArrayHandle s, int indx1, ...) { const VerilatedDpiOpenVar* varp = _vl_openhandle_varp(s); svBit out; va_list ap; va_start(ap, indx1); switch (varp->udims()) { case 1: out = _vl_svGetBitArrElem(s, 1, indx1, 0, 0, 0); break; case 2: { int indx2=va_arg(ap,int); out = _vl_svGetBitArrElem(s, 2, indx1, indx2, 0, 0); break; } case 3: { int indx2=va_arg(ap,int); int indx3=va_arg(ap,int); out = _vl_svGetBitArrElem(s, 3, indx1, indx2, indx3, 0); break; } case 4: { int indx2=va_arg(ap,int); int indx3=va_arg(ap,int); int indx4=va_arg(ap,int); out = _vl_svGetBitArrElem(s, 4, indx1, indx2, indx3, indx4); break; } default: out = _vl_svGetBitArrElem(s, -1, 0, 0, 0, 0); break; // Will error } va_end(ap); return out; } svBit svGetBitArrElem1(const svOpenArrayHandle s, int indx1) { return _vl_svGetBitArrElem(s, 1, indx1, 0, 0, 0); } svBit svGetBitArrElem2(const svOpenArrayHandle s, int indx1, int indx2) { return _vl_svGetBitArrElem(s, 2, indx1, indx2, 0, 0); } svBit svGetBitArrElem3(const svOpenArrayHandle s, int indx1, int indx2, int indx3) { return _vl_svGetBitArrElem(s, 3, indx1, indx2, indx3, 0); } svLogic svGetLogicArrElem(const svOpenArrayHandle s, int indx1, ...) { // Verilator doesn't support X/Z so can just call Bit version const VerilatedDpiOpenVar* varp = _vl_openhandle_varp(s); svBit out; va_list ap; va_start(ap, indx1); switch (varp->udims()) { case 1: out = _vl_svGetBitArrElem(s, 1, indx1, 0, 0, 0); break; case 2: { int indx2=va_arg(ap,int); out = _vl_svGetBitArrElem(s, 2, indx1, indx2, 0, 0); break; } case 3: { int indx2=va_arg(ap,int); int indx3=va_arg(ap,int); out = _vl_svGetBitArrElem(s, 3, indx1, indx2, indx3, 0); break; } case 4: { int indx2=va_arg(ap,int); int indx3=va_arg(ap,int); int indx4=va_arg(ap,int); out = _vl_svGetBitArrElem(s, 4, indx1, indx2, indx3, indx4); break; } default: out = _vl_svGetBitArrElem(s, -1, 0, 0, 0, 0); break; // Will error } va_end(ap); return out; } svLogic svGetLogicArrElem1(const svOpenArrayHandle s, int indx1) { // Verilator doesn't support X/Z so can just call Bit version return svGetBitArrElem1(s, indx1); } svLogic svGetLogicArrElem2(const svOpenArrayHandle s, int indx1, int indx2) { // Verilator doesn't support X/Z so can just call Bit version return svGetBitArrElem2(s, indx1, indx2); } svLogic svGetLogicArrElem3(const svOpenArrayHandle s, int indx1, int indx2, int indx3) { // Verilator doesn't support X/Z so can just call Bit version return svGetBitArrElem3(s, indx1, indx2, indx3); } void svPutBitArrElem(const svOpenArrayHandle d, svBit value, int indx1, ...) { const VerilatedDpiOpenVar* varp = _vl_openhandle_varp(d); va_list ap; va_start(ap, indx1); switch (varp->udims()) { case 1: _vl_svPutBitArrElem(d, value, 1, indx1, 0, 0, 0); break; case 2: { int indx2=va_arg(ap,int); _vl_svPutBitArrElem(d, value, 2, indx1, indx2, 0, 0); break; } case 3: { int indx2=va_arg(ap,int); int indx3=va_arg(ap,int); _vl_svPutBitArrElem(d, value, 3, indx1, indx2, indx3, 0); break; } case 4: { int indx2=va_arg(ap,int); int indx3=va_arg(ap,int); int indx4=va_arg(ap,int); _vl_svPutBitArrElem(d, value, 4, indx1, indx2, indx3, indx4); break; } default: _vl_svPutBitArrElem(d, value, -1, 0, 0, 0, 0); break; // Will error } va_end(ap); } void svPutBitArrElem1(const svOpenArrayHandle d, svBit value, int indx1) { _vl_svPutBitArrElem(d, value, 1, indx1, 0, 0, 0); } void svPutBitArrElem2(const svOpenArrayHandle d, svBit value, int indx1, int indx2) { _vl_svPutBitArrElem(d, value, 2, indx1, indx2, 0, 0); } void svPutBitArrElem3(const svOpenArrayHandle d, svBit value, int indx1, int indx2, int indx3) { _vl_svPutBitArrElem(d, value, 3, indx1, indx2, indx3, 0); } void svPutLogicArrElem(const svOpenArrayHandle d, svLogic value, int indx1, ...) { // Verilator doesn't support X/Z so can just call Bit version const VerilatedDpiOpenVar* varp = _vl_openhandle_varp(d); va_list ap; va_start(ap, indx1); switch (varp->udims()) { case 1: _vl_svPutBitArrElem(d, value, 1, indx1, 0, 0, 0); break; case 2: { int indx2=va_arg(ap,int); _vl_svPutBitArrElem(d, value, 2, indx1, indx2, 0, 0); break; } case 3: { int indx2=va_arg(ap,int); int indx3=va_arg(ap,int); _vl_svPutBitArrElem(d, value, 3, indx1, indx2, indx3, 0); break; } case 4: { int indx2=va_arg(ap,int); int indx3=va_arg(ap,int); int indx4=va_arg(ap,int); _vl_svPutBitArrElem(d, value, 4, indx1, indx2, indx3, indx4); break; } default: _vl_svPutBitArrElem(d, value, -1, 0, 0, 0, 0); break; // Will error } va_end(ap); } void svPutLogicArrElem1(const svOpenArrayHandle d, svLogic value, int indx1) { // Verilator doesn't support X/Z so can just call Bit version svPutBitArrElem1(d, value, indx1); } void svPutLogicArrElem2(const svOpenArrayHandle d, svLogic value, int indx1, int indx2) { // Verilator doesn't support X/Z so can just call Bit version svPutBitArrElem2(d, value, indx1, indx2); } void svPutLogicArrElem3(const svOpenArrayHandle d, svLogic value, int indx1, int indx2, int indx3) { // Verilator doesn't support X/Z so can just call Bit version svPutBitArrElem3(d, value, indx1, indx2, indx3); } //====================================================================== // Functions for working with DPI context svScope svGetScope() { if (VL_UNLIKELY(!Verilated::dpiInContext())) { _VL_SVDPI_CONTEXT_WARN(); return NULL; } // NOLINTNEXTLINE(google-readability-casting) return (svScope)(Verilated::dpiScope()); } svScope svSetScope(const svScope scope) { const VerilatedScope* prevScopep = Verilated::dpiScope(); const VerilatedScope* vscopep = reinterpret_cast<const VerilatedScope*>(scope); Verilated::dpiScope(vscopep); // NOLINTNEXTLINE(google-readability-casting) return (svScope)(prevScopep); } const char* svGetNameFromScope(const svScope scope) { const VerilatedScope* vscopep = reinterpret_cast<const VerilatedScope*>(scope); return vscopep->name(); } svScope svGetScopeFromName(const char* scopeName) { // NOLINTNEXTLINE(google-readability-casting) return (svScope)(VerilatedImp::scopeFind(scopeName)); } int svPutUserData(const svScope scope, void* userKey, void* userData) { VerilatedImp::userInsert(scope,userKey,userData); return 0; } void* svGetUserData(const svScope scope, void* userKey) { return VerilatedImp::userFind(scope,userKey); } int svGetCallerInfo(const char** fileNamepp, int *lineNumberp) { if (VL_UNLIKELY(!Verilated::dpiInContext())) { _VL_SVDPI_CONTEXT_WARN(); return false; } if (VL_LIKELY(fileNamepp)) *fileNamepp = Verilated::dpiFilenamep(); // thread local if (VL_LIKELY(lineNumberp)) *lineNumberp = Verilated::dpiLineno(); // thread local return true; } //====================================================================== // Disables int svIsDisabledState() { return 0; // Disables not implemented } void svAckDisabledState() { // Disables not implemented } <|start_filename|>basic/lesson3/verilator/sim/sim_video.h<|end_filename|> #pragma once #include <string> #ifndef _MSC_VER #include "imgui_impl_sdl.h" #include "imgui_impl_opengl2.h" #else #define WIN32 #include "imgui_impl_win32.h" #include "imgui_impl_dx11.h" #include <d3d11.h> #include <tchar.h> #endif struct SimVideo { public: int output_width; int output_height; int output_rotate; bool output_vflip; int count_pixel; int count_line; int count_frame; float stats_fps; float stats_frameTime; int stats_xMax; int stats_xMin; int stats_yMax; int stats_yMin; ImTextureID texture_id; SimVideo(int width, int height, int rotate); ~SimVideo(); void UpdateTexture(); void CleanUp(); void StartFrame(); void Clock(bool hblank, bool vblank, uint32_t colour); int Initialise(const char* windowTitle); }; <|start_filename|>basic/lesson3/verilator/sim/vinc/verilated_threads.h<|end_filename|> // -*- mode: C++; c-file-style: "cc-mode" -*- //============================================================================= // // THIS MODULE IS PUBLICLY LICENSED // // Copyright 2012-2020 by <NAME>. This program is free software; // you can redistribute it and/or modify it under the terms of either the GNU // Lesser General Public License Version 3 or the Perl Artistic License Version 2.0. // // This is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // //============================================================================= /// /// \file /// \brief Thread pool and profiling for Verilated modules /// //============================================================================= #ifndef _VERILATED_THREADS_H_ #define _VERILATED_THREADS_H_ #include "verilatedos.h" #include "verilated.h" // for VerilatedMutex and clang annotations #include <condition_variable> #include <set> #include <vector> #if defined(__linux) #include <sched.h> // For sched_getcpu() #endif #if defined(__APPLE__) # include <cpuid.h> // For __cpuid_count() #endif // VlMTaskVertex and VlThreadpool will work with multiple symbol table types. // Since the type is opaque to VlMTaskVertex and VlThreadPool, represent it // as a void* here. typedef void* VlThrSymTab; typedef void (*VlExecFnp)(bool, VlThrSymTab); /// Track dependencies for a single MTask. class VlMTaskVertex { // MEMBERS static std::atomic<vluint64_t> s_yields; // Statistics // On even cycles, _upstreamDepsDone increases as upstream // dependencies complete. When it reaches _upstreamDepCount, // this MTaskVertex is ready. // // On odd cycles, _upstreamDepsDone decreases as upstream // dependencies complete, and when it reaches zero this MTaskVertex // is ready. // // An atomic is smaller than a mutex, and lock-free. // // (Why does the size of this class matter? If an mtask has many // downstream mtasks to notify, we hope these will pack into a // small number of cache lines to reduce the cost of pointer chasing // during done-notification. Nobody's quantified that cost though. // If we were really serious about shrinking this class, we could // use 16-bit types here...) std::atomic<vluint32_t> m_upstreamDepsDone; const vluint32_t m_upstreamDepCount; public: // CONSTRUCTORS // 'upstreamDepCount' is the number of upstream MTaskVertex's // that must notify this MTaskVertex before it will become ready // to run. explicit VlMTaskVertex(vluint32_t upstreamDepCount); ~VlMTaskVertex() {} static vluint64_t yields() { return s_yields; } static void yieldThread() { ++s_yields; // Statistics std::this_thread::yield(); } // Upstream mtasks must call this when they complete. // Returns true when the current MTaskVertex becomes ready to execute, // false while it's still waiting on more dependencies. inline bool signalUpstreamDone(bool evenCycle) { if (evenCycle) { vluint32_t upstreamDepsDone = 1 + m_upstreamDepsDone.fetch_add(1, std::memory_order_release); assert(upstreamDepsDone <= m_upstreamDepCount); return (upstreamDepsDone == m_upstreamDepCount); } else { vluint32_t upstreamDepsDone_prev = m_upstreamDepsDone.fetch_sub(1, std::memory_order_release); assert(upstreamDepsDone_prev > 0); return (upstreamDepsDone_prev == 1); } } inline bool areUpstreamDepsDone(bool evenCycle) const { vluint32_t target = evenCycle ? m_upstreamDepCount : 0; return m_upstreamDepsDone.load(std::memory_order_acquire) == target; } inline void waitUntilUpstreamDone(bool evenCycle) const { unsigned ct = 0; while (VL_UNLIKELY(!areUpstreamDepsDone(evenCycle))) { VL_CPU_RELAX(); ++ct; if (VL_UNLIKELY(ct > VL_LOCK_SPINS)) { ct = 0; yieldThread(); } } } }; // Profiling support class VlProfileRec { protected: friend class VlThreadPool; enum VlProfileE { TYPE_MTASK_RUN, TYPE_BARRIER }; VlProfileE m_type; // Record type vluint32_t m_mtaskId; // Mtask we're logging vluint32_t m_predictTime; // How long scheduler predicted would take vluint64_t m_startTime; // Tick at start of execution vluint64_t m_endTime; // Tick at end of execution unsigned m_cpu; // Execution CPU number (at start anyways) public: class Barrier {}; VlProfileRec() {} explicit VlProfileRec(Barrier) { m_type = TYPE_BARRIER; m_mtaskId = 0; m_predictTime = 0; m_startTime = 0; m_endTime = 0; m_cpu = getcpu(); } void startRecord(vluint64_t time, uint32_t mtask, uint32_t predict) { m_type = VlProfileRec::TYPE_MTASK_RUN; m_mtaskId = mtask; m_predictTime = predict; m_startTime = time; m_cpu = getcpu(); } void endRecord(vluint64_t time) { m_endTime = time; } static int getcpu() { // Return current executing CPU #if defined(__linux) return sched_getcpu(); #elif defined(__APPLE__) vluint32_t info[4]; __cpuid_count(1, 0, info[0], info[1], info[2], info[3]); // info[1] is EBX, bits 24-31 are APIC ID if ((info[3] & (1 << 9)) == 0) { return -1; // no APIC on chip } else { return (unsigned)info[1] >> 24; } #elif defined(_WIN32) return GetCurrentProcessorNumber(); #else return 0; #endif } }; class VlThreadPool; class VlWorkerThread { private: // TYPES struct ExecRec { VlExecFnp m_fnp; // Function to execute VlThrSymTab m_sym; // Symbol table to execute bool m_evenCycle; // Even/odd for flag alternation ExecRec() : m_fnp(NULL), m_sym(NULL), m_evenCycle(false) {} ExecRec(VlExecFnp fnp, bool evenCycle, VlThrSymTab sym) : m_fnp(fnp), m_sym(sym), m_evenCycle(evenCycle) {} }; // MEMBERS VerilatedMutex m_mutex; std::condition_variable_any m_cv; // Only notify the condition_variable if the worker is waiting bool m_waiting VL_GUARDED_BY(m_mutex); // Why a vector? We expect the pending list to be very short, typically // 0 or 1 or 2, so popping from the front shouldn't be // expensive. Revisit if we ever have longer queues... std::vector<ExecRec> m_ready VL_GUARDED_BY(m_mutex); // Store the size atomically, so we can spin wait std::atomic<size_t> m_ready_size; VlThreadPool* m_poolp; // Our associated thread pool bool m_profiling; // Is profiling enabled? std::atomic<bool> m_exiting; // Worker thread should exit std::thread m_cthread; // Underlying C++ thread record VL_UNCOPYABLE(VlWorkerThread); public: // CONSTRUCTORS explicit VlWorkerThread(VlThreadPool* poolp, bool profiling); ~VlWorkerThread(); // METHODS inline void dequeWork(ExecRec* workp) { // Spin for a while, waiting for new data for (int i = 0; i < VL_LOCK_SPINS; ++i) { if (VL_LIKELY(m_ready_size.load(std::memory_order_relaxed))) { break; } VL_CPU_RELAX(); } VerilatedLockGuard lk(m_mutex); while (m_ready.empty()) { m_waiting = true; m_cv.wait(lk); } m_waiting = false; // As noted above this is inefficient if our ready list is ever // long (but it shouldn't be) *workp = m_ready.front(); m_ready.erase(m_ready.begin()); m_ready_size.fetch_sub(1, std::memory_order_relaxed); } inline void wakeUp() { addTask(nullptr, false, nullptr); } inline void addTask(VlExecFnp fnp, bool evenCycle, VlThrSymTab sym) { bool notify; { VerilatedLockGuard lk(m_mutex); m_ready.emplace_back(fnp, evenCycle, sym); m_ready_size.fetch_add(1, std::memory_order_relaxed); notify = m_waiting; } if (notify) m_cv.notify_one(); } void workerLoop(); static void startWorker(VlWorkerThread* workerp); }; class VlThreadPool { // TYPES typedef std::vector<VlProfileRec> ProfileTrace; typedef std::set<ProfileTrace*> ProfileSet; // MEMBERS std::vector<VlWorkerThread*> m_workers; // our workers bool m_profiling; // is profiling enabled? // Support profiling -- we can append records of profiling events // to this vector with very low overhead, and then dump them out // later. This prevents the overhead of printf/malloc/IO from // corrupting the profiling data. It's super cheap to append // a VlProfileRec struct on the end of a pre-allocated vector; // this is the only cost we pay in real-time during a profiling cycle. static VL_THREAD_LOCAL ProfileTrace* t_profilep; ProfileSet m_allProfiles VL_GUARDED_BY(m_mutex); VerilatedMutex m_mutex; public: // CONSTRUCTORS // Construct a thread pool with 'nThreads' dedicated threads. The thread // pool will create these threads and make them available to execute tasks // via this->workerp(index)->addTask(...) VlThreadPool(int nThreads, bool profiling); ~VlThreadPool(); // METHODS inline int numThreads() const { return m_workers.size(); } inline VlWorkerThread* workerp(int index) { assert(index >= 0); assert(index < m_workers.size()); return m_workers[index]; } inline VlProfileRec* profileAppend() { t_profilep->emplace_back(); return &(t_profilep->back()); } void profileAppendAll(const VlProfileRec& rec); void profileDump(const char* filenamep, vluint64_t ticksElapsed); // In profiling mode, each executing thread must call // this once to setup profiling state: void setupProfilingClientThread(); void tearDownProfilingClientThread(); private: VL_UNCOPYABLE(VlThreadPool); }; #endif <|start_filename|>basic/lesson3/verilator/sim/sim_clock.h<|end_filename|> #pragma once class SimClock { public: bool clk, old; SimClock(int r); ~SimClock(); void Tick(); void Reset(); private: int ratio, count; }; <|start_filename|>basic/lesson2/verilator/sim_main.cpp<|end_filename|> #include <iostream> #include <fstream> #include <string> #include <stdio.h> #include <stdlib.h> #include <math.h> //#include <atomic> //#include <fstream> #include <verilated.h> #include "Vtop.h" #ifndef _MSC_VER #include "imgui/imgui.h" #include "imgui/imgui_impl_sdl.h" #include "imgui/imgui_impl_opengl2.h" #include <stdio.h> #include <SDL.h> #include <SDL_opengl.h> #else #define WIN32 #include "imgui.h" #include "imgui_impl_win32.h" #include "imgui_impl_dx11.h" #include <d3d11.h> #define DIRECTINPUT_VERSION 0x0800 #include <dinput.h> #include <tchar.h> #endif #include "../imgui/imgui_memory_editor.h" FILE *ioctl_file=NULL; int ioctl_next_addr = 0x0; #ifndef WIN32 SDL_Renderer * renderer =NULL; SDL_Texture * texture =NULL; #else // DirectX data static ID3D11Device* g_pd3dDevice = NULL; static ID3D11DeviceContext* g_pd3dDeviceContext = NULL; static IDXGIFactory* g_pFactory = NULL; static ID3D11Buffer* g_pVB = NULL; static ID3D11Buffer* g_pIB = NULL; static ID3D10Blob* g_pVertexShaderBlob = NULL; static ID3D11VertexShader* g_pVertexShader = NULL; static ID3D11InputLayout* g_pInputLayout = NULL; static ID3D11Buffer* g_pVertexConstantBuffer = NULL; static ID3D10Blob* g_pPixelShaderBlob = NULL; static ID3D11PixelShader* g_pPixelShader = NULL; static ID3D11SamplerState* g_pFontSampler = NULL; static ID3D11ShaderResourceView*g_pFontTextureView = NULL; static ID3D11RasterizerState* g_pRasterizerState = NULL; static ID3D11BlendState* g_pBlendState = NULL; static ID3D11DepthStencilState* g_pDepthStencilState = NULL; static int g_VertexBufferSize = 5000, g_IndexBufferSize = 10000; #endif // Instantiation of module. Vtop* top = NULL; char my_string[1024]; int str_i = 0; unsigned int file_size; unsigned int row; unsigned int col; unsigned int bank; unsigned int dram_address; int pix_count = 0; unsigned char rgb[3]; bool prev_vsync = 0; int frame_count = 0; bool vga_file_select = 0; bool prev_hsync = 0; int line_count = 0; bool prev_sram_we_n = 0; uint32_t inst_data_temp; uint32_t prev_pc = 0xDEADBEEF; unsigned int avm_byte_addr; unsigned int avm_word_addr; unsigned int burstcount; unsigned int byteenable; unsigned int writedata; unsigned int datamux; // What the aoR3000 core is actually reading from the bus! Only valid when avm_readdata_valid is High! unsigned int datatemp; unsigned int old_pc; unsigned int inst_count = 0; unsigned int old_hw_addr; unsigned int hw_count = 0; bool trigger1 = 0; bool trigger2 = 0; int trig_count = 0; uint16_t byteena_bits; bool ram_read_flag = 0; bool ram_write_flag = 0; FILE *vgap; int last_sdram_writedata = 0; int last_sdram_byteaddr = 0; int last_sdram_ben = 0; bool run_enable = 0; bool single_step = 0; bool multi_step = 0; int multi_step_amount = 1024; void ioctl_download_before_eval(void); void ioctl_download_after_eval(void); #ifdef WIN32 // Data static IDXGISwapChain* g_pSwapChain = NULL; static ID3D11RenderTargetView* g_mainRenderTargetView = NULL; void CreateRenderTarget() { ID3D11Texture2D* pBackBuffer; g_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer); g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &g_mainRenderTargetView); pBackBuffer->Release(); } void CleanupRenderTarget() { if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = NULL; } } HRESULT CreateDeviceD3D(HWND hWnd) { // Setup swap chain DXGI_SWAP_CHAIN_DESC sd; ZeroMemory(&sd, sizeof(sd)); sd.BufferCount = 2; sd.BufferDesc.Width = 0; sd.BufferDesc.Height = 0; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = hWnd; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.Windowed = TRUE; sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; UINT createDeviceFlags = 0; //createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; D3D_FEATURE_LEVEL featureLevel; const D3D_FEATURE_LEVEL featureLevelArray[2] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0, }; if (D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext) != S_OK) return E_FAIL; CreateRenderTarget(); return S_OK; } void CleanupDeviceD3D() { CleanupRenderTarget(); if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = NULL; } if (g_pd3dDeviceContext) { g_pd3dDeviceContext->Release(); g_pd3dDeviceContext = NULL; } if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; } } extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) return true; switch (msg) { case WM_SIZE: if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) { CleanupRenderTarget(); g_pSwapChain->ResizeBuffers(0, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam), DXGI_FORMAT_UNKNOWN, 0); CreateRenderTarget(); } return 0; case WM_SYSCOMMAND: if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu return 0; break; case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(hWnd, msg, wParam, lParam); } #else #endif static float values[90] = { 0 }; static int values_offset = 0; vluint64_t main_time = 0; // Current simulation time. unsigned char buffer[16]; uint32_t *bios_ptr = NULL; uint32_t *cart_ptr = NULL; uint32_t *ram_ptr = NULL; uint32_t *vram_ptr = NULL; uint32_t *disp_ptr = NULL; uint32_t *vga_ptr = NULL; unsigned int bios_size = 1024 * 256 * 4; // 1MB. (32-bit wide). //uint32_t *bios_ptr = (uint32_t *) malloc(bios_size); unsigned int cart_size = 1024 * 1024 * 4; // 16MB. (32-bit wide). //uint32_t *cart_ptr = (uint32_t *)malloc(cart_size); unsigned int ram_size = 1024 * 512 * 4; // 2MB. (32-bit wide). //uint32_t *ram_ptr = (uint32_t *) malloc(ram_size); unsigned int vram_size = 1024 * 1024 * 4; // 4MB. (32-bit wide). //uint32_t *vram_ptr = (uint32_t *) malloc(vram_size); #define VGA_WIDTH 1024 #define VGA_HEIGHT 1024 unsigned int jdisp_size = 1024 * 1024 * 4; // 4MB. (32-bit wide). //uint32_t *jptr = (uint32_t *)malloc(jdisp_size); unsigned int disp_size = 1024 * 1024 * 4; // 4MB. (32-bit wide). //uint32_t *disp_ptr = (uint32_t *)malloc(disp_size); uint32_t vga_size = 1024 * 1024 * 4; // 4MB. (32-bit wide). //uint32_t *vga_ptr = (uint32_t *) malloc(vga_size); uint32_t first_cmd_word = 0; bool bios_rom_loaded = 0; bool cart_rom_loaded = 0; uint8_t clk_cnt = 0; double sc_time_stamp () { // Called by $time in Verilog. return main_time; } ImVector<char*> Items; static char* Strdup(const char *str) { size_t len = strlen(str) + 1; void* buf = malloc(len); IM_ASSERT(buf); return (char*)memcpy(buf, (const void*)str, len); } // Demonstrate creating a simple console window, with scrolling, filtering, completion and history. // For the console example, here we are using a more C++ like approach of declaring a class to hold the data and the functions. struct ExampleAppConsole { char InputBuf[256]; ImVector<const char*> Commands; ImVector<char*> History; int HistoryPos; // -1: new line, 0..History.Size-1 browsing history. ImGuiTextFilter Filter; bool AutoScroll; bool ScrollToBottom; void AddLog(const char* fmt, ...) IM_FMTARGS(2) { // FIXME-OPT char buf[1024]; va_list args; va_start(args, fmt); vsnprintf(buf, IM_ARRAYSIZE(buf), fmt, args); buf[IM_ARRAYSIZE(buf) - 1] = 0; va_end(args); Items.push_back(Strdup(buf)); } ExampleAppConsole() { ClearLog(); memset(InputBuf, 0, sizeof(InputBuf)); HistoryPos = -1; Commands.push_back("HELP"); Commands.push_back("HISTORY"); Commands.push_back("CLEAR"); Commands.push_back("CLASSIFY"); // "classify" is only here to provide an example of "C"+[tab] completing to "CL" and displaying matches. AutoScroll = true; ScrollToBottom = false; AddLog("Sim start"); AddLog(""); } ~ExampleAppConsole() { ClearLog(); for (int i = 0; i < History.Size; i++) free(History[i]); } // Portable helpers static int Stricmp(const char* str1, const char* str2) { int d; while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } return d; } static int Strnicmp(const char* str1, const char* str2, int n) { int d = 0; while (n > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; n--; } return d; } // static char* Strdup(const char *str) { size_t len = strlen(str) + 1; void* buf = malloc(len); IM_ASSERT(buf); return (char*)memcpy(buf, (const void*)str, len); } static void Strtrim(char* str) { char* str_end = str + strlen(str); while (str_end > str && str_end[-1] == ' ') str_end--; *str_end = 0; } void ClearLog() { for (int i = 0; i < Items.Size; i++) free(Items[i]); Items.clear(); } /* void AddLog(const char* fmt, ...) IM_FMTARGS(2) { // FIXME-OPT char buf[1024]; va_list args; va_start(args, fmt); vsnprintf(buf, IM_ARRAYSIZE(buf), fmt, args); buf[IM_ARRAYSIZE(buf) - 1] = 0; va_end(args); Items.push_back(Strdup(buf)); } */ void Draw(const char* title, bool* p_open) { ImGui::SetNextWindowSize(ImVec2(520, 600), ImGuiCond_FirstUseEver); if (!ImGui::Begin(title, p_open)) { ImGui::End(); return; } // As a specific feature guaranteed by the library, after calling Begin() the last Item represent the title bar. So e.g. IsItemHovered() will return true when hovering the title bar. // Here we create a context menu only available from the title bar. if (ImGui::BeginPopupContextItem()) { if (ImGui::MenuItem("Close Console")) *p_open = false; ImGui::EndPopup(); } //ImGui::TextWrapped("This example implements a console with basic coloring, completion and history. A more elaborate implementation may want to store entries along with extra data such as timestamp, emitter, etc."); //ImGui::TextWrapped("Enter 'HELP' for help, press TAB to use text completion."); // TODO: display items starting from the bottom if (ImGui::SmallButton("Clear")) { ClearLog(); } ImGui::SameLine(); bool copy_to_clipboard = ImGui::SmallButton("Copy"); ImGui::Separator(); // Options menu if (ImGui::BeginPopup("Options")) { ImGui::Checkbox("Auto-scroll", &AutoScroll); ImGui::EndPopup(); } // Options, Filter if (ImGui::Button("Options")) ImGui::OpenPopup("Options"); ImGui::SameLine(); Filter.Draw("Filter (\"incl,-excl\") (\"error\")", 180); ImGui::Separator(); const float footer_height_to_reserve = ImGui::GetStyle().ItemSpacing.y + ImGui::GetFrameHeightWithSpacing(); // 1 separator, 1 input text ImGui::BeginChild("ScrollingRegion", ImVec2(0, -footer_height_to_reserve), false, ImGuiWindowFlags_HorizontalScrollbar); // Leave room for 1 separator + 1 InputText if (ImGui::BeginPopupContextWindow()) { if (ImGui::Selectable("Clear")) ClearLog(); ImGui::EndPopup(); } // Display every line as a separate entry so we can change their color or add custom widgets. If you only want raw text you can use ImGui::TextUnformatted(log.begin(), log.end()); // NB- if you have thousands of entries this approach may be too inefficient and may require user-side clipping to only process visible items. // You can seek and display only the lines that are visible using the ImGuiListClipper helper, if your elements are evenly spaced and you have cheap random access to the elements. // To use the clipper we could replace the 'for (int i = 0; i < Items.Size; i++)' loop with: // ImGuiListClipper clipper(Items.Size); // while (clipper.Step()) // for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) // However, note that you can not use this code as is if a filter is active because it breaks the 'cheap random-access' property. We would need random-access on the post-filtered list. // A typical application wanting coarse clipping and filtering may want to pre-compute an array of indices that passed the filtering test, recomputing this array when user changes the filter, // and appending newly elements as they are inserted. This is left as a task to the user until we can manage to improve this example code! // If your items are of variable size you may want to implement code similar to what ImGuiListClipper does. Or split your data into fixed height items to allow random-seeking into your list. ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 1)); // Tighten spacing if (copy_to_clipboard) ImGui::LogToClipboard(); for (int i = 0; i < Items.Size; i++) { const char* item = Items[i]; if (!Filter.PassFilter(item)) continue; // Normally you would store more information in your item (e.g. make Items[] an array of structure, store color/type etc.) bool pop_color = false; if (strstr(item, "[error]")) { ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.4f, 0.4f, 1.0f)); pop_color = true; } else if (strncmp(item, "# ", 2) == 0) { ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.8f, 0.6f, 1.0f)); pop_color = true; } ImGui::TextUnformatted(item); if (pop_color) ImGui::PopStyleColor(); } if (copy_to_clipboard) ImGui::LogFinish(); if (ScrollToBottom || (AutoScroll && ImGui::GetScrollY() >= ImGui::GetScrollMaxY())) ImGui::SetScrollHereY(1.0f); ScrollToBottom = false; ImGui::PopStyleVar(); ImGui::EndChild(); ImGui::Separator(); // Command-line bool reclaim_focus = false; if (ImGui::InputText("Input", InputBuf, IM_ARRAYSIZE(InputBuf), ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory, &TextEditCallbackStub, (void*)this)) { char* s = InputBuf; Strtrim(s); if (s[0]) ExecCommand(s); strcpy(s, ""); reclaim_focus = true; } // Auto-focus on window apparition ImGui::SetItemDefaultFocus(); if (reclaim_focus) ImGui::SetKeyboardFocusHere(-1); // Auto focus previous widget ImGui::End(); } void ExecCommand(const char* command_line) { AddLog("# %s\n", command_line); // Insert into history. First find match and delete it so it can be pushed to the back. This isn't trying to be smart or optimal. HistoryPos = -1; for (int i = History.Size - 1; i >= 0; i--) if (Stricmp(History[i], command_line) == 0) { free(History[i]); History.erase(History.begin() + i); break; } History.push_back(Strdup(command_line)); // Process command if (Stricmp(command_line, "CLEAR") == 0) { ClearLog(); } else if (Stricmp(command_line, "HELP") == 0) { this->AddLog("Commands:"); for (int i = 0; i < Commands.Size; i++) this->AddLog("- %s", Commands[i]); } else if (Stricmp(command_line, "HISTORY") == 0) { int first = History.Size - 10; for (int i = first > 0 ? first : 0; i < History.Size; i++) this->AddLog("%3d: %s\n", i, History[i]); } else { this->AddLog("Unknown command: '%s'\n", command_line); } // On commad input, we scroll to bottom even if AutoScroll==false ScrollToBottom = true; } static int TextEditCallbackStub(ImGuiInputTextCallbackData* data) // In C++11 you are better off using lambdas for this sort of forwarding callbacks { ExampleAppConsole* console = (ExampleAppConsole*)data->UserData; return console->TextEditCallback(data); } int TextEditCallback(ImGuiInputTextCallbackData* data) { //AddLog("cursor: %d, selection: %d-%d", data->CursorPos, data->SelectionStart, data->SelectionEnd); switch (data->EventFlag) { case ImGuiInputTextFlags_CallbackCompletion: { // Example of TEXT COMPLETION // Locate beginning of current word const char* word_end = data->Buf + data->CursorPos; const char* word_start = word_end; while (word_start > data->Buf) { const char c = word_start[-1]; if (c == ' ' || c == '\t' || c == ',' || c == ';') break; word_start--; } // Build a list of candidates ImVector<const char*> candidates; for (int i = 0; i < Commands.Size; i++) if (Strnicmp(Commands[i], word_start, (int)(word_end - word_start)) == 0) candidates.push_back(Commands[i]); if (candidates.Size == 0) { // No match this->AddLog("No match for \"%.*s\"!\n", (int)(word_end - word_start), word_start); } else if (candidates.Size == 1) { // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start)); data->InsertChars(data->CursorPos, candidates[0]); data->InsertChars(data->CursorPos, " "); } else { // Multiple matches. Complete as much as we can, so inputing "C" will complete to "CL" and display "CLEAR" and "CLASSIFY" int match_len = (int)(word_end - word_start); for (;;) { int c = 0; bool all_candidates_matches = true; for (int i = 0; i < candidates.Size && all_candidates_matches; i++) if (i == 0) c = toupper(candidates[i][match_len]); else if (c == 0 || c != toupper(candidates[i][match_len])) all_candidates_matches = false; if (!all_candidates_matches) break; match_len++; } if (match_len > 0) { data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start)); data->InsertChars(data->CursorPos, candidates[0], candidates[0] + match_len); } // List matches this->AddLog("Possible matches:\n"); for (int i = 0; i < candidates.Size; i++) this->AddLog("- %s\n", candidates[i]); } break; } case ImGuiInputTextFlags_CallbackHistory: { // Example of HISTORY const int prev_history_pos = HistoryPos; if (data->EventKey == ImGuiKey_UpArrow) { if (HistoryPos == -1) HistoryPos = History.Size - 1; else if (HistoryPos > 0) HistoryPos--; } else if (data->EventKey == ImGuiKey_DownArrow) { if (HistoryPos != -1) if (++HistoryPos >= History.Size) HistoryPos = -1; } // A better implementation would preserve the data on the current input line along with cursor position. if (prev_history_pos != HistoryPos) { const char* history_str = (HistoryPos >= 0) ? History[HistoryPos] : ""; data->DeleteChars(0, data->BufTextLen); data->InsertChars(0, history_str); } } } return 0; } }; static ExampleAppConsole console; static void ShowExampleAppConsole(bool* p_open) { // static ExampleAppConsole console; console.Draw("Debug Log", p_open); } int verilate() { static int clkdiv=3; if (!Verilated::gotFinish()) { //while ( top->FL_ADDR < 0x0100 ) { // Only run for a short time. if (main_time < 48) { top->reset = 1; // Assert reset (active HIGH) } if (main_time == 48) { // Do == here, so we can still reset it in the main loop. top->reset = 0; // Deassert reset. } if ((main_time & 1) == 0) { // top->clk_sys = 0; // Toggle clock if (!clkdiv) { } top->clk_sys=0; top->clk_vid = 0; } if ((main_time & 1) == 1) { // top->clk_sys = 1; if (!clkdiv) { clkdiv=3; } clkdiv--; top->clk_sys=1; top->clk_vid = 1; pix_count++; // Write VGA output to a file. RAW RGB! rgb[0] = top->VGA_B ; // GBA core outputs 4 bits per VGA colour channel (12 bpp). rgb[1] = top->VGA_G ; rgb[2] = top->VGA_R ; //fwrite(rgb, 1, 3, vgap); // Write 24-bit values to the file. uint32_t vga_addr = (line_count * 1024) + pix_count; if (vga_addr <= vga_size) vga_ptr[vga_addr] = (rgb[0] << 16) | (rgb[1] << 8) | (rgb[2] << 0); disp_ptr[vga_addr] = 0xFF000000 | rgb[0] << 16 | rgb[1] << 8 | rgb[2] ; // Our debugger framebuffer is in the 32-bit RGBA format. if (prev_hsync && !top->VGA_HS) { //printf("Line Count: %d\n", line_count); //printf("Pix count: %d\n", pix_count); line_count++; pix_count = 0; } prev_hsync = top->VGA_HS; if (prev_vsync && !top->VGA_VS) { frame_count++; line_count = 0; sprintf(my_string, "Frame: %06d VSync! ", frame_count); console.AddLog(my_string); } prev_vsync = top->VGA_VS; } if (top->clk_sys ) ioctl_download_before_eval(); else if (ioctl_file) console.AddLog("skipping download this cycle %d\n",top->clk_sys); top->eval(); // Evaluate model! if (top->clk_sys ) ioctl_download_after_eval(); main_time++; // Time passes... return 1; } // Stop Verilating... top->final(); delete top; exit(0); return 0; } void ioctl_download_setfile(char *file, int index) { ioctl_next_addr = -1; top->ioctl_addr=ioctl_next_addr; top->ioctl_index = index; ioctl_file=fopen(file,"rb"); if (!ioctl_file) console.AddLog("error opening %s\n",file); } int nextchar = 0; void ioctl_download_before_eval() { if (ioctl_file) { console.AddLog("ioctl_download_before_eval %x\n",top->ioctl_addr); if (top->ioctl_wait==0) { top->ioctl_download=1; top->ioctl_wr = 1; if (feof(ioctl_file)) { fclose(ioctl_file); ioctl_file=NULL; top->ioctl_download=0; top->ioctl_wr = 0; console.AddLog("finished upload\n"); } if (ioctl_file) { int curchar = fgetc(ioctl_file); if (feof(ioctl_file) == 0) { // if (curchar!=EOF) { //top->ioctl_dout=(char)curchar; nextchar=curchar; console.AddLog("ioctl_download_before_eval: dout %x \n",top->ioctl_dout); ioctl_next_addr++; } } } } else { top->ioctl_download=0; top->ioctl_wr=0; } } void ioctl_download_after_eval() { top->ioctl_addr=ioctl_next_addr; top->ioctl_dout=(unsigned char)nextchar; if (ioctl_file) console.AddLog("ioctl_download_after_eval %x wr %x dl %x\n",top->ioctl_addr,top->ioctl_wr,top->ioctl_download); } void start_load_image() { console.AddLog("load image here\n"); #ifdef WIN32 ioctl_download_setfile("..\\Image Examples\\bird.bin",0); #else ioctl_download_setfile("../Image Examples/bird.bin",0); #endif } int my_count = 0; MemoryEditor mem_edit_1; int main(int argc, char** argv, char** env) { bios_ptr = (uint32_t *)malloc(bios_size); cart_ptr = (uint32_t *)malloc(cart_size); ram_ptr = (uint32_t *)malloc(ram_size); vram_ptr = (uint32_t *)malloc(vram_size); disp_ptr = (uint32_t *)malloc(disp_size); vga_ptr = (uint32_t *)malloc(vga_size); #ifdef WIN32 // Create application window WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL }; RegisterClassEx(&wc); HWND hwnd = CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX11 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL); top = new Vtop(); // Initialize Direct3D if (CreateDeviceD3D(hwnd) < 0) { CleanupDeviceD3D(); UnregisterClass(wc.lpszClassName, wc.hInstance); return 1; } // Show the window ShowWindow(hwnd, SW_SHOWDEFAULT); UpdateWindow(hwnd); #else // Setup SDL if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) { printf("Error: %s\n", SDL_GetError()); return -1; } top = new Vtop(); // Setup window SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); SDL_GLContext gl_context = SDL_GL_CreateContext(window); SDL_GL_MakeCurrent(window, gl_context); SDL_GL_SetSwapInterval(1); // Enable vsync #endif // Setup Dear ImGui context IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls // Setup Dear ImGui style ImGui::StyleColorsDark(); //ImGui::StyleColorsClassic(); #ifdef WIN32 // Setup Platform/Renderer bindings ImGui_ImplWin32_Init(hwnd); ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext); #else // Setup Platform/Renderer bindings ImGui_ImplSDL2_InitForOpenGL(window, gl_context); ImGui_ImplOpenGL2_Init(); #endif // Load Fonts // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple. // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit). // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call. // - Read 'misc/fonts/README.txt' for more instructions and details. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ ! //io.Fonts->AddFontDefault(); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f); //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f); //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese()); //IM_ASSERT(font != NULL); Verilated::commandArgs(argc, argv); memset(vram_ptr, 0x00, vram_size); memset(disp_ptr, 0xAA, disp_size); memset(vga_ptr, 0xAA, vga_size); memset(ram_ptr, 0x00, ram_size); // Our state bool show_demo_window = true; bool show_another_window = false; ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f); // Build texture atlas int width = 1024; int height = 512; #ifdef WIN32 // Upload texture to graphics system D3D11_TEXTURE2D_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.Width = width; desc.Height = height; desc.MipLevels = 1; desc.ArraySize = 1; desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; //desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; //desc.Format = DXGI_FORMAT_B5G5R5A1_UNORM; desc.SampleDesc.Count = 1; desc.Usage = D3D11_USAGE_DEFAULT; desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; ID3D11Texture2D *pTexture = NULL; D3D11_SUBRESOURCE_DATA subResource; subResource.pSysMem = disp_ptr; //subResource.pSysMem = vga_ptr; subResource.SysMemPitch = desc.Width * 4; subResource.SysMemSlicePitch = 0; g_pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture); // Create texture view D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; ZeroMemory(&srvDesc, sizeof(srvDesc)); srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; srvDesc.Texture2D.MipLevels = desc.MipLevels; srvDesc.Texture2D.MostDetailedMip = 0; g_pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, &g_pFontTextureView); pTexture->Release(); // Store our identifier ImTextureID my_tex_id = (ImTextureID)g_pFontTextureView; // Create texture sampler { D3D11_SAMPLER_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; desc.MipLODBias = 0.f; desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; desc.MinLOD = 0.f; desc.MaxLOD = 0.f; g_pd3dDevice->CreateSamplerState(&desc, &g_pFontSampler); } #else // the texture should match the GPU so it doesn't have to copy GLuint tex; glGenTextures(1, &tex); glBindTexture(GL_TEXTURE_2D, tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, VGA_WIDTH, VGA_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE,disp_ptr); ImTextureID my_tex_id = (ImTextureID) tex; // ImTextureID my_tex_id = (ImTextureID) renderedTexture; #endif bool follow_writes = 0; int write_address = 0; static bool show_app_console = true; #ifdef WIN32 // imgui Main loop stuff... MSG msg; ZeroMemory(&msg, sizeof(msg)); while (msg.message != WM_QUIT) { // Poll and handle messages (inputs, window resize, etc.) // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); continue; } // Start the Dear ImGui frame ImGui_ImplDX11_NewFrame(); ImGui_ImplWin32_NewFrame(); #else // Main loop bool done = false; while (!done) { // Poll and handle events (inputs, window resize, etc.) // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. SDL_Event event; while (SDL_PollEvent(&event)) { ImGui_ImplSDL2_ProcessEvent(&event); if (event.type == SDL_QUIT) done = true; } // Start the Dear ImGui frame ImGui_ImplOpenGL2_NewFrame(); ImGui_ImplSDL2_NewFrame(window); #endif ImGui::NewFrame(); // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!). //if (show_demo_window) // ImGui::ShowDemoWindow(&show_demo_window); // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window. static float f = 0.1f; static int counter = 0; ImGui::Begin("Virtual Dev Board v1.0"); // Create a window called "Virtual Dev Board v1.0" and append into it. ShowExampleAppConsole(&show_app_console); if (ImGui::Button("RESET")) main_time = 0; if (ImGui::Button("LOAD IMAGE")) start_load_image(); ImGui::Text("main_time %d", main_time); ImGui::Text("frame_count: %d line_count: %d", frame_count, line_count); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); ImGui::Checkbox("RUN", &run_enable); if (single_step == 1) single_step = 0; if (ImGui::Button("Single Step")) { run_enable = 0; single_step = 1; } if (multi_step == 1) multi_step = 0; if (ImGui::Button("Multi Step")) { run_enable = 0; multi_step = 1; } ImGui::SameLine(); ImGui::SliderInt("Step amount", &multi_step_amount, 8, 1024); ImGui::Image(my_tex_id, ImVec2(width, height)); ImGui::End(); ImGui::Begin("RAM Editor"); mem_edit_1.DrawContents(top->top__DOT__soc__DOT__vga__DOT__vmem__DOT__mem, 16384, 0); ImGui::End(); #ifdef WIN32 // Update the texture! // D3D11_USAGE_DEFAULT MUST be set in the texture description (somewhere above) for this to work. // (D3D11_USAGE_DYNAMIC is for use with map / unmap.) ElectronAsh. g_pd3dDeviceContext->UpdateSubresource(pTexture, 0, NULL, disp_ptr, width * 4, 0); // Rendering ImGui::Render(); g_pd3dDeviceContext->OMSetRenderTargets(1, &g_mainRenderTargetView, NULL); g_pd3dDeviceContext->ClearRenderTargetView(g_mainRenderTargetView, (float*)&clear_color); ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); //g_pSwapChain->Present(1, 0); // Present with vsync g_pSwapChain->Present(0, 0); // Present without vsync #else glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, VGA_WIDTH, VGA_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE,disp_ptr); // Rendering ImGui::Render(); glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y); glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); glClear(GL_COLOR_BUFFER_BIT); //glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context where shaders may be bound ImGui_ImplOpenGL2_RenderDrawData(ImGui::GetDrawData()); SDL_GL_SwapWindow(window); #endif if (run_enable) for (int step = 0; step < 1024*10; step++) verilate(); // Simulates MUCH faster if it's done in batches. else { // But, that will affect the values we can grab for the GUI. if (single_step) verilate(); if (multi_step) for (int step = 0; step < multi_step_amount; step++) verilate(); } } #ifdef WIN32 // Close imgui stuff properly... ImGui_ImplDX11_Shutdown(); ImGui_ImplWin32_Shutdown(); ImGui::DestroyContext(); CleanupDeviceD3D(); DestroyWindow(hwnd); UnregisterClass(wc.lpszClassName, wc.hInstance); #else // Cleanup ImGui_ImplOpenGL2_Shutdown(); ImGui_ImplSDL2_Shutdown(); ImGui::DestroyContext(); SDL_GL_DeleteContext(gl_context); SDL_DestroyWindow(window); SDL_Quit(); #endif return 0; } <|start_filename|>basic/lesson3/verilator/sim/sim_bus.h<|end_filename|> #pragma once #include <queue> #include "verilated_heavy.h" #include "sim_console.h" #ifndef _MSC_VER #else #define WIN32 #endif struct SimBus_DownloadChunk { public: std::string file; int index; SimBus_DownloadChunk() { file = ""; index = -1; } SimBus_DownloadChunk(std::string file, int index) { this->file = std::string(file); this->index = index; } }; struct SimBus { public: IData* ioctl_addr; CData* ioctl_index; CData* ioctl_wait; CData* ioctl_download; CData* ioctl_upload; CData* ioctl_wr; CData* ioctl_dout; CData* ioctl_din; void BeforeEval(void); void AfterEval(void); void QueueDownload(std::string file, int index); SimBus(DebugConsole c); ~SimBus(); private: std::queue<SimBus_DownloadChunk> downloadQueue; SimBus_DownloadChunk currentDownload; void SetDownload(std::string file, int index); }; <|start_filename|>basic/lesson4/Makefile<|end_filename|> SDCC=sdcc CPU=z80 CODE=boot_rom all: $(CODE).hex %.ihx: %.c $(SDCC) -m$(CPU) $< %.hex: %.ihx mv $< $@ %.bin: %.hex srec_cat $< -intel -o $@ -binary disasm: $(CODE).bin z80dasm -a -t -g 0 $< clean: rm -rf *~ *.asm *.ihx *.lk *.lst *.map *.noi *.rel *.sym <|start_filename|>basic/lesson3_68k/rom/rom.c<|end_filename|> extern int _stext; extern int _estack; extern int _vram; typedef struct { /* Stack pointer */ void* pStack; void* pReset; void* fill[62]; } DeviceVectors; int main(); __attribute__ ((section(".vectors"))) const DeviceVectors exception_table = { .pStack = (void*) (&_estack), .pReset = (void*) (&main) }; short *vram ; void put_pixel(unsigned int x, unsigned int y, unsigned short color) { vram[320*y+x] = color; } // bresenham algorithm to draw a line void draw_line(int x, int y, int x2, int y2, unsigned short color) { int longest, shortest, numerator, i; int dx1 = (x < x2) ? 1 : -1; int dy1 = (y < y2) ? 1 : -1; int dx2, dy2; longest = ( x2 > x ) ? x2 - x : x - x2; shortest = ( y2 > y ) ? y2 - y : y - y2; if (longest < shortest) { longest = ( y2 > y ) ? y2 - y : y - y2; shortest = ( x2 > x ) ? x2 - x : x - x2; dx2 = 0; dy2 = dy1; } else { dx2 = dx1; dy2 = 0; } numerator = longest/2; for (i=0; i<=longest; i++) { put_pixel(x,y,color) ; if (numerator >= longest-shortest) { numerator += shortest ; numerator -= longest ; x += dx1; y += dy1; } else { numerator += shortest ; x += dx2; y += dy2; } } } int main() { int i; int w = 320; int h = 240; unsigned short color = 0; vram = (short*)&_vram; // clear screen for(i=0;i<76800;i++) vram[i] = 0; // draw colorful lines forever ... while(1) { for (i=0;i<h;i++) draw_line(0,0,w-1,i,color++); for(i=w-1;i>=0;i--) draw_line(0,0,i,h-1,color++); for(i=0;i<w;i++) draw_line(0,h-1,i,0,color++); for(i=0;i<h;i++) draw_line(0,h-1,w-1,i,color++); for(i=h-1;i>=0;i--) draw_line(w-1,h-1,0,i,color++); for(i=0;i<w;i++) draw_line(w-1,h-1,i,0,color++); for(i=w-1;i>=0;i--) draw_line(w-1,0,i,h-1,color++); for(i=h-1;i>=0;i--) draw_line(w-1,0,0,i,color++); } } <|start_filename|>basic/lesson3/verilator/sim/sim_bus.cpp<|end_filename|> #include <iostream> #include <queue> #include <string> #include "sim_bus.h" #include "sim_console.h" #include "verilated_heavy.h" #ifndef _MSC_VER #else #define WIN32 #endif static DebugConsole console; FILE* ioctl_file = NULL; int ioctl_next_addr = -1; int ioctl_last_index = -1; IData* ioctl_addr = NULL; CData* ioctl_index = NULL; CData* ioctl_wait = NULL; CData* ioctl_download = NULL; CData* ioctl_upload = NULL; CData* ioctl_wr = NULL; CData* ioctl_dout = NULL; CData* ioctl_din = NULL; std::queue<SimBus_DownloadChunk> downloadQueue; void SimBus::QueueDownload(std::string file, int index) { SimBus_DownloadChunk chunk = SimBus_DownloadChunk(file, index); downloadQueue.push(chunk); } int nextchar = 0; void SimBus::BeforeEval() { // If no file is open and there is a download queued if (!ioctl_file && downloadQueue.size() > 0) { // Get chunk from queue currentDownload = downloadQueue.front(); downloadQueue.pop(); // If last index differs from this one then reset the addresses if (currentDownload.index != *ioctl_index) { ioctl_next_addr = -1; } // Set address and index *ioctl_addr = ioctl_next_addr; *ioctl_index = currentDownload.index; // Open file ioctl_file = fopen(currentDownload.file.c_str(), "rb"); if (!ioctl_file) { console.AddLog("Cannot open file for download %s\n", currentDownload.file.c_str()); } else { console.AddLog("Starting download: %s %d", currentDownload.file.c_str(), ioctl_next_addr, ioctl_next_addr); } } if (ioctl_file) { //console.AddLog("ioctl_download addr %x ioctl_wait %x", *ioctl_addr, *ioctl_wait); if (*ioctl_wait == 0) { *ioctl_download = 1; *ioctl_wr = 1; if (feof(ioctl_file)) { fclose(ioctl_file); ioctl_file = NULL; *ioctl_download = 0; *ioctl_wr = 0; console.AddLog("ioctl_download complete %d", ioctl_next_addr); } if (ioctl_file) { int curchar = fgetc(ioctl_file); if (feof(ioctl_file) == 0) { nextchar = curchar; //console.AddLog("ioctl_download: dout %x \n", *ioctl_dout); ioctl_next_addr++; } } } } else { ioctl_download = 0; ioctl_wr = 0; } } void SimBus::AfterEval() { *ioctl_addr = ioctl_next_addr; *ioctl_dout = (unsigned char)nextchar; if (ioctl_file) { // console.AddLog("ioctl_download %x wr %x dl %x\n", *ioctl_addr, *ioctl_wr, *ioctl_download); } } SimBus::SimBus(DebugConsole c) { console = c; ioctl_addr = NULL; ioctl_index = NULL; ioctl_wait = NULL; ioctl_download = NULL; ioctl_upload = NULL; ioctl_wr = NULL; ioctl_dout = NULL; ioctl_din = NULL; } SimBus::~SimBus() { } <|start_filename|>basic/lesson3/verilator/sim/vinc/verilated_vpi.cpp<|end_filename|> // -*- mode: C++; c-file-style: "cc-mode" -*- //************************************************************************* // // Copyright 2009-2020 by <NAME>. This program is free software; you can // redistribute it and/or modify it under the terms of either the GNU // Lesser General Public License Version 3 or the Perl Artistic License. // Version 2.0. // // Verilator is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // //========================================================================= /// /// \file /// \brief Verilator: VPI implementation code /// /// This file must be compiled and linked against all objects /// created from Verilator or called by Verilator that use the VPI. /// /// Use "verilator --vpi" to add this to the Makefile for the linker. /// /// Code available from: https://verilator.org /// //========================================================================= #define _VERILATED_VPI_CPP_ #if VM_SC # include "verilated_sc.h" #endif #include "verilated.h" #include "verilated_vpi.h" #include "verilated_imp.h" #include <list> #include <map> #include <set> #include <sstream> //====================================================================== // Internal constants #define VL_DEBUG_IF_PLI VL_DEBUG_IF #define VL_VPI_LINE_SIZE 8192 //====================================================================== // Internal macros #define _VL_VPI_INTERNAL VerilatedVpiImp::error_info()->setMessage(vpiInternal)->setMessage #define _VL_VPI_SYSTEM VerilatedVpiImp::error_info()->setMessage(vpiSystem )->setMessage #define _VL_VPI_ERROR VerilatedVpiImp::error_info()->setMessage(vpiError )->setMessage #define _VL_VPI_WARNING VerilatedVpiImp::error_info()->setMessage(vpiWarning )->setMessage #define _VL_VPI_NOTICE VerilatedVpiImp::error_info()->setMessage(vpiNotice )->setMessage #define _VL_VPI_ERROR_RESET VerilatedVpiImp::error_info()->resetError // Not supported yet #define _VL_VPI_UNIMP() \ _VL_VPI_ERROR(__FILE__, __LINE__, Verilated::catName("Unsupported VPI function: ", VL_FUNC)); //====================================================================== // Implementation // Base VPI handled object class VerilatedVpio { // MEM MANGLEMENT static VL_THREAD_LOCAL vluint8_t* t_freeHead; public: // CONSTRUCTORS VerilatedVpio() {} virtual ~VerilatedVpio() {} inline static void* operator new(size_t size) VL_MT_SAFE { // We new and delete tons of vpi structures, so keep them around // To simplify our free list, we use a size large enough for all derived types // We reserve word zero for the next pointer, as that's safer in case a // dangling reference to the original remains around. static const size_t chunk = 96; if (VL_UNCOVERABLE(size>chunk)) VL_FATAL_MT(__FILE__, __LINE__, "", "increase chunk"); if (VL_LIKELY(t_freeHead)) { vluint8_t* newp = t_freeHead; t_freeHead = *((vluint8_t**)newp); return newp+8; } // +8: 8 bytes for next vluint8_t* newp = reinterpret_cast<vluint8_t*>(::operator new(chunk+8)); return newp+8; } inline static void operator delete(void* obj, size_t size) VL_MT_SAFE { vluint8_t* oldp = ((vluint8_t*)obj)-8; *((void**)oldp) = t_freeHead; t_freeHead = oldp; } // MEMBERS static inline VerilatedVpio* castp(vpiHandle h) { return dynamic_cast<VerilatedVpio*>((VerilatedVpio*)h); } inline vpiHandle castVpiHandle() { return reinterpret_cast<vpiHandle>(this); } // ACCESSORS virtual const char* name() const { return "<null>"; } virtual const char* fullname() const { return "<null>"; } virtual const char* defname() const { return "<null>"; } virtual vluint32_t type() const { return 0; } virtual vluint32_t size() const { return 0; } virtual const VerilatedRange* rangep() const { return NULL; } virtual vpiHandle dovpi_scan() { return 0; } }; typedef PLI_INT32 (*VerilatedPliCb)(struct t_cb_data *); class VerilatedVpioCb : public VerilatedVpio { t_cb_data m_cbData; s_vpi_value m_value; QData m_time; public: // cppcheck-suppress uninitVar // m_value VerilatedVpioCb(const t_cb_data* cbDatap, QData time) : m_cbData(*cbDatap), m_time(time) { m_value.format = cbDatap->value ? cbDatap->value->format : vpiSuppressVal; m_cbData.value = &m_value; } virtual ~VerilatedVpioCb() {} static inline VerilatedVpioCb* castp(vpiHandle h) { return dynamic_cast<VerilatedVpioCb*>((VerilatedVpio*)h); } virtual vluint32_t type() const { return vpiCallback; } vluint32_t reason() const { return m_cbData.reason; } VerilatedPliCb cb_rtnp() const { return m_cbData.cb_rtn; } t_cb_data* cb_datap() { return &(m_cbData); } QData time() const { return m_time; } }; class VerilatedVpioConst : public VerilatedVpio { vlsint32_t m_num; public: explicit VerilatedVpioConst(vlsint32_t num) : m_num(num) {} virtual ~VerilatedVpioConst() {} static inline VerilatedVpioConst* castp(vpiHandle h) { return dynamic_cast<VerilatedVpioConst*>((VerilatedVpio*)h); } virtual vluint32_t type() const { return vpiUndefined; } vlsint32_t num() const { return m_num; } }; class VerilatedVpioRange : public VerilatedVpio { const VerilatedRange* m_range; vlsint32_t m_iteration; public: explicit VerilatedVpioRange(const VerilatedRange* range) : m_range(range), m_iteration(0) {} virtual ~VerilatedVpioRange() {} static inline VerilatedVpioRange* castp(vpiHandle h) { return dynamic_cast<VerilatedVpioRange*>((VerilatedVpio*)h); } virtual vluint32_t type() const { return vpiRange; } virtual vluint32_t size() const { return m_range->elements(); } virtual const VerilatedRange* rangep() const { return m_range; } int iteration() const { return m_iteration; } void iterationInc() { ++m_iteration; } virtual vpiHandle dovpi_scan() { if (!iteration()) { VerilatedVpioRange* nextp = new VerilatedVpioRange(*this); nextp->iterationInc(); return ((nextp)->castVpiHandle()); } return 0; // End of list - only one deep } }; class VerilatedVpioScope : public VerilatedVpio { protected: const VerilatedScope* m_scopep; public: explicit VerilatedVpioScope(const VerilatedScope* scopep) : m_scopep(scopep) {} virtual ~VerilatedVpioScope() {} static inline VerilatedVpioScope* castp(vpiHandle h) { return dynamic_cast<VerilatedVpioScope*>((VerilatedVpio*)h); } virtual vluint32_t type() const { return vpiScope; } const VerilatedScope* scopep() const { return m_scopep; } virtual const char* name() const { return m_scopep->name(); } virtual const char* fullname() const { return m_scopep->name(); } }; class VerilatedVpioVar : public VerilatedVpio { const VerilatedVar* m_varp; const VerilatedScope* m_scopep; vluint8_t* m_prevDatap; // Previous value of data, for cbValueChange union { vluint8_t u8[4]; vluint32_t u32; } m_mask; // memoized variable mask vluint32_t m_entSize; // memoized variable size protected: void* m_varDatap; // varp()->datap() adjusted for array entries vlsint32_t m_index; const VerilatedRange& get_range() const { // Determine number of dimensions and return outermost return (m_varp->dims()>1) ? m_varp->unpacked() : m_varp->packed(); } public: VerilatedVpioVar(const VerilatedVar* varp, const VerilatedScope* scopep) : m_varp(varp), m_scopep(scopep), m_index(0) { m_prevDatap = NULL; m_mask.u32 = VL_MASK_I(varp->packed().elements()); m_entSize = varp->entSize(); m_varDatap = varp->datap(); } virtual ~VerilatedVpioVar() { if (m_prevDatap) { delete [] m_prevDatap; m_prevDatap = NULL; } } static inline VerilatedVpioVar* castp(vpiHandle h) { return dynamic_cast<VerilatedVpioVar*>((VerilatedVpio*)h); } const VerilatedVar* varp() const { return m_varp; } const VerilatedScope* scopep() const { return m_scopep; } vluint32_t mask() const { return m_mask.u32; } vluint8_t mask_byte(int idx) { return m_mask.u8[idx & 3]; } vluint32_t entSize() const { return m_entSize; } vluint32_t index() { return m_index; } virtual vluint32_t type() const { return (varp()->dims()>1) ? vpiMemory : vpiReg; // but might be wire, logic } virtual vluint32_t size() const { return get_range().elements(); } virtual const VerilatedRange* rangep() const { return &get_range(); } virtual const char* name() const { return m_varp->name(); } virtual const char* fullname() const { static VL_THREAD_LOCAL std::string out; out = std::string(m_scopep->name())+"."+name(); return out.c_str(); } void* prevDatap() const { return m_prevDatap; } void* varDatap() const { return m_varDatap; } void createPrevDatap() { if (VL_UNLIKELY(!m_prevDatap)) { m_prevDatap = new vluint8_t [entSize()]; memcpy(prevDatap(), varp()->datap(), entSize()); } } }; class VerilatedVpioMemoryWord : public VerilatedVpioVar { public: VerilatedVpioMemoryWord(const VerilatedVar* varp, const VerilatedScope* scopep, vlsint32_t index, int offset) : VerilatedVpioVar(varp, scopep) { m_index = index; m_varDatap = ((vluint8_t*)varp->datap()) + entSize()*offset; } virtual ~VerilatedVpioMemoryWord() {} static inline VerilatedVpioMemoryWord* castp(vpiHandle h) { return dynamic_cast<VerilatedVpioMemoryWord*>((VerilatedVpio*)h); } virtual vluint32_t type() const { return vpiMemoryWord; } virtual vluint32_t size() const { return varp()->packed().elements(); } virtual const VerilatedRange* rangep() const { return &(varp()->packed()); } virtual const char* fullname() const { static VL_THREAD_LOCAL std::string out; char num[20]; sprintf(num, "%d", m_index); out = std::string(scopep()->name())+"."+name()+"["+num+"]"; return out.c_str(); } }; class VerilatedVpioVarIter : public VerilatedVpio { const VerilatedScope* m_scopep; VerilatedVarNameMap::const_iterator m_it; bool m_started; public: explicit VerilatedVpioVarIter(const VerilatedScope* scopep) : m_scopep(scopep), m_started(false) { } virtual ~VerilatedVpioVarIter() {} static inline VerilatedVpioVarIter* castp(vpiHandle h) { return dynamic_cast<VerilatedVpioVarIter*>((VerilatedVpio*)h); } virtual vluint32_t type() const { return vpiIterator; } virtual vpiHandle dovpi_scan() { if (VL_LIKELY(m_scopep->varsp())) { VerilatedVarNameMap* varsp = m_scopep->varsp(); if (VL_UNLIKELY(!m_started)) { m_it = varsp->begin(); m_started=true; } else if (VL_UNLIKELY(m_it == varsp->end())) return 0; else ++m_it; if (m_it == varsp->end()) return 0; return ((new VerilatedVpioVar(&(m_it->second), m_scopep)) ->castVpiHandle()); } return 0; // End of list - only one deep } }; class VerilatedVpioMemoryWordIter : public VerilatedVpio { const vpiHandle m_handle; const VerilatedVar* m_varp; vlsint32_t m_iteration; vlsint32_t m_direction; bool m_done; public: VerilatedVpioMemoryWordIter(const vpiHandle handle, const VerilatedVar* varp) : m_handle(handle), m_varp(varp), m_iteration(varp->unpacked().right()), m_direction(VL_LIKELY(varp->unpacked().left() > varp->unpacked().right()) ? 1 : -1), m_done(false) { } virtual ~VerilatedVpioMemoryWordIter() {} static inline VerilatedVpioMemoryWordIter* castp(vpiHandle h) { return dynamic_cast<VerilatedVpioMemoryWordIter*>((VerilatedVpio*)h); } virtual vluint32_t type() const { return vpiIterator; } void iterationInc() { if (!(m_done = (m_iteration == m_varp->unpacked().left()))) { m_iteration += m_direction; } } virtual vpiHandle dovpi_scan() { vpiHandle result; if (m_done) return 0; result = vpi_handle_by_index(m_handle, m_iteration); iterationInc(); return result; } }; class VerilatedVpioModule : public VerilatedVpioScope { const char* m_name; const char* m_fullname; public: explicit VerilatedVpioModule(const VerilatedScope* modulep) : VerilatedVpioScope(modulep) { m_fullname = m_scopep->name(); if (strncmp(m_fullname, "TOP.", 4) == 0) m_fullname += 4; m_name = m_scopep->identifier(); } static inline VerilatedVpioModule* castp(vpiHandle h) { return dynamic_cast<VerilatedVpioModule*>((VerilatedVpio*)h); } virtual vluint32_t type() const { return vpiModule; } virtual const char* name() const { return m_name; } virtual const char* fullname() const { return m_fullname; } }; class VerilatedVpioModuleIter : public VerilatedVpio { const std::vector<const VerilatedScope*> *m_vec; std::vector<const VerilatedScope*>::const_iterator m_it; public: explicit VerilatedVpioModuleIter(const std::vector<const VerilatedScope*>& vec) : m_vec(&vec) { m_it = m_vec->begin(); } virtual ~VerilatedVpioModuleIter() {} static inline VerilatedVpioModuleIter* castp(vpiHandle h) { return dynamic_cast<VerilatedVpioModuleIter*>((VerilatedVpio*) h); } virtual vluint32_t type() const { return vpiIterator; } virtual vpiHandle dovpi_scan() { if (m_it == m_vec->end()) { return 0; } const VerilatedScope* modp = *m_it++; return (new VerilatedVpioModule(modp))->castVpiHandle(); } }; //====================================================================== struct VerilatedVpiTimedCbsCmp { /// Ordering sets keyed by time, then callback descriptor bool operator()(const std::pair<QData,VerilatedVpioCb*>& a, const std::pair<QData,VerilatedVpioCb*>& b) const { if (a.first < b.first) return 1; if (a.first > b.first) return 0; return a.second < b.second; } }; class VerilatedVpiError; class VerilatedVpiImp { enum { CB_ENUM_MAX_VALUE = cbAtEndOfSimTime+1 }; // Maxium callback reason typedef std::list<VerilatedVpioCb*> VpioCbList; typedef std::set<std::pair<QData,VerilatedVpioCb*>,VerilatedVpiTimedCbsCmp > VpioTimedCbs; struct product_info { PLI_BYTE8* product; }; VpioCbList m_cbObjLists[CB_ENUM_MAX_VALUE]; // Callbacks for each supported reason VpioTimedCbs m_timedCbs; // Time based callbacks VerilatedVpiError* m_errorInfop; // Container for vpi error info VerilatedAssertOneThread m_assertOne; ///< Assert only called from single thread static VerilatedVpiImp s_s; // Singleton public: VerilatedVpiImp() { m_errorInfop=NULL; } ~VerilatedVpiImp() {} static void assertOneCheck() { s_s.m_assertOne.check(); } static void cbReasonAdd(VerilatedVpioCb* vop) { if (vop->reason() == cbValueChange) { if (VerilatedVpioVar* varop = VerilatedVpioVar::castp(vop->cb_datap()->obj)) { varop->createPrevDatap(); } } if (VL_UNCOVERABLE(vop->reason() >= CB_ENUM_MAX_VALUE)) { VL_FATAL_MT(__FILE__, __LINE__, "", "vpi bb reason too large"); } s_s.m_cbObjLists[vop->reason()].push_back(vop); } static void cbTimedAdd(VerilatedVpioCb* vop) { s_s.m_timedCbs.insert(std::make_pair(vop->time(), vop)); } static void cbReasonRemove(VerilatedVpioCb* cbp) { VpioCbList& cbObjList = s_s.m_cbObjLists[cbp->reason()]; // We do not remove it now as we may be iterating the list, // instead set to NULL and will cleanup later for (VpioCbList::iterator it=cbObjList.begin(); it!=cbObjList.end(); ++it) { if (*it == cbp) *it = NULL; } } static void cbTimedRemove(VerilatedVpioCb* cbp) { VpioTimedCbs::iterator it=s_s.m_timedCbs.find(std::make_pair(cbp->time(), cbp)); if (VL_LIKELY(it != s_s.m_timedCbs.end())) { s_s.m_timedCbs.erase(it); } } static void callTimedCbs() VL_MT_UNSAFE_ONE { assertOneCheck(); QData time = VL_TIME_Q(); for (VpioTimedCbs::iterator it=s_s.m_timedCbs.begin(); it!=s_s.m_timedCbs.end(); ) { if (VL_UNLIKELY(it->first <= time)) { VerilatedVpioCb* vop = it->second; VpioTimedCbs::iterator last_it = it; ++it; // Timed callbacks are one-shot s_s.m_timedCbs.erase(last_it); VL_DEBUG_IF_PLI(VL_DBG_MSGF("- vpi: timed_callback %p\n", vop);); (vop->cb_rtnp()) (vop->cb_datap()); } else { ++it; } } } static QData cbNextDeadline() { VpioTimedCbs::const_iterator it=s_s.m_timedCbs.begin(); if (VL_LIKELY(it != s_s.m_timedCbs.end())) { return it->first; } return ~VL_ULL(0); // maxquad } static bool callCbs(vluint32_t reason) VL_MT_UNSAFE_ONE { VpioCbList& cbObjList = s_s.m_cbObjLists[reason]; bool called = false; for (VpioCbList::iterator it=cbObjList.begin(); it!=cbObjList.end();) { if (VL_UNLIKELY(!*it)) { // Deleted earlier, cleanup it = cbObjList.erase(it); continue; } VerilatedVpioCb* vop = *it++; VL_DEBUG_IF_PLI(VL_DBG_MSGF("- vpi: reason_callback %d %p\n", reason, vop);); (vop->cb_rtnp()) (vop->cb_datap()); called = true; } return called; } static void callValueCbs() VL_MT_UNSAFE_ONE { assertOneCheck(); VpioCbList& cbObjList = s_s.m_cbObjLists[cbValueChange]; typedef std::set<VerilatedVpioVar*> VpioVarSet; VpioVarSet update; // set of objects to update after callbacks for (VpioCbList::iterator it=cbObjList.begin(); it!=cbObjList.end();) { if (VL_UNLIKELY(!*it)) { // Deleted earlier, cleanup it = cbObjList.erase(it); continue; } VerilatedVpioCb* vop = *it++; if (VerilatedVpioVar* varop = VerilatedVpioVar::castp(vop->cb_datap()->obj)) { void* newDatap = varop->varDatap(); void* prevDatap = varop->prevDatap(); // Was malloced when we added the callback VL_DEBUG_IF_PLI(VL_DBG_MSGF("- vpi: value_test %s v[0]=%d/%d %p %p\n", varop->fullname(), *((CData*)newDatap), *((CData*)prevDatap), newDatap, prevDatap);); if (memcmp(prevDatap, newDatap, varop->entSize())) { VL_DEBUG_IF_PLI(VL_DBG_MSGF("- vpi: value_callback %p %s v[0]=%d\n", vop, varop->fullname(), *((CData*)newDatap));); update.insert(varop); vpi_get_value(vop->cb_datap()->obj, vop->cb_datap()->value); (vop->cb_rtnp()) (vop->cb_datap()); } } } for (VpioVarSet::const_iterator it=update.begin(); it!=update.end(); ++it) { memcpy((*it)->prevDatap(), (*it)->varDatap(), (*it)->entSize()); } } static VerilatedVpiError* error_info() VL_MT_UNSAFE_ONE; // getter for vpi error info }; class VerilatedVpiError { //// Container for vpi error info t_vpi_error_info m_errorInfo; bool m_flag; char m_buff[VL_VPI_LINE_SIZE]; void setError(PLI_BYTE8 *message, PLI_BYTE8 *code, PLI_BYTE8 *file, PLI_INT32 line) { m_errorInfo.message = message; m_errorInfo.file = file; m_errorInfo.line = line; m_errorInfo.code = code; do_callbacks(); } void do_callbacks() { if (getError()->level >= vpiError && Verilated::fatalOnVpiError()) { // Stop on vpi error/unsupported vpi_unsupported(); } // We need to run above code first because in the case that the // callback executes further vpi functions we will loose the error // as it will be overwritten. VerilatedVpiImp::callCbs(cbPLIError); } public: VerilatedVpiError() : m_flag(false) { m_buff[0] = '\0'; m_errorInfo.product = (PLI_BYTE8*)Verilated::productName(); } ~VerilatedVpiError() {} static void selfTest() VL_MT_UNSAFE_ONE; VerilatedVpiError* setMessage(PLI_INT32 level) { m_flag = true; m_errorInfo.level = level; return this; } void setMessage(std::string file, PLI_INT32 line, const char* message, ...) { // message cannot be a const string& as va_start cannot use a reference static VL_THREAD_LOCAL std::string filehold; va_list args; va_start(args, message); VL_VSNPRINTF(m_buff, sizeof(m_buff), message, args); va_end(args); m_errorInfo.state = vpiPLI; filehold = file; setError((PLI_BYTE8*)m_buff, NULL, (PLI_BYTE8*)filehold.c_str(), line); } p_vpi_error_info getError() { if (m_flag) return &m_errorInfo; return NULL; } void resetError() { m_flag = false; } static void vpi_unsupported() { // Not supported yet p_vpi_error_info error_info_p = VerilatedVpiImp::error_info()->getError(); if (error_info_p) { VL_FATAL_MT(error_info_p->file, error_info_p->line, "", error_info_p->message); return; } VL_FATAL_MT(__FILE__, __LINE__, "", "vpi_unsupported called without error info set"); } static const char* strFromVpiVal(PLI_INT32 vpiVal) VL_MT_SAFE; static const char* strFromVpiObjType(PLI_INT32 vpiVal) VL_MT_SAFE; static const char* strFromVpiMethod(PLI_INT32 vpiVal) VL_MT_SAFE; static const char* strFromVpiCallbackReason(PLI_INT32 vpiVal) VL_MT_SAFE; static const char* strFromVpiProp(PLI_INT32 vpiVal) VL_MT_SAFE; }; //====================================================================== VerilatedVpiImp VerilatedVpiImp::s_s; // Singleton VL_THREAD_LOCAL vluint8_t* VerilatedVpio::t_freeHead = NULL; //====================================================================== // VerilatedVpi implementation void VerilatedVpi::callTimedCbs() VL_MT_UNSAFE_ONE { VerilatedVpiImp::callTimedCbs(); } void VerilatedVpi::callValueCbs() VL_MT_UNSAFE_ONE { VerilatedVpiImp::callValueCbs(); } bool VerilatedVpi::callCbs(vluint32_t reason) VL_MT_UNSAFE_ONE { return VerilatedVpiImp::callCbs(reason); } //====================================================================== // VerilatedVpiImp implementation VerilatedVpiError* VerilatedVpiImp::error_info() VL_MT_UNSAFE_ONE { VerilatedVpiImp::assertOneCheck(); if (VL_UNLIKELY(!s_s.m_errorInfop)) { s_s.m_errorInfop = new VerilatedVpiError(); } return s_s.m_errorInfop; } //====================================================================== // VerilatedVpiError Methods const char* VerilatedVpiError::strFromVpiVal(PLI_INT32 vpiVal) VL_MT_SAFE { static const char* const names[] = { "*undefined*", "vpiBinStrVal", "vpiOctStrVal", "vpiDecStrVal", "vpiHexStrVal", "vpiScalarVal", "vpiIntVal", "vpiRealVal", "vpiStringVal", "vpiVectorVal", "vpiStrengthVal", "vpiTimeVal", "vpiObjTypeVal", "vpiSuppressVal", "vpiShortIntVal", "vpiLongIntVal", "vpiShortRealVal", "vpiRawTwoStateVal", "vpiRawFourStateVal", }; if (vpiVal < 0) return names[0]; return names[(vpiVal<=vpiRawFourStateVal) ? vpiVal : 0]; } const char* VerilatedVpiError::strFromVpiObjType(PLI_INT32 vpiVal) VL_MT_SAFE { static const char* const names[] = { "*undefined*", "vpiAlways", "vpiAssignStmt", "vpiAssignment", "vpiBegin", "vpiCase", "vpiCaseItem", "vpiConstant", "vpiContAssign", "vpiDeassign", "vpiDefParam", "vpiDelayControl", "vpiDisable", "vpiEventControl", "vpiEventStmt", "vpiFor", "vpiForce", "vpiForever", "vpiFork", "vpiFuncCall", "vpiFunction", "vpiGate", "vpiIf", "vpiIfElse", "vpiInitial", "vpiIntegerVar", "vpiInterModPath", "vpiIterator", "vpiIODecl", "vpiMemory", "vpiMemoryWord", "vpiModPath", "vpiModule", "vpiNamedBegin", "vpiNamedEvent", "vpiNamedFork", "vpiNet", "vpiNetBit", "vpiNullStmt", "vpiOperation", "vpiParamAssign", "vpiParameter", "vpiPartSelect", "vpiPathTerm", "vpiPort", "vpiPortBit", "vpiPrimTerm", "vpiRealVar", "vpiReg", "vpiRegBit", "vpiRelease", "vpiRepeat", "vpiRepeatControl", "vpiSchedEvent", "vpiSpecParam", "vpiSwitch", "vpiSysFuncCall", "vpiSysTaskCall", "vpiTableEntry", "vpiTask", "vpiTaskCall", "vpiTchk", "vpiTchkTerm", "vpiTimeVar", "vpiTimeQueue", "vpiUdp", "vpiUdpDefn", "vpiUserSystf", "vpiVarSelect", "vpiWait", "vpiWhile", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "vpiAttribute", "vpiBitSelect", "vpiCallback", "vpiDelayTerm", "vpiDelayDevice", "vpiFrame", "vpiGateArray", "vpiModuleArray", "vpiPrimitiveArray", "vpiNetArray", "vpiRange", "vpiRegArray", "vpiSwitchArray", "vpiUdpArray", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "*undefined*", "vpiContAssignBit", "vpiNamedEventArray", "vpiIndexedPartSelect", "*undefined*", "*undefined*", "vpiGenScopeArray", "vpiGenScope", "vpiGenVar" }; if (vpiVal < 0) return names[0]; return names[(vpiVal<=vpiGenVar) ? vpiVal : 0]; } const char* VerilatedVpiError::strFromVpiMethod(PLI_INT32 vpiVal) VL_MT_SAFE { static const char* const names[] = { "vpiCondition", "vpiDelay", "vpiElseStmt", "vpiForIncStmt", "vpiForInitStmt", "vpiHighConn", "vpiLhs", "vpiIndex", "vpiLeftRange", "vpiLowConn", "vpiParent", "vpiRhs", "vpiRightRange", "vpiScope", "vpiSysTfCall", "vpiTchkDataTerm", "vpiTchkNotifier", "vpiTchkRefTerm", "vpiArgument", "vpiBit", "vpiDriver", "vpiInternalScope", "vpiLoad", "vpiModDataPathIn", "vpiModPathIn", "vpiModPathOut", "vpiOperand", "vpiPortInst", "vpiProcess", "vpiVariables", "vpiUse", "vpiExpr", "vpiPrimitive", "vpiStmt" }; if (vpiVal>vpiStmt || vpiVal<vpiCondition) { return "*undefined*"; } return names[vpiVal-vpiCondition]; } const char* VerilatedVpiError::strFromVpiCallbackReason(PLI_INT32 vpiVal) VL_MT_SAFE { static const char* const names[] = { "*undefined*", "cbValueChange", "cbStmt", "cbForce", "cbRelease", "cbAtStartOfSimTime", "cbReadWriteSynch", "cbReadOnlySynch", "cbNextSimTime", "cbAfterDelay", "cbEndOfCompile", "cbStartOfSimulation", "cbEndOfSimulation", "cbError", "cbTchkViolation", "cbStartOfSave", "cbEndOfSave", "cbStartOfRestart", "cbEndOfRestart", "cbStartOfReset", "cbEndOfReset", "cbEnterInteractive", "cbExitInteractive", "cbInteractiveScopeChange", "cbUnresolvedSystf", "cbAssign", "cbDeassign", "cbDisable", "cbPLIError", "cbSignal", "cbNBASynch", "cbAtEndOfSimTime" }; if (vpiVal < 0) return names[0]; return names[(vpiVal<=cbAtEndOfSimTime) ? vpiVal : 0]; } const char* VerilatedVpiError::strFromVpiProp(PLI_INT32 vpiVal) VL_MT_SAFE { static const char* const names[] = { "*undefined or other*", "vpiType", "vpiName", "vpiFullName", "vpiSize", "vpiFile", "vpiLineNo", "vpiTopModule", "vpiCellInstance", "vpiDefName", "vpiProtected", "vpiTimeUnit", "vpiTimePrecision", "vpiDefNetType", "vpiUnconnDrive", "vpiDefFile", "vpiDefLineNo", "vpiScalar", "vpiVector", "vpiExplicitName", "vpiDirection", "vpiConnByName", "vpiNetType", "vpiExplicitScalared", "vpiExplicitVectored", "vpiExpanded", "vpiImplicitDecl", "vpiChargeStrength", "vpiArray", "vpiPortIndex", "vpiTermIndex", "vpiStrength0", "vpiStrength1", "vpiPrimType", "vpiPolarity", "vpiDataPolarity", "vpiEdge", "vpiPathType", "vpiTchkType", "vpiOpType", "vpiConstType", "vpiBlocking", "vpiCaseType", "vpiFuncType", "vpiNetDeclAssign", "vpiUserDefn", "vpiScheduled", "*undefined*", "*undefined*", "vpiActive", "vpiAutomatic", "vpiCell", "vpiConfig", "vpiConstantSelect", "vpiDecompile", "vpiDefAttribute", "vpiDelayType", "vpiIteratorType", "vpiLibrary", "*undefined*", "vpiOffset", "vpiResolvedNetType", "vpiSaveRestartID", "vpiSaveRestartLocation", "vpiValid", "vpiSigned", "vpiStop", "vpiFinish", "vpiReset", "vpiSetInteractiveScope", "vpiLocalParam", "vpiModPathHasIfNone", "vpiIndexedPartSelectType", "vpiIsMemory", "vpiIsProtected" }; if (vpiVal == vpiUndefined) { return "vpiUndefined"; } return names[(vpiVal<=vpiIsProtected) ? vpiVal : 0]; } #define CHECK_RESULT_CSTR(got, exp) \ if (strcmp((got), (exp))) { \ std::string msg = std::string("%Error: ") \ + "GOT = '"+((got)?(got):"<null>")+"'" \ + " EXP = '"+((exp)?(exp):"<null>")+"'"; \ VL_FATAL_MT(__FILE__, __LINE__, "", msg.c_str()); \ } #define CHECK_ENUM_STR(fn, enum) \ do { \ const char* strVal = VerilatedVpiError::fn(enum); \ CHECK_RESULT_CSTR(strVal, #enum); \ } while (0) void VerilatedVpi::selfTest() VL_MT_UNSAFE_ONE { VerilatedVpiError::selfTest(); } void VerilatedVpiError::selfTest() VL_MT_UNSAFE_ONE { VerilatedVpiImp::assertOneCheck(); CHECK_ENUM_STR(strFromVpiVal, vpiBinStrVal); CHECK_ENUM_STR(strFromVpiVal, vpiRawFourStateVal); CHECK_ENUM_STR(strFromVpiObjType, vpiAlways); CHECK_ENUM_STR(strFromVpiObjType, vpiWhile); CHECK_ENUM_STR(strFromVpiObjType, vpiAttribute); CHECK_ENUM_STR(strFromVpiObjType, vpiUdpArray); CHECK_ENUM_STR(strFromVpiObjType, vpiContAssignBit); CHECK_ENUM_STR(strFromVpiObjType, vpiGenVar); CHECK_ENUM_STR(strFromVpiMethod, vpiCondition); CHECK_ENUM_STR(strFromVpiMethod, vpiStmt); CHECK_ENUM_STR(strFromVpiCallbackReason, cbValueChange); CHECK_ENUM_STR(strFromVpiCallbackReason, cbAtEndOfSimTime); CHECK_ENUM_STR(strFromVpiProp, vpiType); CHECK_ENUM_STR(strFromVpiProp, vpiProtected); CHECK_ENUM_STR(strFromVpiProp, vpiDirection); CHECK_ENUM_STR(strFromVpiProp, vpiTermIndex); CHECK_ENUM_STR(strFromVpiProp, vpiConstType); CHECK_ENUM_STR(strFromVpiProp, vpiAutomatic); CHECK_ENUM_STR(strFromVpiProp, vpiOffset); CHECK_ENUM_STR(strFromVpiProp, vpiStop); CHECK_ENUM_STR(strFromVpiProp, vpiIsProtected); } #undef CHECK_ENUM_STR #undef CHECK_RESULT_CSTR //====================================================================== // callback related vpiHandle vpi_register_cb(p_cb_data cb_data_p) { VerilatedVpiImp::assertOneCheck(); _VL_VPI_ERROR_RESET(); // cppcheck-suppress nullPointer if (VL_UNLIKELY(!cb_data_p)) { _VL_VPI_WARNING(__FILE__, __LINE__, "%s : callback data pointer is null", VL_FUNC); return NULL; } switch (cb_data_p->reason) { case cbAfterDelay: { QData time = 0; if (cb_data_p->time) time = _VL_SET_QII(cb_data_p->time->high, cb_data_p->time->low); VerilatedVpioCb* vop = new VerilatedVpioCb(cb_data_p, VL_TIME_Q()+time); VL_DEBUG_IF_PLI(VL_DBG_MSGF("- vpi: vpi_register_cb %d %p delay=%" VL_PRI64 "u\n", cb_data_p->reason, vop, time);); VerilatedVpiImp::cbTimedAdd(vop); return vop->castVpiHandle(); } case cbReadWriteSynch: // FALLTHRU // Supported via vlt_main.cpp case cbReadOnlySynch: // FALLTHRU // Supported via vlt_main.cpp case cbNextSimTime: // FALLTHRU // Supported via vlt_main.cpp case cbStartOfSimulation: // FALLTHRU // Supported via vlt_main.cpp case cbEndOfSimulation: // FALLTHRU // Supported via vlt_main.cpp case cbValueChange: // FALLTHRU // Supported via vlt_main.cpp case cbPLIError: // FALLTHRU // NOP, but need to return handle, so make object case cbEnterInteractive: // FALLTHRU // NOP, but need to return handle, so make object case cbExitInteractive: // FALLTHRU // NOP, but need to return handle, so make object case cbInteractiveScopeChange: { // FALLTHRU // NOP, but need to return handle, so make object VerilatedVpioCb* vop = new VerilatedVpioCb(cb_data_p, 0); VL_DEBUG_IF_PLI(VL_DBG_MSGF("- vpi: vpi_register_cb %d %p\n", cb_data_p->reason, vop);); VerilatedVpiImp::cbReasonAdd(vop); return vop->castVpiHandle(); } default: _VL_VPI_WARNING(__FILE__, __LINE__, "%s: Unsupported callback type %s", VL_FUNC, VerilatedVpiError::strFromVpiCallbackReason(cb_data_p->reason)); return NULL; }; } PLI_INT32 vpi_remove_cb(vpiHandle object) { VL_DEBUG_IF_PLI(VL_DBG_MSGF("- vpi: vpi_remove_cb %p\n", object);); VerilatedVpiImp::assertOneCheck(); VerilatedVpioCb* vop = VerilatedVpioCb::castp(object); _VL_VPI_ERROR_RESET(); if (VL_UNLIKELY(!vop)) return 0; if (vop->cb_datap()->reason == cbAfterDelay) { VerilatedVpiImp::cbTimedRemove(vop); } else { VerilatedVpiImp::cbReasonRemove(vop); } return 1; } void vpi_get_cb_info(vpiHandle object, p_cb_data cb_data_p) { _VL_VPI_UNIMP(); return; } vpiHandle vpi_register_systf(p_vpi_systf_data systf_data_p) { _VL_VPI_UNIMP(); return 0; } void vpi_get_systf_info(vpiHandle object, p_vpi_systf_data systf_data_p) { _VL_VPI_UNIMP(); return; } // for obtaining handles vpiHandle vpi_handle_by_name(PLI_BYTE8* namep, vpiHandle scope) { VerilatedVpiImp::assertOneCheck(); _VL_VPI_ERROR_RESET(); if (VL_UNLIKELY(!namep)) return NULL; VL_DEBUG_IF_PLI(VL_DBG_MSGF("- vpi: vpi_handle_by_name %s %p\n", namep, scope);); const VerilatedVar* varp = NULL; const VerilatedScope* scopep; VerilatedVpioScope* voScopep = VerilatedVpioScope::castp(scope); std::string scopeAndName = namep; if (voScopep) { scopeAndName = std::string(voScopep->fullname()) + "." + namep; namep = (PLI_BYTE8*)scopeAndName.c_str(); } { // This doesn't yet follow the hierarchy in the proper way scopep = Verilated::scopeFind(namep); if (scopep) { // Whole thing found as a scope if (scopep->type() == VerilatedScope::SCOPE_MODULE) { return (new VerilatedVpioModule(scopep))->castVpiHandle(); } else { return (new VerilatedVpioScope(scopep))->castVpiHandle(); } } const char* baseNamep = scopeAndName.c_str(); std::string scopename; const char* dotp = strrchr(namep, '.'); if (VL_LIKELY(dotp)) { baseNamep = dotp+1; scopename = std::string(namep, dotp-namep); } if (scopename.find(".") == std::string::npos) { // This is a toplevel, hence search in our TOP ports first. scopep = Verilated::scopeFind("TOP"); if (scopep) { varp = scopep->varFind(baseNamep); } } if (!varp) { scopep = Verilated::scopeFind(scopename.c_str()); if (!scopep) return NULL; varp = scopep->varFind(baseNamep); } } if (!varp) return NULL; return (new VerilatedVpioVar(varp, scopep))->castVpiHandle(); } vpiHandle vpi_handle_by_index(vpiHandle object, PLI_INT32 indx) { // Used to get array entries VL_DEBUG_IF_PLI(VL_DBG_MSGF("- vpi: vpi_handle_by_index %p %d\n", object, indx);); VerilatedVpiImp::assertOneCheck(); VerilatedVpioVar* varop = VerilatedVpioVar::castp(object); _VL_VPI_ERROR_RESET(); if (VL_LIKELY(varop)) { if (varop->varp()->dims()<2) return 0; if (VL_LIKELY(varop->varp()->unpacked().left() >= varop->varp()->unpacked().right())) { if (VL_UNLIKELY(indx > varop->varp()->unpacked().left() || indx < varop->varp()->unpacked().right())) return 0; return (new VerilatedVpioMemoryWord(varop->varp(), varop->scopep(), indx, indx - varop->varp()->unpacked().right())) ->castVpiHandle(); } if (VL_UNLIKELY(indx < varop->varp()->unpacked().left() || indx > varop->varp()->unpacked().right())) return 0; return (new VerilatedVpioMemoryWord(varop->varp(), varop->scopep(), indx, indx - varop->varp()->unpacked().left())) ->castVpiHandle(); } _VL_VPI_INTERNAL(__FILE__, __LINE__, "%s : can't resolve handle", VL_FUNC); return 0; } // for traversing relationships vpiHandle vpi_handle(PLI_INT32 type, vpiHandle object) { VL_DEBUG_IF_PLI(VL_DBG_MSGF("- vpi: vpi_handle %d %p\n", type, object);); VerilatedVpiImp::assertOneCheck(); _VL_VPI_ERROR_RESET(); switch (type) { case vpiLeftRange: { VerilatedVpioVar* vop = VerilatedVpioVar::castp(object); if (VL_UNLIKELY(!vop)) return 0; if (VL_UNLIKELY(!vop->rangep())) return 0; return (new VerilatedVpioConst(vop->rangep()->left()))->castVpiHandle(); } case vpiRightRange: { VerilatedVpioVar* vop = VerilatedVpioVar::castp(object); if (VL_UNLIKELY(!vop)) return 0; if (VL_UNLIKELY(!vop->rangep())) return 0; return (new VerilatedVpioConst(vop->rangep()->right()))->castVpiHandle(); } case vpiIndex: { VerilatedVpioVar* vop = VerilatedVpioVar::castp(object); if (VL_UNLIKELY(!vop)) return 0; return (new VerilatedVpioConst(vop->index()))->castVpiHandle(); } case vpiScope: { VerilatedVpioVar* vop = VerilatedVpioVar::castp(object); if (VL_UNLIKELY(!vop)) return 0; return (new VerilatedVpioScope(vop->scopep()))->castVpiHandle(); } case vpiParent: { VerilatedVpioMemoryWord* vop = VerilatedVpioMemoryWord::castp(object); if (VL_UNLIKELY(!vop)) return 0; return (new VerilatedVpioVar(vop->varp(), vop->scopep()))->castVpiHandle(); } default: _VL_VPI_WARNING(__FILE__, __LINE__, "%s: Unsupported type %s, nothing will be returned", VL_FUNC, VerilatedVpiError::strFromVpiMethod(type)); return 0; } } vpiHandle vpi_handle_multi(PLI_INT32 type, vpiHandle refHandle1, vpiHandle refHandle2, ... ) { _VL_VPI_UNIMP(); return 0; } vpiHandle vpi_iterate(PLI_INT32 type, vpiHandle object) { VL_DEBUG_IF_PLI(VL_DBG_MSGF("- vpi: vpi_iterate %d %p\n", type, object);); VerilatedVpiImp::assertOneCheck(); _VL_VPI_ERROR_RESET(); switch (type) { case vpiMemoryWord: { VerilatedVpioVar* vop = VerilatedVpioVar::castp(object); if (VL_UNLIKELY(!vop)) return 0; if (vop->varp()->dims() < 2) return 0; if (vop->varp()->dims() > 2) { _VL_VPI_WARNING(__FILE__, __LINE__, "%s: %s, object %s has unsupported number of indices (%d)", VL_FUNC, VerilatedVpiError::strFromVpiMethod(type), vop->fullname() , vop->varp()->dims()); } return (new VerilatedVpioMemoryWordIter(object, vop->varp()))->castVpiHandle(); } case vpiRange: { VerilatedVpioVar* vop = VerilatedVpioVar::castp(object); if (VL_UNLIKELY(!vop)) return 0; if (vop->varp()->dims() < 2) return 0; // Unsupported is multidim list if (vop->varp()->dims() > 2) { _VL_VPI_WARNING(__FILE__, __LINE__, "%s: %s, object %s has unsupported number of indices (%d)", VL_FUNC, VerilatedVpiError::strFromVpiMethod(type), vop->fullname() , vop->varp()->dims()); } return ((new VerilatedVpioRange(vop->rangep()))->castVpiHandle()); } case vpiReg: { VerilatedVpioScope* vop = VerilatedVpioScope::castp(object); if (VL_UNLIKELY(!vop)) return 0; return ((new VerilatedVpioVarIter(vop->scopep())) ->castVpiHandle()); } case vpiModule: { VerilatedVpioModule* vop = VerilatedVpioModule::castp(object); const VerilatedHierarchyMap* map = VerilatedImp::hierarchyMap(); const VerilatedScope *mod = vop ? vop->scopep() : NULL; VerilatedHierarchyMap::const_iterator it = map->find((VerilatedScope*) mod); if (it == map->end()) return 0; return ((new VerilatedVpioModuleIter(it->second))->castVpiHandle()); } default: _VL_VPI_WARNING(__FILE__, __LINE__, "%s: Unsupported type %s, nothing will be returned", VL_FUNC, VerilatedVpiError::strFromVpiObjType(type)); return 0; } } vpiHandle vpi_scan(vpiHandle object) { VL_DEBUG_IF_PLI(VL_DBG_MSGF("- vpi: vpi_scan %p\n", object);); VerilatedVpiImp::assertOneCheck(); _VL_VPI_ERROR_RESET(); VerilatedVpio* vop = VerilatedVpio::castp(object); if (VL_UNLIKELY(!vop)) return NULL; return vop->dovpi_scan(); } // for processing properties PLI_INT32 vpi_get(PLI_INT32 property, vpiHandle object) { // Leave this in the header file - in many cases the compiler can constant propagate "object" VL_DEBUG_IF_PLI(VL_DBG_MSGF("- vpi: vpi_get %d %p\n", property, object);); VerilatedVpiImp::assertOneCheck(); _VL_VPI_ERROR_RESET(); switch (property) { case vpiTimePrecision: { return VL_TIME_PRECISION; } case vpiTimeUnit: { return VL_TIME_UNIT; } case vpiType: { VerilatedVpio* vop = VerilatedVpio::castp(object); if (VL_UNLIKELY(!vop)) return 0; return vop->type(); } case vpiDirection: { // By forthought, the directions already are vpi enumerated VerilatedVpioVar* vop = VerilatedVpioVar::castp(object); if (VL_UNLIKELY(!vop)) return 0; return vop->varp()->vldir(); } case vpiScalar: // FALLTHRU case vpiVector: { VerilatedVpioVar* vop = VerilatedVpioVar::castp(object); if (VL_UNLIKELY(!vop)) return 0; return (property==vpiVector) ^ (vop->varp()->dims()==0); } case vpiSize: { VerilatedVpioVar* vop = VerilatedVpioVar::castp(object); if (VL_UNLIKELY(!vop)) return 0; return vop->size(); } default: _VL_VPI_WARNING(__FILE__, __LINE__, "%s: Unsupported type %s, nothing will be returned", VL_FUNC, VerilatedVpiError::strFromVpiProp(property)); return 0; } } PLI_INT64 vpi_get64(PLI_INT32 property, vpiHandle object) { _VL_VPI_UNIMP(); return 0; } PLI_BYTE8 *vpi_get_str(PLI_INT32 property, vpiHandle object) { VL_DEBUG_IF_PLI(VL_DBG_MSGF("- vpi: vpi_get_str %d %p\n", property, object);); VerilatedVpiImp::assertOneCheck(); VerilatedVpio* vop = VerilatedVpio::castp(object); _VL_VPI_ERROR_RESET(); if (VL_UNLIKELY(!vop)) return NULL; switch (property) { case vpiName: { return (PLI_BYTE8*)vop->name(); } case vpiFullName: { return (PLI_BYTE8*)vop->fullname(); } case vpiDefName: { return (PLI_BYTE8*)vop->defname(); } case vpiType: { return (PLI_BYTE8*) VerilatedVpiError::strFromVpiObjType(vop->type()); } default: _VL_VPI_WARNING(__FILE__, __LINE__, "%s: Unsupported type %s, nothing will be returned", VL_FUNC, VerilatedVpiError::strFromVpiProp(property)); return 0; } } // delay processing void vpi_get_delays(vpiHandle object, p_vpi_delay delay_p) { _VL_VPI_UNIMP(); return; } void vpi_put_delays(vpiHandle object, p_vpi_delay delay_p) { _VL_VPI_UNIMP(); return; } // value processing void vpi_get_value(vpiHandle object, p_vpi_value value_p) { // Maximum required size is for binary string, one byte per bit plus null termination static VL_THREAD_LOCAL char outStr[1+VL_MULS_MAX_WORDS*32]; // cppcheck-suppress variableScope static VL_THREAD_LOCAL int outStrSz = sizeof(outStr)-1; VL_DEBUG_IF_PLI(VL_DBG_MSGF("- vpi: vpi_get_value %p\n", object);); VerilatedVpiImp::assertOneCheck(); _VL_VPI_ERROR_RESET(); if (VL_UNLIKELY(!value_p)) return; if (VerilatedVpioVar* vop = VerilatedVpioVar::castp(object)) { // We used to presume vpiValue.format = vpiIntVal or if single bit vpiScalarVal // This may cause backward compatability issues with older code. if (value_p->format == vpiVectorVal) { // Vector pointer must come from our memory pool // It only needs to persist until the next vpi_get_value static VL_THREAD_LOCAL t_vpi_vecval out[VL_MULS_MAX_WORDS*2]; value_p->value.vector = out; switch (vop->varp()->vltype()) { case VLVT_UINT8: out[0].aval = *(reinterpret_cast<CData*>(vop->varDatap())); out[0].bval = 0; return; case VLVT_UINT16: out[0].aval = *(reinterpret_cast<SData*>(vop->varDatap())); out[0].bval = 0; return; case VLVT_UINT32: out[0].aval = *(reinterpret_cast<IData*>(vop->varDatap())); out[0].bval = 0; return; case VLVT_WDATA: { int words = VL_WORDS_I(vop->varp()->packed().elements()); if (VL_UNCOVERABLE(words >= VL_MULS_MAX_WORDS)) { VL_FATAL_MT(__FILE__, __LINE__, "", "vpi_get_value with more than VL_MULS_MAX_WORDS; increase and recompile"); } WDataInP datap = (reinterpret_cast<EData*>(vop->varDatap())); for (int i=0; i<words; ++i) { out[i].aval = datap[i]; out[i].bval = 0; } return; } case VLVT_UINT64: { QData data = *(reinterpret_cast<QData*>(vop->varDatap())); out[1].aval = static_cast<IData>(data>>VL_ULL(32)); out[1].bval = 0; out[0].aval = static_cast<IData>(data); out[0].bval = 0; return; } default: { _VL_VPI_ERROR(__FILE__, __LINE__, "%s: Unsupported format (%s) for %s", VL_FUNC, VerilatedVpiError::strFromVpiVal(value_p->format), vop->fullname()); return; } } } else if (value_p->format == vpiBinStrVal) { value_p->value.str = outStr; switch (vop->varp()->vltype()) { case VLVT_UINT8: case VLVT_UINT16: case VLVT_UINT32: case VLVT_UINT64: case VLVT_WDATA: { int bits = vop->varp()->packed().elements(); CData* datap = (reinterpret_cast<CData*>(vop->varDatap())); int i; if (bits > outStrSz) { // limit maximum size of output to size of buffer to prevent overrun. bits = outStrSz; _VL_VPI_WARNING(__FILE__, __LINE__, "%s: Truncating string value of %s for %s" " as buffer size (%d, VL_MULS_MAX_WORDS=%d) is less than required (%d)", VL_FUNC, VerilatedVpiError::strFromVpiVal(value_p->format), vop->fullname(), outStrSz, VL_MULS_MAX_WORDS, bits); } for (i=0; i<bits; ++i) { char val = (datap[i>>3]>>(i&7))&1; outStr[bits-i-1] = val?'1':'0'; } outStr[i] = '\0'; return; } default: _VL_VPI_ERROR(__FILE__, __LINE__, "%s: Unsupported format (%s) for %s", VL_FUNC, VerilatedVpiError::strFromVpiVal(value_p->format), vop->fullname()); return; } } else if (value_p->format == vpiOctStrVal) { value_p->value.str = outStr; switch (vop->varp()->vltype()) { case VLVT_UINT8: case VLVT_UINT16: case VLVT_UINT32: case VLVT_UINT64: case VLVT_WDATA: { int chars = (vop->varp()->packed().elements()+2)/3; int bytes = VL_BYTES_I(vop->varp()->packed().elements()); CData* datap = (reinterpret_cast<CData*>(vop->varDatap())); int i; if (chars > outStrSz) { // limit maximum size of output to size of buffer to prevent overrun. _VL_VPI_WARNING(__FILE__, __LINE__, "%s: Truncating string value of %s for %s" " as buffer size (%d, VL_MULS_MAX_WORDS=%d) is less than required (%d)", VL_FUNC, VerilatedVpiError::strFromVpiVal(value_p->format), vop->fullname(), outStrSz, VL_MULS_MAX_WORDS, chars); chars = outStrSz; } for (i=0; i<chars; ++i) { div_t idx = div(i*3, 8); int val = datap[idx.quot]; if ((idx.quot+1)<bytes) { // if the next byte is valid or that in // for when the required 3 bits straddle adjacent bytes val |= datap[idx.quot+1]<<8; } // align so least significant 3 bits represent octal char val >>= idx.rem; if (i==(chars-1)) { // most signifcant char, mask off non existant bits when vector // size is not a multiple of 3 unsigned int rem = vop->varp()->packed().elements() % 3; if (rem) { // generate bit mask & zero non existant bits val &= (1<<rem)-1; } } outStr[chars-i-1] = '0' + (val&7); } outStr[i] = '\0'; return; } default: strcpy(outStr, "0"); _VL_VPI_ERROR(__FILE__, __LINE__, "%s: Unsupported format (%s) for %s", VL_FUNC, VerilatedVpiError::strFromVpiVal(value_p->format), vop->fullname()); return; } } else if (value_p->format == vpiDecStrVal) { value_p->value.str = outStr; switch (vop->varp()->vltype()) { // outStrSz does not include NULL termination so add one case VLVT_UINT8: VL_SNPRINTF(outStr, outStrSz+1, "%hhu", static_cast<unsigned char>(*(reinterpret_cast<CData*>(vop->varDatap())))); return; case VLVT_UINT16: VL_SNPRINTF(outStr, outStrSz+1, "%hu", static_cast<unsigned short>(*(reinterpret_cast<SData*>(vop->varDatap())))); return; case VLVT_UINT32: VL_SNPRINTF(outStr, outStrSz+1, "%u", static_cast<unsigned int>(*(reinterpret_cast<IData*>(vop->varDatap())))); return; case VLVT_UINT64: VL_SNPRINTF(outStr, outStrSz+1, "%llu", static_cast<unsigned long long>(*(reinterpret_cast<QData*>(vop->varDatap())))); return; default: strcpy(outStr, "-1"); _VL_VPI_ERROR(__FILE__, __LINE__, "%s: Unsupported format (%s) for %s, maximum limit is 64 bits", VL_FUNC, VerilatedVpiError::strFromVpiVal(value_p->format), vop->fullname()); return; } } else if (value_p->format == vpiHexStrVal) { value_p->value.str = outStr; switch (vop->varp()->vltype()) { case VLVT_UINT8: case VLVT_UINT16: case VLVT_UINT32: case VLVT_UINT64: case VLVT_WDATA: { int chars = (vop->varp()->packed().elements()+3)>>2; CData* datap = (reinterpret_cast<CData*>(vop->varDatap())); int i; if (chars > outStrSz) { // limit maximum size of output to size of buffer to prevent overrun. _VL_VPI_WARNING(__FILE__, __LINE__, "%s: Truncating string value of %s for %s" " as buffer size (%d, VL_MULS_MAX_WORDS=%d) is less than required (%d)", VL_FUNC, VerilatedVpiError::strFromVpiVal(value_p->format), vop->fullname(), outStrSz, VL_MULS_MAX_WORDS, chars); chars = outStrSz; } for (i=0; i<chars; ++i) { char val = (datap[i>>1]>>((i&1)<<2))&15; if (i==(chars-1)) { // most signifcant char, mask off non existant bits when vector // size is not a multiple of 4 unsigned int rem = vop->varp()->packed().elements() & 3; if (rem) { // generate bit mask & zero non existant bits val &= (1<<rem)-1; } } outStr[chars-i-1] = "0123456789abcdef"[static_cast<int>(val)]; } outStr[i] = '\0'; return; } default: _VL_VPI_ERROR(__FILE__, __LINE__, "%s: Unsupported format (%s) for %s", VL_FUNC, VerilatedVpiError::strFromVpiVal(value_p->format), vop->fullname()); return; } } else if (value_p->format == vpiStringVal) { value_p->value.str = outStr; switch (vop->varp()->vltype()) { case VLVT_UINT8: case VLVT_UINT16: case VLVT_UINT32: case VLVT_UINT64: case VLVT_WDATA: { int bytes = VL_BYTES_I(vop->varp()->packed().elements()); CData* datap = (reinterpret_cast<CData*>(vop->varDatap())); int i; if (bytes > outStrSz) { // limit maximum size of output to size of buffer to prevent overrun. _VL_VPI_WARNING(__FILE__, __LINE__, "%s: Truncating string value of %s for %s" " as buffer size (%d, VL_MULS_MAX_WORDS=%d) is less than required (%d)", VL_FUNC, VerilatedVpiError::strFromVpiVal(value_p->format), vop->fullname(), outStrSz, VL_MULS_MAX_WORDS, bytes); bytes = outStrSz; } for (i=0; i<bytes; ++i) { char val = datap[bytes-i-1]; // other simulators replace [leading?] zero chars with spaces, replicate here. outStr[i] = val?val:' '; } outStr[i] = '\0'; return; } default: _VL_VPI_ERROR(__FILE__, __LINE__, "%s: Unsupported format (%s) for %s", VL_FUNC, VerilatedVpiError::strFromVpiVal(value_p->format), vop->fullname()); return; } } else if (value_p->format == vpiIntVal) { switch (vop->varp()->vltype()) { case VLVT_UINT8: value_p->value.integer = *(reinterpret_cast<CData*>(vop->varDatap())); return; case VLVT_UINT16: value_p->value.integer = *(reinterpret_cast<SData*>(vop->varDatap())); return; case VLVT_UINT32: value_p->value.integer = *(reinterpret_cast<IData*>(vop->varDatap())); return; case VLVT_WDATA: // FALLTHRU case VLVT_UINT64: // FALLTHRU default: value_p->value.integer = 0; _VL_VPI_ERROR(__FILE__, __LINE__, "%s: Unsupported format (%s) for %s", VL_FUNC, VerilatedVpiError::strFromVpiVal(value_p->format), vop->fullname()); return; } } else if (value_p->format == vpiSuppressVal) { return; } _VL_VPI_ERROR(__FILE__, __LINE__, "%s: Unsupported format (%s) as requested for %s", VL_FUNC, VerilatedVpiError::strFromVpiVal(value_p->format), vop->fullname()); return; } else if (VerilatedVpioConst* vop = VerilatedVpioConst::castp(object)) { if (value_p->format == vpiIntVal) { value_p->value.integer = vop->num(); return; } _VL_VPI_ERROR(__FILE__, __LINE__, "%s: Unsupported format (%s) for %s", VL_FUNC, VerilatedVpiError::strFromVpiVal(value_p->format), vop->fullname()); return; } _VL_VPI_ERROR(__FILE__, __LINE__, "%s: Unsupported format %s", VL_FUNC, VerilatedVpiError::strFromVpiVal(value_p->format)); } vpiHandle vpi_put_value(vpiHandle object, p_vpi_value value_p, p_vpi_time time_p, PLI_INT32 flags) { VL_DEBUG_IF_PLI(VL_DBG_MSGF("- vpi: vpi_put_value %p %p\n", object, value_p);); VerilatedVpiImp::assertOneCheck(); _VL_VPI_ERROR_RESET(); if (VL_UNLIKELY(!value_p)) { _VL_VPI_WARNING(__FILE__, __LINE__, "Ignoring vpi_put_value with NULL value pointer"); return 0; } if (VerilatedVpioVar* vop = VerilatedVpioVar::castp(object)) { VL_DEBUG_IF_PLI(VL_DBG_MSGF("- vpi: vpi_put_value name=%s fmt=%d vali=%d\n", vop->fullname(), value_p->format, value_p->value.integer); VL_DBG_MSGF("- vpi: varp=%p putatp=%p\n", vop->varp()->datap(), vop->varDatap());); if (VL_UNLIKELY(!vop->varp()->isPublicRW())) { _VL_VPI_WARNING(__FILE__, __LINE__, "Ignoring vpi_put_value to signal marked read-only," " use public_flat_rw instead: ", vop->fullname()); return 0; } if (value_p->format == vpiVectorVal) { if (VL_UNLIKELY(!value_p->value.vector)) return NULL; switch (vop->varp()->vltype()) { case VLVT_UINT8: *(reinterpret_cast<CData*>(vop->varDatap())) = value_p->value.vector[0].aval & vop->mask(); return object; case VLVT_UINT16: *(reinterpret_cast<SData*>(vop->varDatap())) = value_p->value.vector[0].aval & vop->mask(); return object; case VLVT_UINT32: *(reinterpret_cast<IData*>(vop->varDatap())) = value_p->value.vector[0].aval & vop->mask(); return object; case VLVT_WDATA: { int words = VL_WORDS_I(vop->varp()->packed().elements()); WDataOutP datap = (reinterpret_cast<EData*>(vop->varDatap())); for (int i=0; i<words; ++i) { datap[i] = value_p->value.vector[i].aval; if (i==(words-1)) { datap[i] &= vop->mask(); } } return object; } case VLVT_UINT64: { *(reinterpret_cast<QData*>(vop->varDatap())) = _VL_SET_QII( value_p->value.vector[1].aval & vop->mask(), value_p->value.vector[0].aval); return object; } default: { _VL_VPI_ERROR(__FILE__, __LINE__, "%s: Unsupported format (%s) for %s", VL_FUNC, VerilatedVpiError::strFromVpiVal(value_p->format), vop->fullname()); return NULL; } } } else if (value_p->format == vpiBinStrVal) { switch (vop->varp()->vltype()) { case VLVT_UINT8: case VLVT_UINT16: case VLVT_UINT32: case VLVT_UINT64: case VLVT_WDATA: { int bits = vop->varp()->packed().elements(); int len = strlen(value_p->value.str); CData* datap = (reinterpret_cast<CData*>(vop->varDatap())); for (int i=0; i<bits; ++i) { char set = (i < len)?(value_p->value.str[len-i-1]=='1'):0; // zero bits 7:1 of byte when assigning to bit 0, else // or in 1 if bit set if (i&7) { datap[i>>3] |= set<<(i&7); } else { datap[i>>3] = set; } } return object; } default: _VL_VPI_ERROR(__FILE__, __LINE__, "%s: Unsupported format (%s) for %s", VL_FUNC, VerilatedVpiError::strFromVpiVal(value_p->format), vop->fullname()); return 0; } } else if (value_p->format == vpiOctStrVal) { switch (vop->varp()->vltype()) { case VLVT_UINT8: case VLVT_UINT16: case VLVT_UINT32: case VLVT_UINT64: case VLVT_WDATA: { int chars = (vop->varp()->packed().elements()+2)/3; int bytes = VL_BYTES_I(vop->varp()->packed().elements()); int len = strlen(value_p->value.str); CData* datap = (reinterpret_cast<CData*>(vop->varDatap())); div_t idx; datap[0] = 0; // reset zero'th byte for (int i=0; i<chars; ++i) { union { char byte[2]; short half; } val; idx = div(i*3, 8); if (i < len) { // ignore illegal chars char digit = value_p->value.str[len-i-1]; if (digit >= '0' && digit <= '7') { val.half = digit-'0'; } else { _VL_VPI_WARNING(__FILE__, __LINE__, "%s: Non octal character '%c' in '%s' as value %s for %s", VL_FUNC, digit, value_p->value.str, VerilatedVpiError::strFromVpiVal(value_p->format), vop->fullname()); val.half = 0; } } else { val.half = 0; } // align octal character to position within vector, note that // the three bits may straddle a byte bounday so two byte wide // assignments are made to adjacent bytes - but not if the least // signifcant byte of the aligned value is the most significant // byte of the destination. val.half <<= idx.rem; datap[idx.quot] |= val.byte[0]; // or in value if ((idx.quot+1) < bytes) { datap[idx.quot+1] = val.byte[1]; // this also resets // all bits to 0 prior to or'ing above } } // mask off non existant bits in the most significant byte if (idx.quot == (bytes-1)) { datap[idx.quot] &= vop->mask_byte(idx.quot); } else if (idx.quot+1 == (bytes-1)) { datap[idx.quot+1] &= vop->mask_byte(idx.quot+1); } // zero off remaining top bytes for (int i=idx.quot+2; i<bytes; ++i) { datap[i] = 0; } return object; } default: _VL_VPI_ERROR(__FILE__, __LINE__, "%s: Unsupported format (%s) for %s", VL_FUNC, VerilatedVpiError::strFromVpiVal(value_p->format), vop->fullname()); return 0; } } else if (value_p->format == vpiDecStrVal) { char remainder[16]; unsigned long long val; int success = sscanf(value_p->value.str, "%30llu%15s", &val, remainder); if (success < 1) { _VL_VPI_ERROR(__FILE__, __LINE__, "%s: Parsing failed for '%s' as value %s for %s", VL_FUNC, value_p->value.str, VerilatedVpiError::strFromVpiVal(value_p->format), vop->fullname()); return 0; } if (success > 1) { _VL_VPI_WARNING(__FILE__, __LINE__, "%s: Trailing garbage '%s' in '%s' as value %s for %s", VL_FUNC, remainder, value_p->value.str, VerilatedVpiError::strFromVpiVal(value_p->format), vop->fullname()); } switch (vop->varp()->vltype()) { case VLVT_UINT8: *(reinterpret_cast<CData*>(vop->varDatap())) = val & vop->mask(); break; case VLVT_UINT16: *(reinterpret_cast<SData*>(vop->varDatap())) = val & vop->mask(); break; case VLVT_UINT32: *(reinterpret_cast<IData*>(vop->varDatap())) = val & vop->mask(); break; case VLVT_UINT64: *(reinterpret_cast<QData*>(vop->varDatap())) = val; (reinterpret_cast<IData*>(vop->varDatap()))[1] &= vop->mask(); break; case VLVT_WDATA: default: _VL_VPI_ERROR(__FILE__, __LINE__, "%s: Unsupported format (%s) for %s, maximum limit is 64 bits", VL_FUNC, VerilatedVpiError::strFromVpiVal(value_p->format), vop->fullname()); return 0; } return object; } else if (value_p->format == vpiHexStrVal) { switch (vop->varp()->vltype()) { case VLVT_UINT8: case VLVT_UINT16: case VLVT_UINT32: case VLVT_UINT64: case VLVT_WDATA: { int chars = (vop->varp()->packed().elements()+3)>>2; CData* datap = (reinterpret_cast<CData*>(vop->varDatap())); char* val = value_p->value.str; // skip hex ident if one is detected at the start of the string if (val[0] == '0' && (val[1] == 'x' || val[1] == 'X')) { val += 2; } int len = strlen(val); for (int i=0; i<chars; ++i) { char hex; // compute hex digit value if (i < len) { char digit = val[len-i-1]; if (digit >= '0' && digit <= '9') hex = digit - '0'; else if (digit >= 'a' && digit <= 'f') hex = digit - 'a' + 10; else if (digit >= 'A' && digit <= 'F') hex = digit - 'A' + 10; else { _VL_VPI_WARNING(__FILE__, __LINE__, "%s: Non hex character '%c' in '%s' as value %s for %s", VL_FUNC, digit, value_p->value.str, VerilatedVpiError::strFromVpiVal(value_p->format), vop->fullname()); hex = 0; } } else { hex = 0; } // assign hex digit value to destination if (i&1) { datap[i>>1] |= hex<<4; } else { datap[i>>1] = hex; // this also resets all // bits to 0 prior to or'ing above of the msb } } // apply bit mask to most significant byte datap[(chars-1)>>1] &= vop->mask_byte((chars-1)>>1); return object; } default: _VL_VPI_ERROR(__FILE__, __LINE__, "%s: Unsupported format (%s) for %s", VL_FUNC, VerilatedVpiError::strFromVpiVal(value_p->format), vop->fullname()); return 0; } } else if (value_p->format == vpiStringVal) { switch (vop->varp()->vltype()) { case VLVT_UINT8: case VLVT_UINT16: case VLVT_UINT32: case VLVT_UINT64: case VLVT_WDATA: { int bytes = VL_BYTES_I(vop->varp()->packed().elements()); int len = strlen(value_p->value.str); CData* datap = (reinterpret_cast<CData*>(vop->varDatap())); for (int i=0; i<bytes; ++i) { // prepend with 0 values before placing string the least signifcant bytes datap[i] = (i < len)?value_p->value.str[len-i-1]:0; } return object; } default: _VL_VPI_ERROR(__FILE__, __LINE__, "%s: Unsupported format (%s) for %s", VL_FUNC, VerilatedVpiError::strFromVpiVal(value_p->format), vop->fullname()); return 0; } } else if (value_p->format == vpiIntVal) { switch (vop->varp()->vltype()) { case VLVT_UINT8: *(reinterpret_cast<CData*>(vop->varDatap())) = vop->mask() & value_p->value.integer; return object; case VLVT_UINT16: *(reinterpret_cast<SData*>(vop->varDatap())) = vop->mask() & value_p->value.integer; return object; case VLVT_UINT32: *(reinterpret_cast<IData*>(vop->varDatap())) = vop->mask() & value_p->value.integer; return object; case VLVT_WDATA: // FALLTHRU case VLVT_UINT64: // FALLTHRU default: _VL_VPI_ERROR(__FILE__, __LINE__, "%s: Unsupported format (%s) for %s", VL_FUNC, VerilatedVpiError::strFromVpiVal(value_p->format), vop->fullname()); return 0; } } _VL_VPI_ERROR(__FILE__, __LINE__, "%s: Unsupported format (%s) as requested for %s", VL_FUNC, VerilatedVpiError::strFromVpiVal(value_p->format), vop->fullname()); return NULL; } _VL_VPI_ERROR(__FILE__, __LINE__, "%s: Unsupported format (%s) for ??", VL_FUNC, VerilatedVpiError::strFromVpiVal(value_p->format)); return NULL; } void vpi_get_value_array(vpiHandle object, p_vpi_arrayvalue arrayvalue_p, PLI_INT32 *index_p, PLI_UINT32 num) { _VL_VPI_UNIMP(); return; } void vpi_put_value_array(vpiHandle object, p_vpi_arrayvalue arrayvalue_p, PLI_INT32 *index_p, PLI_UINT32 num) { _VL_VPI_UNIMP(); return; } // time processing void vpi_get_time(vpiHandle object, p_vpi_time time_p) { VerilatedVpiImp::assertOneCheck(); // cppcheck-suppress nullPointer if (VL_UNLIKELY(!time_p)) { _VL_VPI_WARNING(__FILE__, __LINE__, "Ignoring vpi_get_time with NULL value pointer"); return; } if (time_p->type == vpiSimTime) { QData qtime = VL_TIME_Q(); WData itime[2]; VL_SET_WQ(itime, qtime); time_p->low = itime[0]; time_p->high = itime[1]; return; } _VL_VPI_ERROR(__FILE__, __LINE__, "%s: Unsupported type (%d)", VL_FUNC, time_p->type); return; } // I/O routines PLI_UINT32 vpi_mcd_open(PLI_BYTE8 *filenamep) { VerilatedVpiImp::assertOneCheck(); _VL_VPI_ERROR_RESET(); return VL_FOPEN_S(filenamep, "wb"); } PLI_UINT32 vpi_mcd_close(PLI_UINT32 mcd) { VerilatedVpiImp::assertOneCheck(); _VL_VPI_ERROR_RESET(); VL_FCLOSE_I(mcd); return 0; } PLI_BYTE8 *vpi_mcd_name(PLI_UINT32 mcd) { _VL_VPI_UNIMP(); return 0; } PLI_INT32 vpi_mcd_printf(PLI_UINT32 mcd, PLI_BYTE8 *formatp, ...) { VerilatedVpiImp::assertOneCheck(); _VL_VPI_ERROR_RESET(); va_list ap; va_start(ap, formatp); int chars = vpi_mcd_vprintf(mcd, formatp, ap); va_end(ap); return chars; } PLI_INT32 vpi_printf(PLI_BYTE8 *formatp, ...) { VerilatedVpiImp::assertOneCheck(); _VL_VPI_ERROR_RESET(); va_list ap; va_start(ap, formatp); int chars = vpi_vprintf(formatp, ap); va_end(ap); return chars; } PLI_INT32 vpi_vprintf(PLI_BYTE8* formatp, va_list ap) { VerilatedVpiImp::assertOneCheck(); _VL_VPI_ERROR_RESET(); return VL_VPRINTF(formatp, ap); } PLI_INT32 vpi_mcd_vprintf(PLI_UINT32 mcd, PLI_BYTE8 *format, va_list ap) { VerilatedVpiImp::assertOneCheck(); FILE* fp = VL_CVT_I_FP(mcd); _VL_VPI_ERROR_RESET(); // cppcheck-suppress nullPointer if (VL_UNLIKELY(!fp)) return 0; int chars = vfprintf(fp, format, ap); return chars; } PLI_INT32 vpi_flush(void) { VerilatedVpiImp::assertOneCheck(); _VL_VPI_ERROR_RESET(); Verilated::flushCall(); return 0; } PLI_INT32 vpi_mcd_flush(PLI_UINT32 mcd) { VerilatedVpiImp::assertOneCheck(); FILE* fp = VL_CVT_I_FP(mcd); _VL_VPI_ERROR_RESET(); if (VL_UNLIKELY(!fp)) return 1; fflush(fp); return 0; } // utility routines PLI_INT32 vpi_compare_objects(vpiHandle object1, vpiHandle object2) { _VL_VPI_UNIMP(); return 0; } PLI_INT32 vpi_chk_error(p_vpi_error_info error_info_p) { // executing vpi_chk_error does not reset error // error_info_p can be NULL, so only return level in that case VerilatedVpiImp::assertOneCheck(); p_vpi_error_info _error_info_p = VerilatedVpiImp::error_info()->getError(); if (error_info_p && _error_info_p) { *error_info_p = *_error_info_p; } if (!_error_info_p) return 0; // no error occured return _error_info_p->level; // return error severity level } PLI_INT32 vpi_free_object(vpiHandle object) { VerilatedVpiImp::assertOneCheck(); _VL_VPI_ERROR_RESET(); return vpi_release_handle(object); // Deprecated } PLI_INT32 vpi_release_handle(vpiHandle object) { VL_DEBUG_IF_PLI(VL_DBG_MSGF("- vpi: vpi_release_handle %p\n", object);); VerilatedVpiImp::assertOneCheck(); VerilatedVpio* vop = VerilatedVpio::castp(object); _VL_VPI_ERROR_RESET(); if (VL_UNLIKELY(!vop)) return 0; vpi_remove_cb(object); // May not be a callback, but that's ok VL_DO_DANGLING(delete vop, vop); return 1; } PLI_INT32 vpi_get_vlog_info(p_vpi_vlog_info vlog_info_p) VL_MT_SAFE { VerilatedVpiImp::assertOneCheck(); _VL_VPI_ERROR_RESET(); vlog_info_p->argc = Verilated::getCommandArgs()->argc; vlog_info_p->argv = (PLI_BYTE8**)Verilated::getCommandArgs()->argv; vlog_info_p->product = (PLI_BYTE8*)Verilated::productName(); vlog_info_p->version = (PLI_BYTE8*)Verilated::productVersion(); return 1; } // routines added with 1364-2001 PLI_INT32 vpi_get_data(PLI_INT32 id, PLI_BYTE8 *dataLoc, PLI_INT32 numOfBytes) { _VL_VPI_UNIMP(); return 0; } PLI_INT32 vpi_put_data(PLI_INT32 id, PLI_BYTE8 *dataLoc, PLI_INT32 numOfBytes) { _VL_VPI_UNIMP(); return 0; } void *vpi_get_userdata(vpiHandle obj) { _VL_VPI_UNIMP(); return 0; } PLI_INT32 vpi_put_userdata(vpiHandle obj, void *userdata) { _VL_VPI_UNIMP(); return 0; } PLI_INT32 vpi_control(PLI_INT32 operation, ...) { VL_DEBUG_IF_PLI(VL_DBG_MSGF("- vpi: vpi_control %d\n", operation);); VerilatedVpiImp::assertOneCheck(); _VL_VPI_ERROR_RESET(); switch (operation) { case vpiFinish: { VL_FINISH_MT(__FILE__, __LINE__, "*VPI*"); return 1; } case vpiStop: { VL_STOP_MT(__FILE__, __LINE__, "*VPI*"); return 1; } } _VL_VPI_WARNING(__FILE__, __LINE__, "%s: Unsupported type %s, ignoring", VL_FUNC, VerilatedVpiError::strFromVpiProp(operation)); return 0; } vpiHandle vpi_handle_by_multi_index(vpiHandle obj, PLI_INT32 num_index, PLI_INT32 *index_array) { _VL_VPI_UNIMP(); return 0; } <|start_filename|>basic/lesson3/verilator/sim/sim_input.h<|end_filename|> #pragma once #ifndef _MSC_VER #else #define WIN32 #pragma comment(lib, "dinput8.lib") #pragma comment(lib, "dxguid.lib") #endif #include <vector> struct SimInput { public: int inputCount = 0; bool inputs[16]; int mappings[16]; void Read(); int Initialise(); void CleanUp(); void SetMapping(int index, int code); SimInput(int count); ~SimInput(); }; <|start_filename|>basic/lesson3/verilator/sim_main.cpp<|end_filename|> #include <verilated.h> #include "Vtop.h" #include "imgui.h" #ifndef _MSC_VER #include <stdio.h> #include <SDL.h> #include <SDL_opengl.h> #else #define WIN32 #include <dinput.h> #endif #include "sim_console.h" #include "sim_bus.h" #include "sim_video.h" #include "sim_input.h" #include "sim_clock.h" #include "../imgui/imgui_memory_editor.h" // Debug GUI // --------- const char* windowTitle = "Verilator Sim: Lesson3"; bool showDebugWindow = true; const char* debugWindowTitle = "Virtual Dev Board v1.0"; DebugConsole console; MemoryEditor mem_edit_1; MemoryEditor mem_edit_2; MemoryEditor mem_edit_3; // HPS emulator // ------------ SimBus bus(console); // Input handling // -------------- SimInput input(12); const int input_right = 0; const int input_left = 1; const int input_down = 2; const int input_up = 3; const int input_fire1 = 4; const int input_fire2 = 5; const int input_start_1 = 6; const int input_start_2 = 7; const int input_coin_1 = 8; const int input_coin_2 = 9; const int input_coin_3 = 10; const int input_pause = 11; // Video // ----- #define VGA_WIDTH 640 #define VGA_HEIGHT 400 #define VGA_ROTATE 0 // 90 degrees anti-clockwise SimVideo video(VGA_WIDTH, VGA_HEIGHT, VGA_ROTATE); // Simulation control // ------------------ int initialReset = 48; bool run_enable = 1; int batchSize = 25000000 / 100; bool single_step = 0; bool multi_step = 0; int multi_step_amount = 1024; // Verilog module // -------------- Vtop* top = NULL; vluint64_t main_time = 0; // Current simulation time. double sc_time_stamp() { // Called by $time in Verilog. return main_time; } int clockSpeed = 24; // This is not used, just a reminder for the dividers below SimClock clk_sys(1); // 12mhz SimClock clk_pix(1); // 6mhz void resetSim() { main_time = 0; top->reset = 1; clk_sys.Reset(); clk_pix.Reset(); } int verilate() { if (!Verilated::gotFinish()) { // Assert reset during startup if (main_time < initialReset) { top->reset = 1; } // Deassert reset after startup if (main_time == initialReset) { top->reset = 0; } // Clock dividers clk_sys.Tick(); clk_pix.Tick(); // Set system clock in core top->clk_sys = clk_sys.clk; top->clk_vid = clk_pix.clk; // Output pixels on rising edge of pixel clock if (clk_pix.clk && !clk_pix.old) { uint32_t colour = 0xFF000000 | top->VGA_B << 16 | top->VGA_G << 8 | top->VGA_R; video.Clock(top->VGA_HB, top->VGA_VB, colour); } // Simulate both edges of system clock if (clk_sys.clk != clk_sys.old) { if (clk_sys.clk) { bus.BeforeEval(); } top->eval(); if (clk_sys.clk) { bus.AfterEval(); } } main_time++; return 1; } // Stop verilating and cleanup top->final(); delete top; exit(0); return 0; } int main(int argc, char** argv, char** env) { // Create core and initialise top = new Vtop(); Verilated::commandArgs(argc, argv); #ifdef WIN32 // Attach debug console to the verilated code Verilated::setDebug(console); #endif // Attach bus bus.ioctl_addr = &top->ioctl_addr; bus.ioctl_index = &top->ioctl_index; bus.ioctl_wait = &top->ioctl_wait; bus.ioctl_download = &top->ioctl_download; //bus.ioctl_upload = &top->ioctl_upload; bus.ioctl_wr = &top->ioctl_wr; bus.ioctl_dout = &top->ioctl_dout; //bus.ioctl_din = &top->ioctl_din; // Set up input module input.Initialise(); #ifdef WIN32 input.SetMapping(input_up, DIK_UP); input.SetMapping(input_right, DIK_RIGHT); input.SetMapping(input_down, DIK_DOWN); input.SetMapping(input_left, DIK_LEFT); input.SetMapping(input_fire1, DIK_SPACE); input.SetMapping(input_start_1, DIK_1); input.SetMapping(input_start_2, DIK_2); input.SetMapping(input_coin_1, DIK_5); input.SetMapping(input_coin_2, DIK_6); input.SetMapping(input_coin_3, DIK_7); input.SetMapping(input_pause, DIK_P); #else input.SetMapping(input_up, SDL_SCANCODE_UP); input.SetMapping(input_right, SDL_SCANCODE_RIGHT); input.SetMapping(input_down, SDL_SCANCODE_DOWN); input.SetMapping(input_left, SDL_SCANCODE_LEFT); input.SetMapping(input_fire1, SDL_SCANCODE_SPACE); input.SetMapping(input_start_1, SDL_SCANCODE_1); input.SetMapping(input_start_2, SDL_SCANCODE_2); input.SetMapping(input_coin_1, SDL_SCANCODE_3); input.SetMapping(input_coin_2, SDL_SCANCODE_4); input.SetMapping(input_coin_3, SDL_SCANCODE_5); input.SetMapping(input_pause, SDL_SCANCODE_P); #endif // Setup video output if (video.Initialise(windowTitle) == 1) { return 1; } //bus.QueueDownload("bird.bin", 0); #ifdef WIN32 MSG msg; ZeroMemory(&msg, sizeof(msg)); while (msg.message != WM_QUIT) { if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); continue; } #else bool done = false; while (!done) { SDL_Event event; while (SDL_PollEvent(&event)) { ImGui_ImplSDL2_ProcessEvent(&event); if (event.type == SDL_QUIT) done = true; } #endif video.StartFrame(); input.Read(); // Draw GUI // -------- ImGui::NewFrame(); console.Draw("Debug Log", &showDebugWindow); ImGui::Begin(debugWindowTitle); ImGui::SetWindowPos(debugWindowTitle, ImVec2(580, 10), ImGuiCond_Once); ImGui::SetWindowSize(debugWindowTitle, ImVec2(1000, 1000), ImGuiCond_Once); if (ImGui::Button("RESET")) { resetSim(); } ImGui::SameLine(); if (ImGui::Button("START")) { run_enable = 1; } ImGui::SameLine(); if (ImGui::Button("STOP")) { run_enable = 0; } ImGui::SameLine(); ImGui::Checkbox("RUN", &run_enable); ImGui::SliderInt("Batch size", &batchSize, 1, 1000000); if (single_step == 1) { single_step = 0; } if (ImGui::Button("Single Step")) { run_enable = 0; single_step = 1; } ImGui::SameLine(); if (multi_step == 1) { multi_step = 0; } if (ImGui::Button("Multi Step")) { run_enable = 0; multi_step = 1; } ImGui::SameLine(); ImGui::SliderInt("Step amount", &multi_step_amount, 8, 1024); ImGui::SliderInt("Rotate", &video.output_rotate, -1, 1); ImGui::SameLine(); ImGui::Checkbox("Flip V", &video.output_vflip); ImGui::Text("main_time: %d frame_count: %d sim FPS: %f", main_time, video.count_frame, video.stats_fps); // Draw VGA output float m = 1.0; ImGui::Image(video.texture_id, ImVec2(video.output_width * m, video.output_height * m)); ImGui::End(); ImGui::Begin("ROM Editor"); //mem_edit_1.DrawContents(top->top__DOT__soc__DOT__vga__DOT__vmem__DOT__mem, 16384, 0); mem_edit_1.DrawContents(top->top__DOT__soc__DOT__rom__DOT__mem, 4096, 0); ImGui::End(); ImGui::Begin("RAM Editor"); //mem_edit_1.DrawContents(top->top__DOT__soc__DOT__vga__DOT__vmem__DOT__mem, 16384, 0); mem_edit_2.DrawContents(top->top__DOT__soc__DOT__ram__DOT__mem, 4096, 0); ImGui::End(); ImGui::Begin("VRAM Editor"); //mem_edit_1.DrawContents(top->top__DOT__soc__DOT__vga__DOT__vmem__DOT__mem, 16384, 0); mem_edit_3.DrawContents(top->top__DOT__soc__DOT__vga__DOT__vmem, 16000, 0); ImGui::End(); ImGui::Begin("CPU Registers"); ImGui::Spacing(); ImGui::Text("PC 0x%04X", top->top__DOT__soc__DOT__T80x__DOT__i_tv80_core__DOT__PC); ImGui::Text("ACC 0x%04X", top->top__DOT__soc__DOT__T80x__DOT__i_tv80_core__DOT__ACC); ImGui::Text("Main Registers"); /* ImGui::Text("B 0x%02X", top->top__DOT__soc__DOT__T80x__DOT__i_tv80_core__DOT__i_reg__DOT__B); ImGui::Text("C 0x%02X", top->top__DOT__soc__DOT__T80x__DOT__i_tv80_core__DOT__i_reg__DOT__C); ImGui::Text("D 0x%02X", top->top__DOT__soc__DOT__T80x__DOT__i_tv80_core__DOT__i_reg__DOT__D); ImGui::Text("E 0x%02X", top->top__DOT__soc__DOT__T80x__DOT__i_tv80_core__DOT__i_reg__DOT__E); ImGui::Text("H 0x%02X", top->top__DOT__soc__DOT__T80x__DOT__i_tv80_core__DOT__i_reg__DOT__H); ImGui::Text("L 0x%02X", top->top__DOT__soc__DOT__T80x__DOT__i_tv80_core__DOT__i_reg__DOT__L); */ ImGui::Spacing(); ImGui::Separator(); ImGui::Text("16 bit Registers"); /* ImGui::Text("IX 0x%04X", top->top__DOT__soc__DOT__T80x__DOT__i_tv80_core__DOT__i_reg__DOT__IX); ImGui::Text("IY 0x%04X", top->top__DOT__soc__DOT__T80x__DOT__i_tv80_core__DOT__i_reg__DOT__IY); ImGui::Text("SP 0x%04X", top->top__DOT__soc__DOT__T80x__DOT__i_tv80_core__DOT__SP); */ ImGui::Text("PC 0x%04X", top->top__DOT__soc__DOT__T80x__DOT__i_tv80_core__DOT__PC); ImGui::End(); video.UpdateTexture(); // Pass inputs to sim //top->inputs = 0; for (int i = 0; i < input.inputCount; i++) { //if (input.inputs[i]) { top->inputs |= (1 << i); } } // Run simulation if (run_enable) { for (int step = 0; step < batchSize; step++) { verilate(); } } else { if (single_step) { verilate(); } if (multi_step) { for (int step = 0; step < multi_step_amount; step++) { verilate(); } } } } // Clean up before exit // -------------------- video.CleanUp(); input.CleanUp(); return 0; } <|start_filename|>basic/lesson8/mmc.c<|end_filename|> /*------------------------------------------------------------------------/ / Bitbanging MMCv3/SDv1/SDv2 (in SPI mode) control module for PFF / Modified to support the Z80 SoC hardware spi interface /-------------------------------------------------------------------------/ / / Copyright (C) 2014, ChaN, all right reserved. / / * This software is a free software and there is NO WARRANTY. / * No restriction on use. You can use, modify and redistribute it for / personal, non-profit or commercial products UNDER YOUR RESPONSIBILITY. / * Redistributions of source code must retain the above copyright notice. / /--------------------------------------------------------------------------/ */ #include "diskio.h" static unsigned char buffer[512]; static DWORD buffer_sector = 0xffffffff; // SPI data is read and written via port 0. Writing to the port starts a spi transfer, // reading the port returns the last byte received during a transfer but doesn't start // a transfer by itself __sfr __at 0x00 DataPort; // SPI control port is a single write only port bit used for spi select (ss) __sfr __at 0x01 ControlPort; void dly_us(unsigned int n) { while(n--) {}; } void forward(BYTE n) { } /*-------------------------------------------------------------------------*/ /* Platform dependent macros and functions needed to be modified */ /*-------------------------------------------------------------------------*/ #define INIT_PORT() init_port() /* Initialize MMC control port (CS/CLK/DI:output, DO:input) */ #define DLY_US(n) dly_us(n) /* Delay n microseconds */ #define FORWARD(d) forward(d) /* Data in-time processing function (depends on the project) */ #define CS_H() ControlPort=1 /* Set MMC CS "high" */ #define CS_L() ControlPort=0 /* Set MMC CS "low" */ /*-------------------------------------------------------------------------- Module Private Functions ---------------------------------------------------------------------------*/ /* Definitions for MMC/SDC command */ #define CMD0 (0x40+0) /* GO_IDLE_STATE */ #define CMD1 (0x40+1) /* SEND_OP_COND (MMC) */ #define ACMD41 (0xC0+41) /* SEND_OP_COND (SDC) */ #define CMD8 (0x40+8) /* SEND_IF_COND */ #define CMD16 (0x40+16) /* SET_BLOCKLEN */ #define CMD17 (0x40+17) /* READ_SINGLE_BLOCK */ #define CMD24 (0x40+24) /* WRITE_BLOCK */ #define CMD55 (0x40+55) /* APP_CMD */ #define CMD58 (0x40+58) /* READ_OCR */ /* Card type flags (CardType) */ #define CT_MMC 0x01 /* MMC ver 3 */ #define CT_SD1 0x02 /* SD ver 1 */ #define CT_SD2 0x04 /* SD ver 2 */ #define CT_SDC (CT_SD1|CT_SD2) /* SD */ #define CT_BLOCK 0x08 /* Block addressing */ static BYTE CardType; /* b0:MMC, b1:SDv1, b2:SDv2, b3:Block addressing */ /*-----------------------------------------------------------------------*/ /* Transmit a byte to the MMC via SPI */ /*-----------------------------------------------------------------------*/ #define XMIT_MMC(a) DataPort=a /*-----------------------------------------------------------------------*/ /* Receive a byte from the MMC (bitbanging) */ /*-----------------------------------------------------------------------*/ static BYTE rcvr_mmc (void) { DataPort = 0xff; // some additional delay to give spi transmitter some // time to finish __asm nop nop __endasm; return DataPort; } /*-----------------------------------------------------------------------*/ /* Skip bytes on the MMC (bitbanging) */ /*-----------------------------------------------------------------------*/ static void skip_mmc ( UINT n /* Number of bytes to skip */ ) { do { DataPort = 0xff; } while (--n); } /*-----------------------------------------------------------------------*/ /* Deselect the card and release SPI bus */ /*-----------------------------------------------------------------------*/ static void release_spi (void) { CS_H(); rcvr_mmc(); } /*-----------------------------------------------------------------------*/ /* Send a command packet to MMC */ /*-----------------------------------------------------------------------*/ static BYTE send_cmd ( BYTE cmd, /* Command byte */ DWORD arg /* Argument */ ) { BYTE n, res; if (cmd & 0x80) { /* ACMD<n> is the command sequense of CMD55-CMD<n> */ cmd &= 0x7F; res = send_cmd(CMD55, 0); if (res > 1) return res; } /* Select the card */ CS_H(); rcvr_mmc(); CS_L(); rcvr_mmc(); /* Send a command packet */ XMIT_MMC(cmd); /* Start + Command index */ XMIT_MMC((BYTE)(arg >> 24)); /* Argument[31..24] */ XMIT_MMC((BYTE)(arg >> 16)); /* Argument[23..16] */ XMIT_MMC((BYTE)(arg >> 8)); /* Argument[15..8] */ XMIT_MMC((BYTE)arg); /* Argument[7..0] */ n = 0x01; /* Dummy CRC + Stop */ if (cmd == CMD0) n = 0x95; /* Valid CRC for CMD0(0) */ if (cmd == CMD8) n = 0x87; /* Valid CRC for CMD8(0x1AA) */ XMIT_MMC(n); /* Receive a command response */ n = 10; /* Wait for a valid response in timeout of 10 attempts */ do { res = rcvr_mmc(); } while ((res & 0x80) && --n); return res; /* Return with the response value */ } /*-------------------------------------------------------------------------- Public Functions ---------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------*/ /* Initialize Disk Drive */ /*-----------------------------------------------------------------------*/ DSTATUS disk_initialize (void) { BYTE n, cmd, ty, buf[4]; UINT tmr; CS_H(); skip_mmc(10); /* Dummy clocks */ ty = 0; if (send_cmd(CMD0, 0) == 1) { /* Enter Idle state */ if (send_cmd(CMD8, 0x1AA) == 1) { /* SDv2 */ for (n = 0; n < 4; n++) buf[n] = rcvr_mmc(); /* Get trailing return value of R7 resp */ if (buf[2] == 0x01 && buf[3] == 0xAA) { /* The card can work at vdd range of 2.7-3.6V */ for (tmr = 1000; tmr; tmr--) { /* Wait for leaving idle state (ACMD41 with HCS bit) */ if (send_cmd(ACMD41, 1UL << 30) == 0) break; DLY_US(1000); } if (tmr && send_cmd(CMD58, 0) == 0) { /* Check CCS bit in the OCR */ for (n = 0; n < 4; n++) buf[n] = rcvr_mmc(); ty = (buf[0] & 0x40) ? CT_SD2 | CT_BLOCK : CT_SD2; /* SDv2 (HC or SC) */ } } } else { /* SDv1 or MMCv3 */ if (send_cmd(ACMD41, 0) <= 1) { ty = CT_SD1; cmd = ACMD41; /* SDv1 */ } else { ty = CT_MMC; cmd = CMD1; /* MMCv3 */ } for (tmr = 1000; tmr; tmr--) { /* Wait for leaving idle state */ if (send_cmd(cmd, 0) == 0) break; DLY_US(1000); } if (!tmr || send_cmd(CMD16, 512) != 0) /* Set R/W block length to 512 */ ty = 0; } } CardType = ty; release_spi(); return ty ? 0 : STA_NOINIT; } /*-----------------------------------------------------------------------*/ /* Read partial sector */ /*-----------------------------------------------------------------------*/ DRESULT disk_readp ( BYTE *buff, /* Pointer to the read buffer (NULL:Read bytes are forwarded to the stream) */ DWORD sector, /* Sector number (LBA) */ UINT offset, /* Byte offset to read from (0..511) */ UINT count /* Number of bytes to read (ofs + cnt mus be <= 512) */ ) { BYTE *buff_sec = buffer; DRESULT res; BYTE d; UINT bc, tmr; if (!(CardType & CT_BLOCK)) sector *= 512; /* Convert to byte address if needed */ // check if sector is already in sector buffer if(buffer_sector == sector) { buff_sec += offset; // skip to requested bytes while(count--) *buff++ = *buff_sec++; return RES_OK; } res = RES_ERROR; if (send_cmd(CMD17, sector) == 0) { /* READ_SINGLE_BLOCK */ tmr = 1000; do { /* Wait for data packet in timeout of 100ms */ DLY_US(100); d = rcvr_mmc(); } while (d == 0xFF && --tmr); if (d == 0xFE) { /* A data packet arrived */ // if the whole sector is being read we assume that it // will not be needed again and we won't cache it if((!offset) && (count == 512)) { BYTE c; for(c=0;c<64;c++) { *buff++ = rcvr_mmc(); *buff++ = rcvr_mmc(); *buff++ = rcvr_mmc(); *buff++ = rcvr_mmc(); *buff++ = rcvr_mmc(); *buff++ = rcvr_mmc(); *buff++ = rcvr_mmc(); *buff++ = rcvr_mmc(); } skip_mmc(2); } else { bc = 512 - offset - count; /* Skip leading bytes (store in buffer only) */ while(offset--) *buff_sec++ = rcvr_mmc(); /* Receive a part of the sector */ if (buff) { /* Store data to the memory */ do *buff_sec++ = *buff++ = rcvr_mmc(); while (--count); } else { /* Forward data to the outgoing stream */ do { *buff_sec++ = d = rcvr_mmc(); FORWARD(d); } while (--count); } /* Skip trailing bytes (store in buffer only) */ while(bc--) *buff_sec++ = rcvr_mmc(); /* and skip crc */ skip_mmc(2); buffer_sector = sector; } res = RES_OK; } } release_spi(); return res; } <|start_filename|>basic/lesson3/verilator/sim/vinc/verilated_heavy.h<|end_filename|> // -*- mode: C++; c-file-style: "cc-mode" -*- //************************************************************************* // // Copyright 2010-2020 by <NAME>. This program is free software; you can // redistribute it and/or modify it under the terms of either the GNU // Lesser General Public License Version 3 or the Perl Artistic License. // Version 2.0. // // Verilator is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // //************************************************************************* /// /// \file /// \brief Verilator: String include for all Verilated C files /// /// This file is included automatically by Verilator at the top of /// all C++ files it generates. It is used when strings or other /// heavyweight types are required; these contents are not part of /// verilated.h to save compile time when such types aren't used. /// /// Code available from: https://verilator.org /// //************************************************************************* #ifndef _VERILATED_HEAVY_H_ #define _VERILATED_HEAVY_H_ 1 ///< Header Guard #include "verilated.h" #include <deque> #include <map> #include <string> //=================================================================== // String formatters (required by below containers) extern std::string VL_TO_STRING(CData obj); extern std::string VL_TO_STRING(SData obj); extern std::string VL_TO_STRING(IData obj); extern std::string VL_TO_STRING(QData obj); inline std::string VL_TO_STRING(const std::string& obj) { return "\"" + obj + "\""; } extern std::string VL_TO_STRING_W(int words, WDataInP obj); //=================================================================== // Readmem/Writemem operation classes class VlReadMem { bool m_hex; // Hex format int m_bits; // Bit width of values const std::string& m_filename; // Filename QData m_end; // End address (as specified by user) FILE* m_fp; // File handle for filename QData m_addr; // Next address to read int m_linenum; // Line number last read from file public: VlReadMem(bool hex, int bits, const std::string& filename, QData start, QData end); ~VlReadMem(); bool isOpen() const { return m_fp != NULL; } int linenum() const { return m_linenum; } bool get(QData& addrr, std::string& valuer); void setData(void* valuep, const std::string& rhs); }; class VlWriteMem { int m_bits; // Bit width of values FILE* m_fp; // File handle for filename QData m_addr; // Next address to write public: VlWriteMem(bool hex, int bits, const std::string& filename, QData start, QData end); ~VlWriteMem(); bool isOpen() const { return m_fp != NULL; } void print(QData addr, bool addrstamp, const void* valuep); }; //=================================================================== // Verilog array container // Similar to std::array<WData, N>, but: // 1. Doesn't require C++11 // 2. Lighter weight, only methods needed by Verilator, to help compile time. // // This is only used when we need an upper-level container and so can't // simply use a C style array (which is just a pointer). template <std::size_t T_Words> class VlWide { WData m_storage[T_Words]; public: // Default constructor/destructor/copy are fine const WData& at(size_t index) const { return m_storage[index]; } WData& at(size_t index) { return m_storage[index]; } WData* data() { return &m_storage[0]; } const WData* data() const { return &m_storage[0]; } bool operator<(const VlWide<T_Words>& rhs) const { return VL_LT_W(T_Words, data(), rhs.data()); } }; // Convert a C array to std::array reference by pointer magic, without copy. // Data type (second argument) is so the function template can automatically generate. template <std::size_t T_Words> VlWide<T_Words>& VL_CVT_W_A(WDataInP inp, const VlWide<T_Words>&) { return *((VlWide<T_Words>*)inp); } template <std::size_t T_Words> std::string VL_TO_STRING(const VlWide<T_Words>& obj) { return VL_TO_STRING_W(T_Words, obj.data()); } //=================================================================== // Verilog associative array container // There are no multithreaded locks on this; the base variable must // be protected by other means // template <class T_Key, class T_Value> class VlAssocArray { private: // TYPES typedef std::map<T_Key, T_Value> Map; public: typedef typename Map::const_iterator const_iterator; private: // MEMBERS Map m_map; // State of the assoc array T_Value m_defaultValue; // Default value public: // CONSTRUCTORS VlAssocArray() { // m_defaultValue isn't defaulted. Caller's constructor must do it. } ~VlAssocArray() {} // Standard copy constructor works. Verilog: assoca = assocb // METHODS T_Value& atDefault() { return m_defaultValue; } // Size of array. Verilog: function int size(), or int num() int size() const { return m_map.size(); } // Clear array. Verilog: function void delete([input index]) void clear() { m_map.clear(); } void erase(const T_Key& index) { m_map.erase(index); } // Return 0/1 if element exists. Verilog: function int exists(input index) int exists(const T_Key& index) const { return m_map.find(index) != m_map.end(); } // Return first element. Verilog: function int first(ref index); int first(T_Key& indexr) const { typename Map::const_iterator it = m_map.begin(); if (it == m_map.end()) return 0; indexr = it->first; return 1; } // Return last element. Verilog: function int last(ref index) int last(T_Key& indexr) const { typename Map::const_reverse_iterator it = m_map.rbegin(); if (it == m_map.rend()) return 0; indexr = it->first; return 1; } // Return next element. Verilog: function int next(ref index) int next(T_Key& indexr) const { typename Map::const_iterator it = m_map.find(indexr); if (VL_UNLIKELY(it == m_map.end())) return 0; it++; if (VL_UNLIKELY(it == m_map.end())) return 0; indexr = it->first; return 1; } // Return prev element. Verilog: function int prev(ref index) int prev(T_Key& indexr) const { typename Map::const_iterator it = m_map.find(indexr); if (VL_UNLIKELY(it == m_map.end())) return 0; if (VL_UNLIKELY(it == m_map.begin())) return 0; --it; indexr = it->first; return 1; } // Setting. Verilog: assoc[index] = v // Can't just overload operator[] or provide a "at" reference to set, // because we need to be able to insert only when the value is set T_Value& at(const T_Key& index) { typename Map::iterator it = m_map.find(index); if (it == m_map.end()) { std::pair<typename Map::iterator, bool> pit = m_map.insert(std::make_pair(index, m_defaultValue)); return pit.first->second; } return it->second; } // Accessing. Verilog: v = assoc[index] const T_Value& at(const T_Key& index) const { typename Map::iterator it = m_map.find(index); if (it == m_map.end()) return m_defaultValue; else return it->second; } // For save/restore const_iterator begin() const { return m_map.begin(); } const_iterator end() const { return m_map.end(); } // Dumping. Verilog: str = $sformatf("%p", assoc) std::string to_string() const { std::string out = "'{"; std::string comma; for (typename Map::const_iterator it = m_map.begin(); it != m_map.end(); ++it) { out += comma + VL_TO_STRING(it->first) + ":" + VL_TO_STRING(it->second); comma = ", "; } // Default not printed - maybe random init data return out + "} "; } }; template <class T_Key, class T_Value> std::string VL_TO_STRING(const VlAssocArray<T_Key, T_Value>& obj) { return obj.to_string(); } template <class T_Key, class T_Value> void VL_READMEM_N(bool hex, int bits, const std::string& filename, VlAssocArray<T_Key, T_Value>& obj, QData start, QData end) VL_MT_SAFE { VlReadMem rmem(hex, bits, filename, start, end); if (VL_UNLIKELY(!rmem.isOpen())) return; while (1) { QData addr; std::string data; if (rmem.get(addr /*ref*/, data /*ref*/)) { rmem.setData(&(obj.at(addr)), data); } else { break; } } } template <class T_Key, class T_Value> void VL_WRITEMEM_N(bool hex, int bits, const std::string& filename, const VlAssocArray<T_Key, T_Value>& obj, QData start, QData end) VL_MT_SAFE { VlWriteMem wmem(hex, bits, filename, start, end); if (VL_UNLIKELY(!wmem.isOpen())) return; for (typename VlAssocArray<T_Key, T_Value>::const_iterator it = obj.begin(); it != obj.end(); ++it) { QData addr = it->first; if (addr >= start && addr <= end) wmem.print(addr, true, &(it->second)); } } //=================================================================== // Verilog queue container // There are no multithreaded locks on this; the base variable must // be protected by other means // // Bound here is the maximum size() allowed, e.g. 1 + SystemVerilog bound template <class T_Value, size_t T_MaxSize = 0> class VlQueue { private: // TYPES typedef std::deque<T_Value> Deque; public: typedef typename Deque::const_iterator const_iterator; private: // MEMBERS Deque m_deque; // State of the assoc array T_Value m_defaultValue; // Default value public: // CONSTRUCTORS VlQueue() { // m_defaultValue isn't defaulted. Caller's constructor must do it. } ~VlQueue() {} // Standard copy constructor works. Verilog: assoca = assocb // METHODS T_Value& atDefault() { return m_defaultValue; } // Size. Verilog: function int size(), or int num() int size() const { return m_deque.size(); } // Clear array. Verilog: function void delete([input index]) void clear() { m_deque.clear(); } void erase(size_t index) { if (VL_LIKELY(index < m_deque.size())) m_deque.erase(index); } // function void q.push_front(value) void push_front(const T_Value& value) { m_deque.push_front(value); if (VL_UNLIKELY(T_MaxSize != 0 && m_deque.size() > T_MaxSize)) m_deque.pop_back(); } // function void q.push_back(value) void push_back(const T_Value& value) { if (VL_LIKELY(T_MaxSize == 0 || m_deque.size() < T_MaxSize)) m_deque.push_back(value); } // function value_t q.pop_front(); T_Value pop_front() { if (m_deque.empty()) return m_defaultValue; T_Value v = m_deque.front(); m_deque.pop_front(); return v; } // function value_t q.pop_back(); T_Value pop_back() { if (m_deque.empty()) return m_defaultValue; T_Value v = m_deque.back(); m_deque.pop_back(); return v; } // Setting. Verilog: assoc[index] = v // Can't just overload operator[] or provide a "at" reference to set, // because we need to be able to insert only when the value is set T_Value& at(size_t index) { static T_Value s_throwAway; if (VL_UNLIKELY(index >= m_deque.size())) { s_throwAway = atDefault(); return s_throwAway; } else return m_deque[index]; } // Accessing. Verilog: v = assoc[index] const T_Value& at(size_t index) const { static T_Value s_throwAway; if (VL_UNLIKELY(index >= m_deque.size())) return atDefault(); else return m_deque[index]; } // function void q.insert(index, value); void insert(size_t index, const T_Value& value) { if (VL_UNLIKELY(index >= m_deque.size())) return; m_deque[index] = value; } // For save/restore const_iterator begin() const { return m_deque.begin(); } const_iterator end() const { return m_deque.end(); } // Dumping. Verilog: str = $sformatf("%p", assoc) std::string to_string() const { std::string out = "'{"; std::string comma; for (typename Deque::const_iterator it = m_deque.begin(); it != m_deque.end(); ++it) { out += comma + VL_TO_STRING(*it); comma = ", "; } return out + "} "; } }; template <class T_Value> std::string VL_TO_STRING(const VlQueue<T_Value>& obj) { return obj.to_string(); } //====================================================================== // Conversion functions extern std::string VL_CVT_PACK_STR_NW(int lwords, WDataInP lwp) VL_MT_SAFE; inline std::string VL_CVT_PACK_STR_NQ(QData lhs) VL_PURE { WData lw[VL_WQ_WORDS_E]; VL_SET_WQ(lw, lhs); return VL_CVT_PACK_STR_NW(VL_WQ_WORDS_E, lw); } inline std::string VL_CVT_PACK_STR_NN(const std::string& lhs) VL_PURE { return lhs; } inline std::string VL_CVT_PACK_STR_NI(IData lhs) VL_PURE { WData lw[VL_WQ_WORDS_E]; VL_SET_WI(lw, lhs); return VL_CVT_PACK_STR_NW(1, lw); } inline std::string VL_CONCATN_NNN(const std::string& lhs, const std::string& rhs) VL_PURE { return lhs + rhs; } inline std::string VL_REPLICATEN_NNQ(int,int,int, const std::string& lhs, IData rep) VL_PURE { std::string out; out.reserve(lhs.length() * rep); for (unsigned times=0; times<rep; ++times) out += lhs; return out; } inline std::string VL_REPLICATEN_NNI(int obits,int lbits,int rbits, const std::string& lhs, IData rep) VL_PURE { return VL_REPLICATEN_NNQ(obits, lbits, rbits, lhs, rep); } inline IData VL_LEN_IN(const std::string& ld) { return ld.length(); } extern std::string VL_TOLOWER_NN(const std::string& ld); extern std::string VL_TOUPPER_NN(const std::string& ld); extern IData VL_FOPEN_NI(const std::string& filename, IData mode) VL_MT_SAFE; extern void VL_READMEM_N(bool hex, int bits, QData depth, int array_lsb, const std::string& filename, void* memp, QData start, QData end) VL_MT_SAFE; extern void VL_WRITEMEM_N(bool hex, int bits, QData depth, int array_lsb, const std::string& filename, const void* memp, QData start, QData end) VL_MT_SAFE; extern IData VL_SSCANF_INX(int lbits, const std::string& ld, const char* formatp, ...) VL_MT_SAFE; extern void VL_SFORMAT_X(int obits_ignored, std::string& output, const char* formatp, ...) VL_MT_SAFE; extern std::string VL_SFORMATF_NX(const char* formatp, ...) VL_MT_SAFE; extern IData VL_VALUEPLUSARGS_INW(int rbits, const std::string& ld, WDataOutP rwp) VL_MT_SAFE; inline IData VL_VALUEPLUSARGS_INI(int rbits, const std::string& ld, CData& rdr) VL_MT_SAFE { WData rwp[2]; // WData must always be at least 2 IData got = VL_VALUEPLUSARGS_INW(rbits, ld, rwp); if (got) rdr = rwp[0]; return got; } inline IData VL_VALUEPLUSARGS_INI(int rbits, const std::string& ld, SData& rdr) VL_MT_SAFE { WData rwp[2]; // WData must always be at least 2 IData got = VL_VALUEPLUSARGS_INW(rbits, ld, rwp); if (got) rdr = rwp[0]; return got; } inline IData VL_VALUEPLUSARGS_INI(int rbits, const std::string& ld, IData& rdr) VL_MT_SAFE { WData rwp[2]; IData got = VL_VALUEPLUSARGS_INW(rbits, ld, rwp); if (got) rdr = rwp[0]; return got; } inline IData VL_VALUEPLUSARGS_INQ(int rbits, const std::string& ld, QData& rdr) VL_MT_SAFE { WData rwp[2]; IData got = VL_VALUEPLUSARGS_INW(rbits, ld, rwp); if (got) rdr = VL_SET_QW(rwp); return got; } inline IData VL_VALUEPLUSARGS_INQ(int rbits, const std::string& ld, double& rdr) VL_MT_SAFE { WData rwp[2]; IData got = VL_VALUEPLUSARGS_INW(rbits, ld, rwp); if (got) rdr = VL_CVT_D_Q(VL_SET_QW(rwp)); return got; } extern IData VL_VALUEPLUSARGS_INN(int, const std::string& ld, std::string& rdr) VL_MT_SAFE; //====================================================================== // Strings extern std::string VL_PUTC_N(const std::string& lhs, IData rhs, CData ths) VL_PURE; extern CData VL_GETC_N(const std::string& lhs, IData rhs) VL_PURE; extern std::string VL_SUBSTR_N(const std::string& lhs, IData rhs, IData ths) VL_PURE; inline IData VL_CMP_NN(const std::string& lhs, const std::string& rhs, bool ignoreCase) VL_PURE { // SystemVerilog does not allow a string variable to contain '\0'. // So C functions such as strcmp() can correctly compare strings. int result; if (ignoreCase) { result = VL_STRCASECMP(lhs.c_str(), rhs.c_str()); } else { result = std::strcmp(lhs.c_str(), rhs.c_str()); } return result; } extern IData VL_ATOI_N(const std::string& str, int base) VL_PURE; #endif // Guard <|start_filename|>basic/lesson3/verilator/sim/vinc/verilated_fst_c.cpp<|end_filename|> // -*- mode: C++; c-file-style: "cc-mode" -*- //============================================================================= // // THIS MODULE IS PUBLICLY LICENSED // // Copyright 2001-2020 by <NAME>. This program is free software; // you can redistribute it and/or modify it under the terms of either the GNU // Lesser General Public License Version 3 or the Perl Artistic License Version 2.0. // // This is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // //============================================================================= /// /// \file /// \brief C++ Tracing in FST Format /// //============================================================================= // SPDIFF_OFF #define __STDC_LIMIT_MACROS // UINT64_MAX #include "verilatedos.h" #include "verilated.h" #include "verilated_fst_c.h" // GTKWave configuration #ifdef VL_TRACE_THREADED # define HAVE_LIBPTHREAD # define FST_WRITER_PARALLEL #endif // Include the GTKWave implementation directly #define FST_CONFIG_INCLUDE "fst_config.h" #include "gtkwave/fastlz.c" #include "gtkwave/fstapi.c" #include "gtkwave/lz4.c" #include <algorithm> #include <cerrno> #include <ctime> #include <fcntl.h> #include <iterator> #include <sstream> #include <sys/stat.h> #if defined(_WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__) # include <io.h> #else # include <stdint.h> # include <unistd.h> #endif //============================================================================= class VerilatedFstCallInfo { protected: friend class VerilatedFst; VerilatedFstCallback_t m_initcb; ///< Initialization Callback function VerilatedFstCallback_t m_fullcb; ///< Full Dumping Callback function VerilatedFstCallback_t m_changecb; ///< Incremental Dumping Callback function void* m_userthis; ///< Fake "this" for caller vluint32_t m_code; ///< Starting code number // CONSTRUCTORS VerilatedFstCallInfo(VerilatedFstCallback_t icb, VerilatedFstCallback_t fcb, VerilatedFstCallback_t changecb, void* ut, vluint32_t code) : m_initcb(icb), m_fullcb(fcb), m_changecb(changecb), m_userthis(ut), m_code(code) {} ~VerilatedFstCallInfo() {} }; //============================================================================= // VerilatedFst VerilatedFst::VerilatedFst(void* fst) : m_fst(fst), m_fullDump(true), m_scopeEscape('.') { m_valueStrBuffer.reserve(64+1); // Need enough room for quad } void VerilatedFst::open(const char* filename) VL_MT_UNSAFE { m_assertOne.check(); m_fst = fstWriterCreate(filename, 1); fstWriterSetPackType(m_fst, FST_WR_PT_LZ4); #ifdef VL_TRACE_THREADED fstWriterSetParallelMode(m_fst, 1); #endif m_curScope.clear(); for (vluint32_t ent = 0; ent< m_callbacks.size(); ++ent) { VerilatedFstCallInfo* cip = m_callbacks[ent]; cip->m_code = 1; (cip->m_initcb)(this, cip->m_userthis, cip->m_code); } // Clear the scope stack std::list<std::string>::iterator it = m_curScope.begin(); while (it != m_curScope.end()) { fstWriterSetUpscope(m_fst); it = m_curScope.erase(it); } } void VerilatedFst::module(const std::string& name) { m_module = name; } //============================================================================= // Decl void VerilatedFst::declDTypeEnum(int dtypenum, const char* name, vluint32_t elements, unsigned int minValbits, const char** itemNamesp, const char** itemValuesp) { fstEnumHandle enumNum = fstWriterCreateEnumTable(m_fst, name, elements, minValbits, itemNamesp, itemValuesp); m_local2fstdtype[dtypenum] = enumNum; } void VerilatedFst::declSymbol(vluint32_t code, const char* name, int dtypenum, fstVarDir vardir, fstVarType vartype, bool array, int arraynum, vluint32_t len) { std::pair<Code2SymbolType::iterator, bool> p = m_code2symbol.insert(std::make_pair(code, static_cast<fstHandle>(NULL))); std::istringstream nameiss(name); std::istream_iterator<std::string> beg(nameiss), end; std::list<std::string> tokens(beg, end); // Split name std::string symbol_name(tokens.back()); tokens.pop_back(); // Remove symbol name from hierarchy tokens.insert(tokens.begin(), m_module); // Add current module to the hierarchy // Find point where current and new scope diverge std::list<std::string>::iterator cur_it = m_curScope.begin(); std::list<std::string>::iterator new_it = tokens.begin(); while (cur_it != m_curScope.end() && new_it != tokens.end()) { if (*cur_it != *new_it) break; ++cur_it; ++new_it; } // Go back to the common point while (cur_it != m_curScope.end()) { fstWriterSetUpscope(m_fst); cur_it = m_curScope.erase(cur_it); } // Follow the hierarchy of the new variable from the common scope point while (new_it != tokens.end()) { fstWriterSetScope(m_fst, FST_ST_VCD_SCOPE, new_it->c_str(), NULL); m_curScope.push_back(*new_it); new_it = tokens.erase(new_it); } std::stringstream name_ss; name_ss << symbol_name; if (array) name_ss << "(" << arraynum << ")"; std::string name_str = name_ss.str(); if (dtypenum > 0) { fstEnumHandle enumNum = m_local2fstdtype[dtypenum]; fstWriterEmitEnumTableRef(m_fst, enumNum); } if (p.second) { // New p.first->second = fstWriterCreateVar(m_fst, vartype, vardir, len, name_str.c_str(), 0); assert(p.first->second); } else { // Alias fstWriterCreateVar(m_fst, vartype, vardir, len, name_str.c_str(), p.first->second); } } //============================================================================= // Callbacks void VerilatedFst::addCallback( VerilatedFstCallback_t initcb, VerilatedFstCallback_t fullcb, VerilatedFstCallback_t changecb, void* userthis) VL_MT_UNSAFE_ONE { m_assertOne.check(); if (VL_UNLIKELY(isOpen())) { std::string msg = (std::string("Internal: ")+__FILE__+"::"+__FUNCTION__ +" called with already open file"); VL_FATAL_MT(__FILE__, __LINE__, "", msg.c_str()); } VerilatedFstCallInfo* vci = new VerilatedFstCallInfo(initcb, fullcb, changecb, userthis, 1); m_callbacks.push_back(vci); } //============================================================================= // Dumping void VerilatedFst::dump(vluint64_t timeui) { if (!isOpen()) return; if (VL_UNLIKELY(m_fullDump)) { m_fullDump = false; // No need for more full dumps for (vluint32_t ent = 0; ent< m_callbacks.size(); ++ent) { VerilatedFstCallInfo* cip = m_callbacks[ent]; (cip->m_fullcb)(this, cip->m_userthis, cip->m_code); } return; } fstWriterEmitTimeChange(m_fst, timeui); for (vluint32_t ent = 0; ent< m_callbacks.size(); ++ent) { VerilatedFstCallInfo* cip = m_callbacks[ent]; (cip->m_changecb)(this, cip->m_userthis, cip->m_code); } } //******************************************************************** // Local Variables: // End: <|start_filename|>basic/lesson9/Makefile<|end_filename|> SDCC=sdcc CPU=z80 CODE=boot_rom TTY=/dev/ttyUSB0 OBJ=$(CODE).rel font.rel ROM=z80_soc.rom all: $(ROM) bin2c: bin2c.c font.part: font.fnt dd if=$< of=$@ bs=1 count=768 skip=256 font.c: font.part bin2c ./bin2c font.part font.c "unsigned char font[]" %.rel: %.c $(SDCC) -m$(CPU) -c $< $(CODE).ihx: $(OBJ) $(SDCC) -m$(CPU) $(OBJ) %.hex: %.ihx cp $< $@ %.bin: %.hex srec_cat -multiple $< -intel -o $@ -binary $(ROM): $(CODE).bin cp $< $@ disasm: $(CODE).bin z80dasm -a -t -g 0 $< clean: rm -rf *~ *.asm *.ihx *.lk *.lst *.map *.noi *.rel *.sym *.bin bin2c *.part run: $(ROM) stty -F $(TTY) speed 115200 raw -echo timeout 1s cp $(TTY) /dev/null || /bin/true echo "x $< `stat -c%s $<`" > $(TTY) sx $< <$(TTY) >$(TTY) echo "r" > $(TTY) reset: echo "r" > $(TTY) <|start_filename|>basic/lesson3/verilator/sim/sim_input.cpp<|end_filename|> #include "sim_input.h" #include <string> #ifndef _MSC_VER #include <SDL2/SDL.h> const Uint8 *m_keyboardState; #else #define WIN32 #include <dinput.h> //#define DIRECTINPUT_VERSION 0x0800 IDirectInput8* m_directInput; IDirectInputDevice8* m_keyboard; unsigned char m_keyboardState[256]; #endif #include <vector> // - Core inputs //#define VSW1 top->top__DOT__sw1 //#define VSW2 top->top__DOT__sw2 //#define PLAYERINPUT top->top__DOT__playerinput //#define JS top->top__DOT__joystick //void js_assert(int s) { JS &= ~(1 << s); } //void js_deassert(int s) { JS |= 1 << s; } //void playinput_assert(int s) { PLAYERINPUT &= ~(1 << s); } //void playinput_deassert(int s) { PLAYERINPUT |= (1 << s); } bool ReadKeyboard() { #ifdef WIN32 HRESULT result; // Read the keyboard device. result = m_keyboard->GetDeviceState(sizeof(m_keyboardState), (LPVOID)&m_keyboardState); if (FAILED(result)) { // If the keyboard lost focus or was not acquired then try to get control back. if ((result == DIERR_INPUTLOST) || (result == DIERR_NOTACQUIRED)) { m_keyboard->Acquire(); } else { return false; } } #else m_keyboardState= SDL_GetKeyboardState(NULL); #endif return true; } int SimInput::Initialise() { #ifdef WIN32 m_directInput = 0; m_keyboard = 0; HRESULT result; // Initialize the main direct input interface. result = DirectInput8Create(GetModuleHandle(nullptr), DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&m_directInput, NULL); if (FAILED(result)) { return false; } // Initialize the direct input interface for the keyboard. result = m_directInput->CreateDevice(GUID_SysKeyboard, &m_keyboard, NULL); if (FAILED(result)) { return false; } // Set the data format. In this case since it is a keyboard we can use the predefined data format. result = m_keyboard->SetDataFormat(&c_dfDIKeyboard); if (FAILED(result)) { return false; } // Now acquire the keyboard. result = m_keyboard->Acquire(); if (FAILED(result)) { return false; } #endif return 0; } void SimInput::Read() { // Read keyboard state bool pr = ReadKeyboard(); // Collect inputs for (int i = 0; i < inputCount; i++) { #ifdef WIN32 inputs[i] = m_keyboardState[mappings[i]] & 0x80; #else inputs[i] = m_keyboardState[mappings[i]]; #endif } } void SimInput::SetMapping(int index, int code) { printf("index %d code %d\n",index,code); if (code < 256) mappings[index] = code; else mappings[index] = 0; } void SimInput::CleanUp() { #ifdef WIN32 // Release keyboard if (m_keyboard) { m_keyboard->Unacquire(); m_keyboard->Release(); m_keyboard = 0; } // Release direct input if (m_directInput) { m_directInput->Release(); m_directInput = 0; } #endif } SimInput::SimInput(int count) { inputCount = count; } SimInput::~SimInput() { } <|start_filename|>basic/lesson9/boot_rom.c<|end_filename|> // boot_rom.c // Boot ROM for the Z80 system on a chip (SoC) // (c) 2015 <NAME> #include <stdio.h> #include <string.h> #include <stdlib.h> // for abs() extern unsigned char font[]; // the pointer has a mask const unsigned char cursor_data[] = { 0x00, 0xb0, 0xb8, 0x9c, 0xae, 0xb5, 0x1a, 0x0c }; const unsigned char cursor_mask[] = { 0x7c, 0x78, 0x7c, 0x7e, 0x5f, 0x0e, 0x04, 0x00 }; unsigned char cur_x=0, cur_y=0; void putchar(char c) { unsigned char *p; unsigned char *dptr = (unsigned char*)(160*(8*cur_y) + 8*cur_x); char i, j; if(c < 32) { if(c == '\r') cur_x=0; if(c == '\n') { cur_y++; cur_x=0; if(cur_y >= 12) cur_y = 0; } return; } if(c < 0) return; p = font+8*(unsigned char)(c-32); for(i=0;i<8;i++) { unsigned char l = *p++; for(j=0;j<8;j++) { *dptr++ = (l & 0x80)?0xff:0x00; l <<= 1; } dptr += (160-8); } cur_x++; if(cur_x >= 20) { cur_x = 0; cur_y++; if(cur_y >= 12) cur_y = 0; } } void cls(void) { unsigned char i; unsigned char *p = (unsigned char*)0; for(i=0;i<100;i++) { memset(p, 0, 160); p+=160; } cur_x = 0; cur_y = 0; } // draw a pixel // At 160x100 pixel screen size a byte is sufficient to hold the x and // y coordinates- Video memory begins at address 0 and is write only. // The address space is shared with the ROM which is read only. void put_pixel(unsigned char x, unsigned char y, unsigned char color) { *((unsigned char*)(160*y+x)) = color; } // bresenham algorithm to draw a line void draw_line(unsigned char x, unsigned char y, unsigned char x2, unsigned char y2, unsigned char color) { unsigned char longest, shortest, numerator, i; char dx1 = (x<x2)?1:-1; char dy1 = (y<y2)?1:-1; char dx2, dy2; longest = abs(x2 - x); shortest = abs(y2 - y); if(longest<shortest) { longest = abs(y2 - y); shortest = abs(x2 - x); dx2 = 0; dy2 = dy1; } else { dx2 = dx1; dy2 = 0; } numerator = longest/2; for(i=0;i<=longest;i++) { put_pixel(x,y,color) ; if(numerator >= longest-shortest) { numerator += shortest ; numerator -= longest ; x += dx1; y += dy1; } else { numerator += shortest ; x += dx2; y += dy2; } } } // the key registers has two bits: // 0 - <SPACE> // 1 - S // 2 - C __sfr __at 0x20 keys; __sfr __at 0x30 mouse_x_reg; __sfr __at 0x31 mouse_y_reg; __sfr __at 0x32 mouse_but_reg; void main() { int mouse_x=80, mouse_y=50; int last_x = -1, last_y; char i; cls(); // load cursor image into VGA controller for(i=0;i<8;i++) { *(char*)(0x3f00+i) = cursor_data[i]; *(char*)(0x3f08+i) = cursor_mask[i]; } // set cursor hotspot to pixel 1,0 *(unsigned char*)0x3efd = 0x10; // cursor colors *(unsigned char*)0x3efb = 0xda; // bright grey *(unsigned char*)0x3efc = 0x49; // dark grey puts(" << Z80 SoC Paint >>\n"); puts(" <C>lear image\n"); puts(" Hit <Space>"); // wait for bit 0 to show up on key register while(!(keys & 1)); cls(); puts("Paint ..."); // clear mouse registers by reading them i = (char)mouse_x_reg; i = (char)mouse_y_reg; while(1) { // 'C' clears screen if(keys & 4) cls(); mouse_x += (char)mouse_x_reg; mouse_y -= (char)mouse_y_reg; // limit mouse movement if(mouse_x < 0) mouse_x = 0; if(mouse_x > 159) mouse_x = 159; if(mouse_y < 0) mouse_y = 0; if(mouse_y > 99) mouse_y = 99; // set mouse cursor position *(unsigned char*)0x3efe = mouse_x; *(unsigned char*)0x3eff = mouse_y; if(mouse_but_reg & 3) { // left button draws white, right button black and both red unsigned char colors[] = { 0x00, 0xff, 0x00, 0xe0 }; // there is a valid "last" mouse position if(last_x >= 0) draw_line(last_x, last_y, mouse_x, mouse_y, colors[mouse_but_reg]); last_x = mouse_x; last_y = mouse_y; } else last_x = -1; } } <|start_filename|>basic/lesson3/verilator/sim/vinc/verilated_cov.h<|end_filename|> // -*- mode: C++; c-file-style: "cc-mode" -*- //============================================================================= // // THIS MODULE IS PUBLICLY LICENSED // // Copyright 2001-2020 by <NAME>. This program is free software; // you can redistribute it and/or modify it under the terms of either the GNU // Lesser General Public License Version 3 or the Perl Artistic License Version 2.0. // // This is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // //============================================================================= /// /// \file /// \brief Coverage analysis support /// //============================================================================= #ifndef _VERILATED_COV_H_ #define _VERILATED_COV_H_ 1 #include "verilatedos.h" #include <iostream> #include <sstream> #include <string> //============================================================================= /// Conditionally compile coverage code #ifdef VM_COVERAGE # define VL_IF_COVER(stmts) do { stmts ; } while(0) #else # define VL_IF_COVER(stmts) do { if(0) { stmts ; } } while(0) #endif //============================================================================= /// Insert a item for coverage analysis. /// The first argument is a pointer to the count to be dumped. /// The remaining arguments occur in pairs: A string key, and a value. /// The value may be a string, or another type which will be auto-converted to a string. /// /// Some typical keys: /// filename File the recording occurs in. Defaults to __FILE__ /// lineno Line number the recording occurs in. Defaults to __LINE__ /// column Column number (or occurrence# for dup file/lines). Defaults to undef. /// hier Hierarchical name. Defaults to name() /// type Type of coverage. Defaults to "user" /// Other types are 'block', 'fsm', 'toggle'. /// comment Description of the coverage event. Should be set by the user. /// Comments for type==block: 'if', 'else', 'elsif', 'case' /// thresh Threshold to consider fully covered. /// If unspecified, downstream tools will determine it. /// /// Examples: /// /// vluint32_t m_cases[10]; /// constructor { /// for (int i=0; i<10; ++i) { m_cases[i]=0; } /// } /// for (int i=0; i<10; ++i) { /// VL_COVER_INSERT(&m_cases[i], "comment", "Coverage Case", "i", cvtToNumStr(i)); /// } #define VL_COVER_INSERT(countp,args...) \ VL_IF_COVER(VerilatedCov::_inserti(countp); \ VerilatedCov::_insertf(__FILE__, __LINE__); \ VerilatedCov::_insertp("hier", name(), args)) //============================================================================= /// Convert VL_COVER_INSERT value arguments to strings template< class T> std::string vlCovCvtToStr(const T& t) VL_PURE { std::ostringstream os; os<<t; return os.str(); } //============================================================================= // VerilatedCov /// Verilator coverage global class //// /// Global class with methods affecting all coverage data. /// All public methods in this class are thread safe. class VerilatedCov { VL_UNCOPYABLE(VerilatedCov); public: // GLOBAL METHODS /// Return default filename static const char* defaultFilename() VL_PURE { return "coverage.dat"; } /// Write all coverage data to a file static void write(const char* filenamep = defaultFilename()) VL_MT_SAFE; /// Insert a coverage item /// We accept from 1-30 key/value pairs, all as strings. /// Call _insert1, followed by _insert2 and _insert3 /// Do not call directly; use VL_COVER_INSERT or higher level macros instead // _insert1: Remember item pointer with count. (Not const, as may add zeroing function) static void _inserti(vluint32_t* itemp) VL_MT_SAFE; static void _inserti(vluint64_t* itemp) VL_MT_SAFE; // _insert2: Set default filename and line number static void _insertf(const char* filename, int lineno) VL_MT_SAFE; // _insert3: Set parameters // We could have just the maximum argument version, but this compiles // much slower (nearly 2x) than having smaller versions also. However // there's not much more gain in having a version for each number of args. #define K(n) const char* key ## n #define A(n) const char* key ## n, const char* valp ## n // Argument list #define D(n) const char* key ## n = NULL, const char* valp ## n = NULL // Argument list static void _insertp(D(0),D(1),D(2),D(3),D(4),D(5),D(6),D(7),D(8),D(9)); static void _insertp(A(0),A(1),A(2),A(3),A(4),A(5),A(6),A(7),A(8),A(9) ,A(10),D(11),D(12),D(13),D(14),D(15),D(16),D(17),D(18),D(19)); static void _insertp(A(0),A(1),A(2),A(3),A(4),A(5),A(6),A(7),A(8),A(9) ,A(10),A(11),A(12),A(13),A(14),A(15),A(16),A(17),A(18),A(19) ,A(20),D(21),D(22),D(23),D(24),D(25),D(26),D(27),D(28),D(29)); // Backward compatibility for Verilator static void _insertp(A(0), A(1), K(2),int val2, K(3),int val3, K(4),const std::string& val4, A(5),A(6)); #undef K #undef A #undef D /// Clear coverage points (and call delete on all items) static void clear() VL_MT_SAFE; /// Clear items not matching the provided string static void clearNonMatch(const char* matchp) VL_MT_SAFE; /// Zero coverage points static void zero() VL_MT_SAFE; }; #endif // Guard <|start_filename|>basic/lesson3/verilator/sim/vinc/verilated_sym_props.h<|end_filename|> // -*- mode: C++; c-file-style: "cc-mode" -*- //************************************************************************* // // Copyright 2003-2020 by <NAME>. This program is free software; you can // redistribute it and/or modify it under the terms of either the GNU // Lesser General Public License Version 3 or the Perl Artistic License. // Version 2.0. // // Verilator is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // //************************************************************************* /// /// \file /// \brief Verilator: Include to provide information about symbol inspection /// /// This file is for inclusion by internal files that need to inspect /// specific symbols. /// /// User routines wanting to inspect the symbol table should use /// verilated_syms.h instead. /// /// These classes are thread safe, and read only. /// /// Code available from: https://verilator.org /// //************************************************************************* #ifndef _VERILATED_SYM_PROPS_H_ #define _VERILATED_SYM_PROPS_H_ 1 ///< Header Guard #include "verilatedos.h" //=========================================================================== /// Verilator range /// Thread safety: Assume is constructed only with model, then any number of readers // See also V3Ast::VNumRange class VerilatedRange { int m_left; int m_right; protected: friend class VerilatedVarProps; friend class VerilatedScope; VerilatedRange() : m_left(0), m_right(0) {} VerilatedRange(int left, int right) : m_left(left), m_right(right) {} void init(int left, int right) { m_left=left; m_right=right; } public: ~VerilatedRange() {} int left() const { return m_left; } int right() const { return m_right; } int low() const { return (m_left < m_right) ? m_left : m_right; } int high() const { return (m_left > m_right) ? m_left : m_right; } int elements() const { return (VL_LIKELY(m_left>=m_right) ? (m_left-m_right+1) : (m_right-m_left+1)); } int increment() const { return (m_left >= m_right) ? 1 : -1; } }; //=========================================================================== /// Verilator variable /// Thread safety: Assume is constructed only with model, then any number of readers class VerilatedVarProps { // TYPES enum { MAGIC = 0xddc4f829 }; // MEMBERS const vluint32_t m_magic; // Magic number const VerilatedVarType m_vltype; // Data type const VerilatedVarFlags m_vlflags; // Direction const int m_pdims; // Packed dimensions const int m_udims; // Unpacked dimensions VerilatedRange m_packed; // Packed array range VerilatedRange m_unpacked[3]; // Unpacked array range // CONSTRUCTORS protected: friend class VerilatedScope; VerilatedVarProps(VerilatedVarType vltype, VerilatedVarFlags vlflags, int pdims, int udims) : m_magic(MAGIC), m_vltype(vltype), m_vlflags(vlflags), m_pdims(pdims), m_udims(udims) {} public: class Unpacked {}; // Without packed VerilatedVarProps(VerilatedVarType vltype, int vlflags) : m_magic(MAGIC), m_vltype(vltype), m_vlflags(VerilatedVarFlags(vlflags)), m_pdims(0), m_udims(0) { } VerilatedVarProps(VerilatedVarType vltype, int vlflags, Unpacked, int u0l, int u0r) : m_magic(MAGIC), m_vltype(vltype), m_vlflags(VerilatedVarFlags(vlflags)), m_pdims(0), m_udims(1) { m_unpacked[0].init(u0l, u0r); } VerilatedVarProps(VerilatedVarType vltype, int vlflags, Unpacked, int u0l, int u0r, int u1l, int u1r) : m_magic(MAGIC), m_vltype(vltype), m_vlflags(VerilatedVarFlags(vlflags)), m_pdims(0), m_udims(2) { m_unpacked[0].init(u0l, u0r); m_unpacked[1].init(u1l, u1r); } VerilatedVarProps(VerilatedVarType vltype, int vlflags, Unpacked, int u0l, int u0r, int u1l, int u1r, int u2l, int u2r) : m_magic(MAGIC), m_vltype(vltype), m_vlflags(VerilatedVarFlags(vlflags)), m_pdims(0), m_udims(3) { m_unpacked[0].init(u0l, u0r); m_unpacked[1].init(u1l, u1r); m_unpacked[2].init(u2l, u2r); } // With packed class Packed {}; VerilatedVarProps(VerilatedVarType vltype, int vlflags, Packed, int pl, int pr) : m_magic(MAGIC), m_vltype(vltype), m_vlflags(VerilatedVarFlags(vlflags)), m_pdims(1), m_udims(0), m_packed(pl,pr) { } VerilatedVarProps(VerilatedVarType vltype, int vlflags, Packed, int pl, int pr, Unpacked, int u0l, int u0r) : m_magic(MAGIC), m_vltype(vltype), m_vlflags(VerilatedVarFlags(vlflags)), m_pdims(1), m_udims(1), m_packed(pl,pr) { m_unpacked[0].init(u0l, u0r); } VerilatedVarProps(VerilatedVarType vltype, int vlflags, Packed, int pl, int pr, Unpacked, int u0l, int u0r, int u1l, int u1r) : m_magic(MAGIC), m_vltype(vltype), m_vlflags(VerilatedVarFlags(vlflags)), m_pdims(1), m_udims(2), m_packed(pl,pr) { m_unpacked[0].init(u0l, u0r); m_unpacked[1].init(u1l, u1r); } VerilatedVarProps(VerilatedVarType vltype, int vlflags, Packed, int pl, int pr, Unpacked, int u0l, int u0r, int u1l, int u1r, int u2l, int u2r) : m_magic(MAGIC), m_vltype(vltype), m_vlflags(VerilatedVarFlags(vlflags)), m_pdims(1), m_udims(3), m_packed(pl,pr) { m_unpacked[0].init(u0l, u0r); m_unpacked[1].init(u1l, u1r); m_unpacked[2].init(u2l, u2r); } public: ~VerilatedVarProps() {} // METHODS bool magicOk() const { return m_magic == MAGIC; } VerilatedVarType vltype() const { return m_vltype; } VerilatedVarFlags vldir() const { return static_cast<VerilatedVarFlags>(static_cast<int>(m_vlflags) & VLVF_MASK_DIR); } vluint32_t entSize() const; bool isPublicRW() const { return ((m_vlflags & VLVF_PUB_RW) != 0); } /// DPI compatible C standard layout bool isDpiCLayout() const { return ((m_vlflags & VLVF_DPI_CLAY) != 0); } int udims() const { return m_udims; } int dims() const { return m_pdims + m_udims; } const VerilatedRange& packed() const { return m_packed; } const VerilatedRange& unpacked() const { return m_unpacked[0]; } // DPI accessors int left(int dim) const { return dim==0 ? m_packed.left() : VL_LIKELY(dim>=1 && dim<=3) ? m_unpacked[dim-1].left() : 0; } int right(int dim) const { return dim==0 ? m_packed.right() : VL_LIKELY(dim>=1 && dim<=3) ? m_unpacked[dim-1].right() : 0; } int low(int dim) const { return dim==0 ? m_packed.low() : VL_LIKELY(dim>=1 && dim<=3) ? m_unpacked[dim-1].low() : 0; } int high(int dim) const { return dim==0 ? m_packed.high() : VL_LIKELY(dim>=1 && dim<=3) ? m_unpacked[dim-1].high() : 0; } int increment(int dim) const { return dim==0 ? m_packed.increment() : VL_LIKELY(dim>=1 && dim<=3) ? m_unpacked[dim-1].increment() : 0; } int elements(int dim) const { return dim==0 ? m_packed.elements() : VL_LIKELY(dim>=1 && dim<=3) ? m_unpacked[dim-1].elements() : 0; } /// Total size in bytes (note DPI limited to 4GB) size_t totalSize() const; /// Adjust a data pointer to access a given array element, NuLL if something goes bad void* datapAdjustIndex(void* datap, int dim, int indx) const; }; //=========================================================================== /// Verilator DPI open array variable class VerilatedDpiOpenVar { // MEMBERS const VerilatedVarProps* m_propsp; // Variable properties void* m_datap; // Location of data (local to thread always, so safe) public: // CONSTRUCTORS VerilatedDpiOpenVar(const VerilatedVarProps* propsp, void* datap) : m_propsp(propsp) , m_datap(datap) {} VerilatedDpiOpenVar(const VerilatedVarProps* propsp, const void* datap) : m_propsp(propsp) , m_datap(const_cast<void*>(datap)) {} ~VerilatedDpiOpenVar() {} // METHODS void* datap() const { return m_datap; } // METHODS - from VerilatedVarProps bool magicOk() const { return m_propsp->magicOk(); } VerilatedVarType vltype() const { return m_propsp->vltype(); } bool isDpiStdLayout() const { return m_propsp->isDpiCLayout(); } const VerilatedRange& packed() const { return m_propsp->packed(); } const VerilatedRange& unpacked() const { return m_propsp->unpacked(); } int udims() const { return m_propsp->udims(); } int left(int dim) const { return m_propsp->left(dim); } int right(int dim) const { return m_propsp->right(dim); } int low(int dim) const { return m_propsp->low(dim); } int high(int dim) const { return m_propsp->high(dim); } int increment(int dim) const { return m_propsp->increment(dim); } int elements(int dim) const { return m_propsp->elements(dim); } size_t totalSize() const { return m_propsp->totalSize(); } void* datapAdjustIndex(void* datap, int dim, int indx) const { return m_propsp->datapAdjustIndex(datap, dim, indx); } }; //=========================================================================== /// Verilator variable /// Thread safety: Assume is constructed only with model, then any number of readers class VerilatedVar : public VerilatedVarProps { // MEMBERS void* m_datap; // Location of data const char* m_namep; // Name - slowpath protected: friend class VerilatedScope; // CONSTRUCTORS VerilatedVar(const char* namep, void* datap, VerilatedVarType vltype, VerilatedVarFlags vlflags, int dims) : VerilatedVarProps(vltype, vlflags, (dims>0?1:0), ((dims>1)?dims-1:0)) , m_datap(datap), m_namep(namep) {} public: ~VerilatedVar() {} // ACCESSORS void* datap() const { return m_datap; } const VerilatedRange& range() const { return packed(); } // Deprecated const VerilatedRange& array() const { return unpacked(); } // Deprecated const char* name() const { return m_namep; } }; #endif // Guard <|start_filename|>basic/lesson3/verilator/sim/vinc/verilated_syms.h<|end_filename|> // -*- mode: C++; c-file-style: "cc-mode" -*- //************************************************************************* // // Copyright 2003-2020 by <NAME>. This program is free software; you can // redistribute it and/or modify it under the terms of either the GNU // Lesser General Public License Version 3 or the Perl Artistic License. // Version 2.0. // // Verilator is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // //************************************************************************* /// /// \file /// \brief Verilator: Include to allow symbol inspection /// /// This file is for inclusion by files that need to inspect the symbol /// table. It is not included in verilated.h (instead see /// verilated_sym_props.h) as it requires some heavyweight C++ classes. /// /// These classes are thread safe and read only. It is constructed only /// when a model is built (from the main thread). /// /// Code available from: https://verilator.org /// //************************************************************************* #ifndef _VERILATED_SYMS_H_ #define _VERILATED_SYMS_H_ 1 ///< Header Guard #include "verilatedos.h" #include "verilated_heavy.h" #include "verilated_sym_props.h" #include <map> #include <vector> //====================================================================== /// Types /// Class to sort maps keyed by const char*'s struct VerilatedCStrCmp { bool operator()(const char* a, const char* b) const { return std::strcmp(a, b) < 0; } }; /// Map of sorted scope names to find associated scope class class VerilatedScopeNameMap : public std::map<const char*, const VerilatedScope*, VerilatedCStrCmp> { public: VerilatedScopeNameMap() {} ~VerilatedScopeNameMap() {} }; /// Map of sorted variable names to find associated variable class class VerilatedVarNameMap : public std::map<const char*, VerilatedVar, VerilatedCStrCmp> { public: VerilatedVarNameMap() {} ~VerilatedVarNameMap() {} }; typedef std::vector<const VerilatedScope*> VerilatedScopeVector; class VerilatedHierarchyMap : public std::map<const VerilatedScope*, VerilatedScopeVector> { public: VerilatedHierarchyMap() {} ~VerilatedHierarchyMap() {} }; #endif // Guard <|start_filename|>basic/lesson3_68k/rom/go.bat<|end_filename|> ; toolchain available ; https://gnutoolchains.com/m68k-elf/ m68k-elf-gcc -Wall -nostdlib -nodefaultlibs -fomit-frame-pointer -m68000 -c test.c m68k-elf-ld -T 68k.ld test.o m68k-elf-objcopy -I coff-m68k -O binary a.out test.bin ; disassembly can be generated using ; m68k-elf-objdump -d a.out <|start_filename|>advanced/zaxsound/romextract/dumppf.c<|end_filename|> #include <stdio.h> #include <stdlib.h> #define kSize 1024*16 unsigned char b[kSize]; main(int argc, char *argv[]) { int i; char *bs; if (1 || argc > 1 && argv[1][0] == '-' && argv[1][1] == 'c') { // case read(0, b, kSize); printf(" // centipede\n"); printf(" case (a)\n"); for (i = 0; i < kSize; i++) { printf("\t14'h%03x: q = 8'h%02x; // 0x%03x\n", i, b[i], i); } printf(" endcase\n"); } else { // initial block printf("initial begin\n"); printf("\t// centipede\n"); read(0, b, 8192); for (i = 0; i < 2048; i++) { printf("\trom[%d] = 8'h%02x; // 0x%04x\n", i, b[i], i); } printf("end\n"); } exit(0); } <|start_filename|>basic/lesson3/verilator/sim/sim_console.h<|end_filename|> #pragma once #include "imgui.h" struct DebugConsole { public: void AddLog(const char* fmt, ...) IM_FMTARGS(2); DebugConsole(); ~DebugConsole(); void ClearLog(); void Draw(const char* title, bool* p_open); void ExecCommand(const char* command_line); int TextEditCallback(ImGuiInputTextCallbackData* data); }; <|start_filename|>basic/lesson3_68k/clean.bat<|end_filename|> @echo off del /s *.bak del /s *.orig del /s *.rej del /s *~ rmdir /s /q db rmdir /s /q incremental_db rmdir /s /q output_files rmdir /s /q simulation rmdir /s /q greybox_tmp rmdir /s /q hc_output rmdir /s /q .qsys_edit rmdir /s /q hps_isw_handoff rmdir /s /q sys\.qsys_edit rmdir /s /q sys\vip for /d %%i in (sys\*_sim) do rmdir /s /q "%%i" for /d %%i in (rtl\*_sim) do rmdir /s /q "%%i" del build_id.v del c5_pin_model_dump.txt del PLLJ_PLLSPE_INFO.txt del /s *.qws del /s *.ppf del /s *.ddb del /s *.csv del /s *.cmp del /s *.sip del /s *.spd del /s *.bsf del /s *.f del /s *.sopcinfo del /s *.xml del *.cdf del *.rpt del /s new_rtl_netlist del /s old_rtl_netlist pause <|start_filename|>basic/lesson3/verilator/sim/sim_clock.cpp<|end_filename|> #include "sim_clock.h" #include <string> //bool clk, old; //int ratio, count; SimClock::SimClock(int r) { ratio = r; count = 0; clk = false; old = false; } SimClock::~SimClock() { } void SimClock::Tick() { old = clk; count++; if (count >= ratio) { clk = !clk; count = 0; } } void SimClock::Reset() { count = 0; clk = false; old = false; } <|start_filename|>basic/lesson3_68k/rom/bin2hex/bin2hex.c<|end_filename|> #include <stdio.h> #include <stdlib.h> void ConvertFile(char *srcname, char *dstname) { int count,checksum; int offs = 0; int offsh, offsl; FILE *src,*dst; unsigned char buffer[16]; src = fopen(srcname,"rb"); if (ferror(src)) { char errbuf[256] = ""; perror(errbuf); printf("%s\n", errbuf); exit(0); } dst = fopen(dstname,"w"); count = fread(buffer, 1, 2, src); while ( count > 0 ) { offsh = ( offs >> 8 ) & 0xff ; offsl = offs & 0xff ; // value of each hex digit in the output line checksum = 2 + offsh + offsl + buffer[0] + buffer[1]; if ( count == 1 ) { // always write 16 bits worth buffer[1]=0; } // fprintf(dst,":02%02X%02X00%02X%02X%02X\n", offsh, offsl, buffer[0], buffer[1], (65536-checksum) & 0xff); offs++; // one 16 bit word // read more count = fread(buffer, sizeof(unsigned char), 2, src); } fprintf(dst,":00000001FF\n"); fclose(src); fclose(dst); } int main (int argc, char **argv ) { if ( argc == 0 ) { printf("usage: bin2hex test.bin test.hex"); exit(0); } ConvertFile(argv[1],argv[2]); } <|start_filename|>basic/lesson9/bin2c.c<|end_filename|> /* * bin2c.c - binary to c array converter. * * Written by * <NAME> <<EMAIL>> * * This file is part of VICE, the Versatile Commodore Emulator. * See README for copyright notice. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA. * */ #include <stdio.h> void generate_c_file(char *in_filename, char *out_filename, char *array) { FILE *infile, *outfile; int amount, start, i; unsigned char buffer[8]; infile=fopen(in_filename,"rb"); if (infile==NULL) { printf("cannot open %s for reading\n",in_filename); return; } outfile=fopen(out_filename,"wb"); if (outfile==NULL) { printf("cannot open %s for writing\n",out_filename); fclose(infile); return; } fprintf(outfile,"/* Autogenerated file, DO NOT EDIT !!! */\n\n"); fprintf(outfile,"%s = {\n", array); start = 1; while (!feof(infile)) { amount = fread(buffer, 1, 8, infile); if (start == 0) { fprintf(outfile, ",\n"); } else { start = 0; } if (amount >= 1) { fprintf(outfile, " 0x%02X", buffer[0]); } for (i = 2; i < 9; i++) { if (amount >= i) { fprintf(outfile, ", 0x%02X", buffer[i - 1]); } } } fprintf(outfile,"\n};\n"); fclose(infile); fclose(outfile); return; } int main(int argc, char *argv[]) { if (argc<4) { printf("too few arguments\n"); exit(1); } generate_c_file(argv[1], argv[2], argv[3]); return 0; } <|start_filename|>basic/lesson9/font.c<|end_filename|> /* Autogenerated file, DO NOT EDIT !!! */ unsigned char font[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x78, 0x78, 0x78, 0x30, 0x00, 0x30, 0x00, 0xCC, 0x66, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x7F, 0x36, 0x36, 0x7F, 0x36, 0x00, 0x7C, 0xD6, 0xD0, 0x7C, 0x16, 0xD6, 0x7C, 0x10, 0xE3, 0xA6, 0xEC, 0x18, 0x37, 0x65, 0xC7, 0x00, 0x38, 0x4C, 0x38, 0x45, 0xC6, 0xCE, 0x7A, 0x01, 0x06, 0x0C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x0C, 0x60, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x60, 0x10, 0x54, 0x38, 0xFE, 0x38, 0x54, 0x10, 0x00, 0x00, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x30, 0x00, 0x00, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x03, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x00, 0x7C, 0xCE, 0xDE, 0xFE, 0xEE, 0xCE, 0x7C, 0x00, 0x1C, 0x3C, 0x1C, 0x1C, 0x1C, 0x1C, 0x1C, 0x00, 0x7C, 0xCE, 0x0E, 0x1C, 0x38, 0x70, 0xFE, 0x00, 0x7C, 0xCE, 0x0E, 0x3C, 0x0E, 0xCE, 0x7C, 0x00, 0xCE, 0xCE, 0xCE, 0xCE, 0xFE, 0x0E, 0x0E, 0x00, 0xFE, 0xE0, 0xE0, 0xFC, 0x0E, 0x0E, 0xFC, 0x00, 0x7C, 0xE6, 0xE0, 0xFC, 0xE6, 0xE6, 0x7C, 0x00, 0xFE, 0x06, 0x0E, 0x1C, 0x38, 0x38, 0x38, 0x00, 0x7C, 0xE6, 0xE6, 0x7C, 0xE6, 0xE6, 0x7C, 0x00, 0x7C, 0xCE, 0xCE, 0x7E, 0x0E, 0x0E, 0xFC, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x30, 0x60, 0x00, 0x00, 0x18, 0x30, 0x60, 0x30, 0x18, 0x00, 0x00, 0x00, 0x00, 0x7E, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x30, 0x18, 0x0C, 0x18, 0x30, 0x00, 0x00, 0x7C, 0xC6, 0x0E, 0x1C, 0x38, 0x00, 0x38, 0x00, 0x7C, 0xC6, 0xDE, 0xDE, 0xDC, 0xC0, 0x7C, 0x00, 0x7C, 0xE6, 0xE6, 0xE6, 0xFE, 0xE6, 0xE6, 0x00, 0xFC, 0xE6, 0xE6, 0xFC, 0xE6, 0xE6, 0xFC, 0x00, 0x7C, 0xE6, 0xE0, 0xE0, 0xE6, 0xE6, 0x7C, 0x00, 0xFC, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xFC, 0x00, 0xFE, 0xE0, 0xE0, 0xFE, 0xE0, 0xE0, 0xFE, 0x00, 0xFE, 0xE0, 0xE0, 0xFE, 0xE0, 0xE0, 0xE0, 0x00, 0x7C, 0xE6, 0xE0, 0xEE, 0xE6, 0xE6, 0x7C, 0x00, 0xE6, 0xE6, 0xE6, 0xFE, 0xE6, 0xE6, 0xE6, 0x00, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x00, 0x0E, 0x0E, 0x0E, 0x0E, 0xCE, 0xCE, 0x7C, 0x00, 0xE6, 0xEC, 0xF8, 0xF0, 0xF8, 0xEC, 0xE6, 0x00, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xFE, 0x00, 0xC6, 0xEE, 0xFE, 0xD6, 0xC6, 0xC6, 0xC6, 0x00, 0xC6, 0xE6, 0xF6, 0xFE, 0xEE, 0xE6, 0xE6, 0x00, 0x7C, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0x7C, 0x00, 0xFC, 0xE6, 0xE6, 0xFC, 0xE0, 0xE0, 0xE0, 0x00, 0x7C, 0xE6, 0xE6, 0xE6, 0xE6, 0xEA, 0x74, 0x02, 0xFC, 0xE6, 0xE6, 0xFC, 0xE6, 0xE6, 0xE6, 0x00, 0x7C, 0xE6, 0xE0, 0x7C, 0x0E, 0xCE, 0x7C, 0x00, 0xFE, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x00, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0x7C, 0x00, 0xE6, 0xE6, 0xE6, 0xE6, 0xE6, 0x7C, 0x38, 0x00, 0xC6, 0xC6, 0xC6, 0xD6, 0xD6, 0xFE, 0xFC, 0x00, 0xE3, 0x76, 0x3C, 0x18, 0x3C, 0x6E, 0xC7, 0x00, 0xE6, 0xE6, 0x7C, 0x38, 0x38, 0x38, 0x38, 0x00, 0xFE, 0x0E, 0x1C, 0x38, 0x70, 0xE0, 0xFE, 0x00, 0x1C, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1C, 0x00, 0x60, 0x30, 0x18, 0x0C, 0x06, 0x03, 0x00, 0x70, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x70, 0x18, 0x3C, 0x66, 0xC3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x30, 0x18, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0x0E, 0x7E, 0xCE, 0x7E, 0x00, 0xC0, 0xC0, 0xFC, 0xE6, 0xE6, 0xE6, 0xFC, 0x00, 0x00, 0x00, 0x7C, 0xE6, 0xE0, 0xE6, 0x7C, 0x00, 0x06, 0x06, 0x7E, 0xCE, 0xCE, 0xCE, 0x7E, 0x00, 0x00, 0x00, 0x7C, 0xE6, 0xFE, 0xE0, 0x7E, 0x00, 0x3C, 0x70, 0x70, 0xFC, 0x70, 0x70, 0x70, 0x00, 0x00, 0x00, 0x7C, 0xCE, 0xCE, 0x7E, 0x0E, 0x7C, 0xC0, 0xC0, 0xFC, 0xE6, 0xE6, 0xE6, 0xE6, 0x00, 0x18, 0x00, 0x18, 0x38, 0x38, 0x38, 0x38, 0x00, 0x0C, 0x00, 0x0C, 0x1C, 0x1C, 0x1C, 0x1C, 0xF8, 0xC0, 0xC0, 0xCC, 0xD8, 0xF0, 0xD8, 0xCC, 0x00, 0x18, 0x18, 0x38, 0x38, 0x38, 0x38, 0x38, 0x00, 0x00, 0x00, 0xFC, 0xD6, 0xD6, 0xD6, 0xD6, 0x00, 0x00, 0x00, 0xFC, 0xE6, 0xE6, 0xE6, 0xE6, 0x00, 0x00, 0x00, 0x7C, 0xE6, 0xE6, 0xE6, 0x7C, 0x00, 0x00, 0x00, 0xFC, 0xE6, 0xE6, 0xFC, 0xE0, 0xE0, 0x00, 0x00, 0x7E, 0xCE, 0xCE, 0x7E, 0x0E, 0x0E, 0x00, 0x00, 0xFC, 0xE6, 0xE0, 0xE0, 0xE0, 0x00, 0x00, 0x00, 0x7E, 0xE0, 0x7C, 0x0E, 0xFC, 0x00, 0x18, 0x18, 0x7E, 0x38, 0x38, 0x38, 0x38, 0x00, 0x00, 0x00, 0xE6, 0xE6, 0xE6, 0xE6, 0x7E, 0x00, 0x00, 0x00, 0xE6, 0xE6, 0xE6, 0x6C, 0x38, 0x00, 0x00, 0x00, 0xD6, 0xD6, 0xD6, 0xD6, 0xFC, 0x00, 0x00, 0x00, 0xE6, 0x7C, 0x38, 0x7C, 0xCE, 0x00, 0x00, 0x00, 0xCE, 0xCE, 0xCE, 0x7E, 0x0E, 0xFC, 0x00, 0x00, 0xFE, 0x1C, 0x38, 0x70, 0xFE, 0x00, 0x0C, 0x18, 0x18, 0x30, 0x18, 0x18, 0x0C, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x60, 0x30, 0x30, 0x18, 0x30, 0x30, 0x60, 0x00, 0x70, 0xDB, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x28, 0x44, 0xFE, 0x00, 0x00, }; <|start_filename|>basic/lesson3/verilator/sim/sim_video.cpp<|end_filename|> #include "sim_video.h" #include <string> #ifndef _MSC_VER #include "imgui_impl_sdl.h" #include "imgui_impl_opengl2.h" #include <stdio.h> #include <SDL.h> #include <SDL_opengl.h> #include <sys/time.h> #else #define WIN32 #include "imgui_impl_win32.h" #include "imgui_impl_dx11.h" #include <d3d11.h> #include <tchar.h> #endif // Renderer variables // ------------------ int output_width = 512; int output_height = 512; int output_rotate = 0; bool output_vflip = false; uint32_t* output_ptr = NULL; unsigned int output_size; #ifdef WIN32 HWND hwnd; WNDCLASSEX wc; #else SDL_Window* window; SDL_GLContext gl_context; GLuint tex; #endif ImTextureID texture_id; ImGuiIO io; ImVec4 clear_color = ImVec4(0.25f, 0.35f, 0.40f, 0.80f); int count_pixel; int count_line; int count_frame; bool last_hblank; bool last_vblank; // Statistics #ifdef WIN32 SYSTEMTIME actualtime; LONG time_ms; LONG old_time; LONG stats_frameTime; #else double time_ms; double old_time; double stats_frameTime; #endif float stats_fps; int stats_xMax; int stats_yMax; int stats_xMin; int stats_yMin; #ifndef WIN32 SDL_Renderer* renderer = NULL; SDL_Texture* texture = NULL; #else // DirectX data static ID3D11Device* g_pd3dDevice = NULL; static ID3D11DeviceContext* g_pd3dDeviceContext = NULL; static IDXGIFactory* g_pFactory = NULL; static ID3D11Buffer* g_pVB = NULL; static ID3D11Buffer* g_pIB = NULL; static ID3D10Blob* g_pVertexShaderBlob = NULL; static ID3D11VertexShader* g_pVertexShader = NULL; static ID3D11InputLayout* g_pInputLayout = NULL; static ID3D11Buffer* g_pVertexConstantBuffer = NULL; static ID3D10Blob* g_pPixelShaderBlob = NULL; static ID3D11PixelShader* g_pPixelShader = NULL; static ID3D11SamplerState* g_pFontSampler = NULL; static ID3D11ShaderResourceView* g_pFontTextureView = NULL; static ID3D11RasterizerState* g_pRasterizerState = NULL; static ID3D11BlendState* g_pBlendState = NULL; static ID3D11DepthStencilState* g_pDepthStencilState = NULL; static int g_VertexBufferSize = 5000, g_IndexBufferSize = 10000; static ID3D11Texture2D* texture = NULL; #endif #ifdef WIN32 // Data static IDXGISwapChain* g_pSwapChain = NULL; static ID3D11RenderTargetView* g_mainRenderTargetView = NULL; void CreateRenderTarget() { ID3D11Texture2D* pBackBuffer; g_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer); g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &g_mainRenderTargetView); pBackBuffer->Release(); } void CleanupRenderTarget() { if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = NULL; } } HRESULT CreateDeviceD3D(HWND hWnd) { // Setup swap chain DXGI_SWAP_CHAIN_DESC sd; ZeroMemory(&sd, sizeof(sd)); sd.BufferCount = 2; sd.BufferDesc.Width = output_width; sd.BufferDesc.Height = output_height; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = hWnd; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.Windowed = TRUE; sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; UINT createDeviceFlags = 0; D3D_FEATURE_LEVEL featureLevel; const D3D_FEATURE_LEVEL featureLevelArray[2] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_0, }; if (D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &featureLevel, &g_pd3dDeviceContext) != S_OK) return E_FAIL; CreateRenderTarget(); return S_OK; } void CleanupDeviceD3D() { CleanupRenderTarget(); if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = NULL; } if (g_pd3dDeviceContext) { g_pd3dDeviceContext->Release(); g_pd3dDeviceContext = NULL; } if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; } } extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam)) return true; switch (msg) { case WM_SIZE: if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) { CleanupRenderTarget(); g_pSwapChain->ResizeBuffers(0, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam), DXGI_FORMAT_UNKNOWN, 0); CreateRenderTarget(); } return 0; case WM_SYSCOMMAND: if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu return 0; break; case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(hWnd, msg, wParam, lParam); } #else #endif SimVideo::SimVideo(int width, int height, int rotate) { output_width = width; output_height = height; output_size = output_width * output_height * 4; output_rotate = rotate; output_vflip = 0; count_pixel = 0; count_line = 0; count_frame = 0; last_hblank = 0; last_vblank = 0; old_time = 0; stats_frameTime = 0; stats_fps = 0.0; stats_xMax = -100; stats_yMax = -100; stats_xMin = 1000; stats_yMin = 1000; } SimVideo::~SimVideo() { } int SimVideo::Initialise(const char* windowTitle) { // Setup pointers for video texture output_ptr = (uint32_t*)malloc(output_size); #ifdef WIN32 // Create application window wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T(windowTitle), NULL }; RegisterClassEx(&wc); hwnd = CreateWindow(wc.lpszClassName, _T(windowTitle), WS_OVERLAPPEDWINDOW, 100, 100, 1600, 1100, NULL, NULL, wc.hInstance, NULL); // Initialize Direct3D if (CreateDeviceD3D(hwnd) < 0) { CleanupDeviceD3D(); UnregisterClass(wc.lpszClassName, wc.hInstance); return 1; } // Show the window ShowWindow(hwnd, SW_SHOWDEFAULT); UpdateWindow(hwnd); #else // Setup SDL if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_GAMECONTROLLER) != 0) { printf("Error: %s\n", SDL_GetError()); return -1; } // Setup window SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); window = SDL_CreateWindow("Dear ImGui SDL2+OpenGL example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags); gl_context = SDL_GL_CreateContext(window); SDL_GL_MakeCurrent(window, gl_context); SDL_GL_SetSwapInterval(0); #endif // Setup Dear ImGui context IMGUI_CHECKVERSION(); ImGui::CreateContext(); io = ImGui::GetIO(); (void)io; // Setup Dear ImGui style ImGui::StyleColorsDark(); #ifdef WIN32 // Setup Platform/Renderer bindings ImGui_ImplWin32_Init(hwnd); ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext); #else // Setup Platform/Renderer bindings ImGui_ImplSDL2_InitForOpenGL(window, gl_context); ImGui_ImplOpenGL2_Init(); #endif memset(output_ptr, 0xAA, output_size); #ifdef WIN32 // Upload texture to graphics system D3D11_TEXTURE2D_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.Width = output_width; desc.Height = output_height; desc.MipLevels = 1; desc.ArraySize = 1; desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; desc.SampleDesc.Count = 1; desc.Usage = D3D11_USAGE_DEFAULT; desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; D3D11_SUBRESOURCE_DATA subResource; subResource.pSysMem = output_ptr; subResource.SysMemPitch = desc.Width * 4; subResource.SysMemSlicePitch = 0; g_pd3dDevice->CreateTexture2D(&desc, &subResource, &texture); // Create texture view D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; ZeroMemory(&srvDesc, sizeof(srvDesc)); srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; srvDesc.Texture2D.MipLevels = desc.MipLevels; srvDesc.Texture2D.MostDetailedMip = 0; g_pd3dDevice->CreateShaderResourceView(texture, &srvDesc, &g_pFontTextureView); texture->Release(); // Store our identifier texture_id = (ImTextureID)g_pFontTextureView; // Create texture sampler { D3D11_SAMPLER_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; desc.MipLODBias = 0.f; desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; desc.MinLOD = 0.f; desc.MaxLOD = 0.f; g_pd3dDevice->CreateSamplerState(&desc, &g_pFontSampler); } #else // the texture should match the GPU so it doesn't have to copy glGenTextures(1, &tex); glBindTexture(GL_TEXTURE_2D, tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, output_width, output_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, output_ptr); texture_id = (ImTextureID)tex; #endif return 0; } void SimVideo::UpdateTexture() { #ifdef WIN32 // Update the texture! // D3D11_USAGE_DEFAULT MUST be set in the texture description (somewhere above) for this to work. // (D3D11_USAGE_DYNAMIC is for use with map / unmap.) ElectronAsh. g_pd3dDeviceContext->UpdateSubresource(texture, 0, NULL, output_ptr, output_width * 4, 0); // Rendering ImGui::Render(); g_pd3dDeviceContext->OMSetRenderTargets(1, &g_mainRenderTargetView, NULL); g_pd3dDeviceContext->ClearRenderTargetView(g_mainRenderTargetView, (float*)&clear_color); ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); g_pSwapChain->Present(0, 0); // Present without vsync #else glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, output_width, output_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, output_ptr); // Rendering ImGui::Render(); glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y); glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); glClear(GL_COLOR_BUFFER_BIT); //glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context where shaders may be bound ImGui_ImplOpenGL2_RenderDrawData(ImGui::GetDrawData()); SDL_GL_SwapWindow(window); #endif } void SimVideo::CleanUp() { #ifdef WIN32 // Close imgui stuff properly... ImGui_ImplDX11_Shutdown(); ImGui_ImplWin32_Shutdown(); ImGui::DestroyContext(); CleanupDeviceD3D(); DestroyWindow(hwnd); UnregisterClass(wc.lpszClassName, wc.hInstance); #else // Cleanup ImGui_ImplOpenGL2_Shutdown(); ImGui_ImplSDL2_Shutdown(); ImGui::DestroyContext(); SDL_GL_DeleteContext(gl_context); SDL_DestroyWindow(window); SDL_Quit(); #endif } void SimVideo::StartFrame() { #ifdef WIN32 ImGui_ImplDX11_NewFrame(); ImGui_ImplWin32_NewFrame(); #else ImGui_ImplOpenGL2_NewFrame(); ImGui_ImplSDL2_NewFrame(window); #endif } void SimVideo::Clock(bool hblank, bool vblank, uint32_t colour) { int ox = count_pixel + 1; int oy = count_line; // Only draw outside of blanks if (!(hblank || vblank)) { int x = ox, xs = output_width, y = oy; if (output_rotate == -1) { // Rotate output by 90 degrees clockwise y = output_height - ox; xs = output_width; x = oy; } if (output_rotate == 1) { // Rotate output by 90 degrees clockwise y = ox; xs = output_width; x = output_width - oy; } if (output_vflip) { y = output_height - y; } // Clamp values to stop access violations on texture if (x < 0) { x = 0; } if (x > output_width - 1) { x = output_width - 1; } if (y < 0) { y = 0; } if (y > output_height - 1) { y = output_height - 1; } // Generate texture address uint32_t vga_addr = (y * xs) + x; // Write pixel to texture output_ptr[vga_addr] = colour; // Track bounds (debug) if (x > stats_xMax) { stats_xMax = x; } if (y > stats_yMax) { stats_yMax = y; } if (x < stats_xMin) { stats_xMin = x; } if (y < stats_yMin) { stats_yMin = y; } } // Increment pixel counter count_pixel++; // Falling edge of hblank if (last_hblank && !hblank) { // Increment line and reset pixel count count_line++; count_pixel = 0; } // Falling edge of vblank if (last_vblank && !vblank) { count_frame++; count_line = 0; #ifdef WIN32 GetSystemTime(&actualtime); time_ms = (actualtime.wSecond * 1000) + actualtime.wMilliseconds; #else struct timeval tv; gettimeofday(&tv, NULL); time_ms = (tv.tv_sec) * 1000 + (tv.tv_usec) / 1000; // convert tv_sec & tv_usec to millisecond #endif stats_frameTime = time_ms - old_time; old_time = time_ms; stats_fps = (float)(1000.0 / stats_frameTime); } last_hblank = hblank; last_vblank = vblank; } <|start_filename|>basic/lesson8/ym_deint.c<|end_filename|> // ym files are usually interleaved for better compression. But that's // not convenient for streaming. This tool de-interleaves a ym file #include <stdio.h> #include <stdlib.h> #define SWAP32(a) ((((a)&0xff)<<24)|(((a)&0xff00)<<8)|(((a)&0xff0000)>>8)|(((a)&0xff000000)>>24)) int main(int argc, char **argv) { FILE *in, *out; char hdr[34], end[4]; int v, i, j; if(argc != 3) { printf("Usage: ym_deint <infile> <outfile>\n"); exit(-1); } printf("%s\n", argv[1]); in = fopen(argv[1], "rb"); if(!in) { printf("Unable to open %s\n", argv[1]); exit(-1); } out = fopen(argv[2], "wb"); if(!out) { printf("Unable to open %s\n", argv[2]); exit(-1); } if((v=fread(hdr, sizeof(hdr), 1, in)) < 0) { perror("fread"); exit(-1); } if(v != 1) { printf("short read\n"); exit(-1); } // check for ym file if((hdr[0] != 'Y')||(hdr[1] != 'M')) { printf("Not a YM file. Maybe compressed, please uncompress first\n"); exit(-1); } // check for digidrums if(hdr[20]||hdr[21]) { printf("Digidrums not supported\n"); exit(-1); } // check for interleaved if(hdr[19] != 0x01) { printf("File is not interleaved\n"); exit(-1); } // remove interleave marker hdr[19] = 0; // write header if(fwrite(hdr, sizeof(hdr), 1, out) < 0) { perror("fwrite"); exit(-1); } // skip names int c; printf("Name: "); while(((c = fgetc(in)) > 0) && c) { putchar(c); fputc(c, out); } fputc(c, out); puts(""); printf("Author: "); while(((c = fgetc(in)) > 0) && c) { putchar(c); fputc(c, out); } fputc(c, out); puts(""); printf("Comment: "); while(((c = fgetc(in)) > 0) && c) { putchar(c); fputc(c, out); } fputc(c, out); puts(""); unsigned long frames = SWAP32(*(unsigned long*)(hdr+12)); printf("converting %lu frames\n", frames); // allocate buffer for interleaved frames char *b = malloc(frames*16); if(!b) { perror("malloc"); exit(-1); } if((v=fread(b, 16, frames, in)) < 0) { perror("fread"); exit(-1); } if(v != frames) { printf("short read\n"); exit(-1); } // write de-interleaved for(i=0;i<frames;i++) for(j=0;j<16;j++) fputc(b[frames*j+i], out); if((v=fread(end, sizeof(end), 1, in)) < 0) { perror("fread"); exit(-1); } if(v != 1) { printf("short read\n"); exit(-1); } // check for ym file if((end[0] != 'E')||(end[1] != 'n')||(end[2] != 'd')||(end[3] != '!')) { printf("No End ID!\n"); exit(-1); } // write end if(fwrite(end, sizeof(end), 1, out) < 0) { perror("fwrite"); exit(-1); } fclose(in); return 0; } <|start_filename|>basic/lesson8/boot_rom.c<|end_filename|> // boot_rom.c // Boot ROM for the Z80 system on a chip (SoC) // (c) 2015 <NAME> #include <stdio.h> #include <string.h> #include "pff.h" #define BUFFERS 8 const BYTE animation[] = "|/-\\"; // space for 8 sectors DWORD frames = 0; WORD rptr = 0xffff; BYTE rsec = 0; BYTE ym_buffer[BUFFERS][512]; __sfr __at 0x10 PsgAddrPort; __sfr __at 0x11 PsgDataPort; // YM replay is happening in the interrupt void isr(void) __interrupt { BYTE i, *p; if(frames) { frames--; // write all 14 psg sound registers p = ym_buffer[rsec] + rptr; // unrolled loop for min delay between register writes PsgAddrPort = 0; PsgDataPort = *p++; PsgAddrPort = 1; PsgDataPort = *p++; PsgAddrPort = 2; PsgDataPort = *p++; PsgAddrPort = 3; PsgDataPort = *p++; PsgAddrPort = 4; PsgDataPort = *p++; PsgAddrPort = 5; PsgDataPort = *p++; PsgAddrPort = 6; PsgDataPort = *p++; PsgAddrPort = 7; PsgDataPort = *p++; PsgAddrPort = 8; PsgDataPort = *p++; PsgAddrPort = 9; PsgDataPort = *p++; PsgAddrPort = 10; PsgDataPort = *p++; PsgAddrPort = 11; PsgDataPort = *p++; PsgAddrPort = 12; PsgDataPort = *p++; PsgAddrPort = 13; if(*p != 255) PsgDataPort = *p++; rptr += 16; // one whole sector processed? if(rptr == 512) { rsec++; rptr=0; if(rsec == BUFFERS) rsec = 0; } } else { // not playing? mute all channels for(i=0;i<16;i++) { PsgAddrPort = i; PsgDataPort = 0; } } // re-enable interrupt __asm ei __endasm; } extern unsigned char font[]; unsigned char cur_x=0, cur_y=0; void putchar(char c) { unsigned char *p; unsigned char *dptr = (unsigned char*)(160*(8*cur_y) + 8*cur_x); char i, j; if(c < 32) { if(c == '\r') cur_x=0; if(c == '\n') { cur_y++; cur_x=0; if(cur_y >= 12) cur_y = 0; } return; } if(c < 0) return; p = font+8*(unsigned char)(c-32); for(i=0;i<8;i++) { unsigned char l = *p++; for(j=0;j<8;j++) { *dptr++ = (l & 0x80)?0xff:0x00; l <<= 1; } dptr += (160-8); } cur_x++; if(cur_x >= 20) { cur_x = 0; cur_y++; if(cur_y >= 12) cur_y = 0; } } void cls(void) { unsigned char i; unsigned char *p = (unsigned char*)0; for(i=0;i<100;i++) { memset(p, 0, 160); p+=160; } } void ei() { // set interrupt mode 1 and enable interrupts __asm im 1 ei __endasm; } void die (FRESULT rc) { printf("Fail rc=%u", rc); for (;;) ; } void main() { FATFS fatfs; /* File system object */ FRESULT rc; UINT bytes_read; BYTE i, wsec = 0; ei(); cls(); puts(" << Z80 SoC >>"); printf("Mounting SD card...\n"); // not playing? mute all channels for(i=0;i<16;i++) { PsgAddrPort = i; PsgDataPort = 0; } rc = pf_mount(&fatfs); if (rc) die(rc); // open song.ym printf("Opening SONG.YM...\n"); rc = pf_open("SONG.YM"); if(rc == FR_NO_FILE) { printf("File not found"); for(;;); } if (rc) die(rc); // read file sector by sector do { // Wait while irq routine is playing and all sector buffers are // full This would be the place where we'd be doing the main // processing like running a game engine. while((wsec == rsec) && frames); rc = pf_read(ym_buffer[wsec], 512, &bytes_read); // No song info yet? Read and analyse header! if(!frames) { // check for file header if((ym_buffer[0][0] != 'Y')||(ym_buffer[0][1] != 'M')) { printf("No YM file!\n"); for(;;); } printf("YM version: %.4s\n", ym_buffer[0]); // we only support files that are not interleaved if(ym_buffer[0][19] & 1) { printf("No Interleave!\n"); for(;;); } // we don't support digi drums if(ym_buffer[0][20] || ym_buffer[0][21]) { printf("No Digidums!\n"); for(;;); } // skip Song name, Author name and Song comment rptr = 34; printf("%s\n", ym_buffer[0]+rptr); while(ym_buffer[0][rptr]) rptr++; // song name rptr++; printf("%s\n", ym_buffer[0]+rptr); while(ym_buffer[0][rptr]) rptr++; // author name rptr++; while(ym_buffer[0][rptr]) rptr++; // song comment rptr++; // extract frames frames = 256l*256l*256l*ym_buffer[0][12] + 256l*256l*ym_buffer[0][13] + 256l*ym_buffer[0][14] + ym_buffer[0][15]; printf("Frames: %ld\n", frames); } // circle through the sector buffers wsec++; if(wsec == BUFFERS) wsec = 0; // do some animation printf("%c\r", animation[wsec&3]); // do this until all sectors are read } while((!rc) && (bytes_read == 512)); if (rc) die(rc); printf("done.\n"); while(1); }
tacertain/Tutorials_MiSTer
<|start_filename|>lib/src/rendering/layer.dart<|end_filename|> import 'dart:ui' as ui; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:local_hero/src/rendering/controller.dart'; import 'package:vector_math/vector_math_64.dart'; // ignore_for_file: public_member_api_docs class LocalHeroLayer extends ContainerLayer { /// Creates a local hero layer. /// /// The [controller] property must not be null. LocalHeroLayer({ required this.controller, }); /// An instance which holds the offset from the origin of the leader layer /// to the origin of the child layers, used when the layer is linked to a /// [LeaderLayer]. /// /// The scene must be explicitly recomposited after this property is changed /// (as described at [Layer]). LocalHeroController controller; Offset? _lastOffset; Matrix4? _lastTransform; Matrix4? _invertedTransform; bool _inverseDirty = true; Offset? _transformOffset<S>(Offset localPosition) { if (_inverseDirty) { _invertedTransform = Matrix4.tryInvert(getLastTransform()!); _inverseDirty = false; } if (_invertedTransform == null) { return null; } final Vector4 vector = Vector4(localPosition.dx, localPosition.dy, 0, 1); final Vector4 result = _invertedTransform!.transform(vector); return Offset( result[0] - controller.linkedOffset.dx, result[1] - controller.linkedOffset.dy, ); } @override @protected bool findAnnotations<S extends Object>( AnnotationResult<S> result, Offset localPosition, { required bool onlyFirst, }) { if (controller.link.leader == null) { return false; } final Offset? transformedOffset = _transformOffset<S>(localPosition); if (transformedOffset == null) { return false; } return super .findAnnotations<S>(result, transformedOffset, onlyFirst: onlyFirst); } /// The transform that was used during the last composition phase. /// /// If the [link] was not linked to a [LeaderLayer], or if this layer has /// a degenerate matrix applied, then this will be null. /// /// This method returns a new [Matrix4] instance each time it is invoked. Matrix4? getLastTransform() { if (_lastTransform == null) { return null; } final Matrix4 result = Matrix4.translationValues(-_lastOffset!.dx, -_lastOffset!.dy, 0); result.multiply(_lastTransform!); return result; } /// Call [applyTransform] for each layer in the provided list. /// /// The list is in reverse order (deepest first). The first layer will be /// treated as the child of the second, and so forth. The first layer in the /// list won't have [applyTransform] called on it. The first layer may be /// null. Matrix4 _collectTransformForLayerChain(List<ContainerLayer?> layers) { // Initialize our result matrix. final Matrix4 result = Matrix4.identity(); // Apply each layer to the matrix in turn, starting from the last layer, // and providing the previous layer as the child. for (int index = layers.length - 1; index > 0; index -= 1) { layers[index]!.applyTransform(layers[index - 1], result); } return result; } /// Populate [_lastTransform] given the current state of the tree. void _establishTransform() { _lastTransform = null; // Check to see if we are linked. if (controller.link.leader == null) { return; } // If we're linked, check the link is valid. assert(controller.link.leader!.owner == owner, 'Linked LeaderLayer anchor is not in the same layer tree as the FollowerLayer.'); // Collect all our ancestors into a Set so we can recognize them. final Set<Layer> ancestors = <Layer>{}; Layer? ancestor = parent; while (ancestor != null) { ancestors.add(ancestor); ancestor = ancestor.parent; } // Collect all the layers from a hypothetical child (null) of the target // layer up to the common ancestor layer. ContainerLayer layer = controller.link.leader!; final List<ContainerLayer?> forwardLayers = <ContainerLayer?>[null, layer]; do { layer = layer.parent!; forwardLayers.add(layer); } while (!ancestors.contains(layer)); ancestor = layer; // Collect all the layers from this layer up to the common ancestor layer. layer = this; final List<ContainerLayer?> inverseLayers = <ContainerLayer?>[layer]; do { layer = layer.parent!; inverseLayers.add(layer); } while (layer != ancestor); // Establish the forward and backward matrices given these lists of layers. final Matrix4 forwardTransform = _collectTransformForLayerChain(forwardLayers); final Matrix4 inverseTransform = _collectTransformForLayerChain(inverseLayers); if (inverseTransform.invert() == 0.0) { // We are in a degenerate transform, so there's not much we can do. return; } // Combine the matrices and store the result. inverseTransform.multiply(forwardTransform); inverseTransform.translate( controller.linkedOffset.dx, controller.linkedOffset.dy, ); _lastTransform = inverseTransform; _inverseDirty = true; } /// {@template flutter.leaderFollower.alwaysNeedsAddToScene} /// This disables retained rendering. /// /// A [FollowerLayer] copies changes from a [LeaderLayer] that could be anywhere /// in the Layer tree, and that leader layer could change without notifying the /// follower layer. Therefore we have to always call a follower layer's /// [addToScene]. In order to call follower layer's [addToScene], leader layer's /// [addToScene] must be called first so leader layer must also be considered /// as [alwaysNeedsAddToScene]. /// {@endtemplate} @override bool get alwaysNeedsAddToScene => true; @override void addToScene(ui.SceneBuilder builder, [Offset layerOffset = Offset.zero]) { if (controller.link.leader == null) { _lastTransform = null; _lastOffset = null; _inverseDirty = true; engineLayer = null; return; } _establishTransform(); if (controller.isAnimating) { engineLayer = builder.pushTransform( _lastTransform!.storage, oldLayer: engineLayer as ui.TransformEngineLayer?, ); addChildrenToScene(builder); builder.pop(); } _lastOffset = layerOffset; _inverseDirty = true; } @override void applyTransform(Layer? child, Matrix4 transform) { assert(child != null); assert(transform != null); transform.multiply(_lastTransform!); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<LocalHeroController>( 'controller', controller, )); properties.add(TransformProperty( 'transform', getLastTransform(), defaultValue: null, )); } }
FrankDomburg/local_hero
<|start_filename|>src/test/java/net/mguenther/kafka/junit/EmbeddedKafkaConfigTest.java<|end_filename|> package net.mguenther.kafka.junit; import kafka.server.KafkaConfig$; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.Properties; import static org.assertj.core.api.Assertions.assertThat; class EmbeddedKafkaConfigTest { @Test @DisplayName("should use defaults if not explicitly overridden") void shouldUseDefaultsIfNotOverridden() { final EmbeddedKafkaConfig config = EmbeddedKafkaConfig.defaultBrokers(); final Properties props = config.getBrokerProperties(); assertThat(props.get(KafkaConfig$.MODULE$.ZkSessionTimeoutMsProp())).isEqualTo("8000"); assertThat(props.get(KafkaConfig$.MODULE$.ZkConnectionTimeoutMsProp())).isEqualTo("10000"); assertThat(props.get(KafkaConfig$.MODULE$.NumPartitionsProp())).isEqualTo("1"); assertThat(props.get(KafkaConfig$.MODULE$.AutoCreateTopicsEnableProp())).isEqualTo("true"); assertThat(props.get(KafkaConfig$.MODULE$.MessageMaxBytesProp())).isEqualTo("1000000"); assertThat(props.get(KafkaConfig$.MODULE$.ControlledShutdownEnableProp())).isEqualTo("true"); assertThat(props.get(KafkaConfig$.MODULE$.OffsetsTopicReplicationFactorProp())).isEqualTo("1"); assertThat(props.get(KafkaConfig$.MODULE$.GroupInitialRebalanceDelayMsProp())).isEqualTo(0); assertThat(props.get(KafkaConfig$.MODULE$.TransactionsTopicReplicationFactorProp())).isEqualTo("1"); assertThat(props.get(KafkaConfig$.MODULE$.TransactionsTopicMinISRProp())).isEqualTo("1"); } @Test @DisplayName("with(param) should override the corresponding default setting") void withShouldOverrideDefaultSetting() { final EmbeddedKafkaConfig config = EmbeddedKafkaConfig .brokers() .with(KafkaConfig$.MODULE$.AdvertisedListenersProp(), "localhost:9092") .build(); final Properties props = config.getBrokerProperties(); assertThat(props.get(KafkaConfig$.MODULE$.AdvertisedListenersProp())).isEqualTo("localhost:9092"); } @Test @DisplayName("withAll(params) should override the corresponding default settings") void withAllShouldOverrideDefaultSettings() { final Properties overrides = new Properties(); overrides.put(KafkaConfig$.MODULE$.AdvertisedListenersProp(), "localhost:9092"); overrides.put(KafkaConfig$.MODULE$.NumPartitionsProp(), "2"); final EmbeddedKafkaConfig config = EmbeddedKafkaConfig .brokers() .withAll(overrides) .build(); final Properties props = config.getBrokerProperties(); assertThat(props.get(KafkaConfig$.MODULE$.AdvertisedListenersProp())).isEqualTo("localhost:9092"); assertThat(props.get(KafkaConfig$.MODULE$.NumPartitionsProp())).isEqualTo("2"); } @Test @DisplayName("should yield listeners for multiple brokers") void shouldYieldListenersForMultipleBrokers() { final EmbeddedKafkaConfig config = EmbeddedKafkaConfig .brokers() .withNumberOfBrokers(3) .build(); assertThat(config.listenerFor(0)).startsWith("PLAINTEXT://localhost"); assertThat(config.listenerFor(1)).startsWith("PLAINTEXT://localhost"); assertThat(config.listenerFor(2)).startsWith("PLAINTEXT://localhost"); } @Test @DisplayName("should yield default listener for single broker") void shouldYieldDefaultListenerForSingleBroker() { final EmbeddedKafkaConfig config = EmbeddedKafkaConfig.defaultBrokers(); assertThat(config.listenerFor(0)).isEqualTo("PLAINTEXT://localhost:9092"); } } <|start_filename|>src/test/java/net/mguenther/kafka/junit/ExternalKafkaClusterTest.java<|end_filename|> package net.mguenther.kafka.junit; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.testcontainers.containers.KafkaContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import java.util.ArrayList; import java.util.List; import static net.mguenther.kafka.junit.ObserveKeyValues.on; import static net.mguenther.kafka.junit.SendKeyValues.to; @Testcontainers class ExternalKafkaClusterTest { @Container private KafkaContainer kafkaContainer = new KafkaContainer(); @Test @DisplayName("should be able to observe records written to an external Kafka cluster") void externalKafkaClusterShouldWorkWithExternalResources() throws Exception { final ExternalKafkaCluster kafka = ExternalKafkaCluster.at(kafkaContainer.getBootstrapServers()); final List<KeyValue<String, String>> records = new ArrayList<>(); records.add(new KeyValue<>("aggregate", "a")); records.add(new KeyValue<>("aggregate", "b")); records.add(new KeyValue<>("aggregate", "c")); kafka.send(to("test-topic", records)); kafka.observe(on("test-topic", 3).useDefaults()); } } <|start_filename|>src/test/java/net/mguenther/kafka/junit/SendValuesTransactionalTest.java<|end_filename|> package net.mguenther.kafka.junit; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.IntegerSerializer; import org.apache.kafka.common.serialization.StringSerializer; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.Properties; import static org.assertj.core.api.Assertions.assertThat; class SendValuesTransactionalTest { @Test @DisplayName("should preserve constructor arguments") void shouldPreserveConstructorArguments() { final SendValuesTransactional<String> sendRequest = SendValuesTransactional .inTransaction("test-topic", Collections.singletonList("a")) .useDefaults(); assertThat(sendRequest.getValuesPerTopic().containsKey("test-topic")).isTrue(); assertThat(sendRequest.getValuesPerTopic().get("test-topic").contains("a")).isTrue(); } @Test @DisplayName("should be able to close over records for multiple topics") void shouldBeAbleToCloseOverRecordsForMultipleTopics() { final SendValuesTransactional<String> sendRequest = SendValuesTransactional .inTransaction("test-topic", Collections.singletonList("a")) .inTransaction("test-topic-2", Collections.singletonList("b")) .useDefaults(); assertThat(sendRequest.getValuesPerTopic().containsKey("test-topic-2")).isTrue(); assertThat(sendRequest.getValuesPerTopic().get("test-topic-2").contains("b")).isTrue(); } @Test @DisplayName("should use defaults if not overridden") void shouldUseDefaultsIfNotOverridden() { final SendValuesTransactional<String> sendRequest = SendValuesTransactional .inTransaction("test-topic", Collections.singletonList("a")) .useDefaults(); final Properties props = sendRequest.getProducerProps(); assertThat(props.get(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)).isEqualTo(StringSerializer.class); assertThat(props.get(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)).isEqualTo(StringSerializer.class); assertThat(sendRequest.shouldFailTransaction()).isFalse(); } @Test @DisplayName("should preserve fail transaction setting if overridden") void shouldPreserveFailTransactionSettingIfOverridden() { final SendValuesTransactional<String> sendRequest = SendValuesTransactional .inTransaction("test-topic", Collections.singletonList("a")) .failTransaction() .build(); assertThat(sendRequest.shouldFailTransaction()).isTrue(); } @Test @DisplayName("with should override default setting of given parameter with the given value") void withShouldOverrideDefaultSetting() { final SendValuesTransactional<Integer> sendRequest = SendValuesTransactional .inTransaction("test-topic", Collections.singletonList(1)) .with(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class) .build(); final Properties props = sendRequest.getProducerProps(); assertThat(props.get(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)).isEqualTo(IntegerSerializer.class); } @Test @DisplayName("withAll should override default settings of given parameters with the resp. values") void withAllShouldOverrideDefaultSettings() { final Properties overrides = new Properties(); overrides.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class); final SendValuesTransactional<Integer> sendRequest = SendValuesTransactional .inTransaction("test-topic", Collections.singletonList(1)) .withAll(overrides) .build(); final Properties props = sendRequest.getProducerProps(); assertThat(props.get(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)).isEqualTo(IntegerSerializer.class); } } <|start_filename|>src/test/java/net/mguenther/kafka/junit/SingleBrokerTest.java<|end_filename|> package net.mguenther.kafka.junit; import kafka.server.KafkaConfig$; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static net.mguenther.kafka.junit.EmbeddedKafkaCluster.provisionWith; import static net.mguenther.kafka.junit.EmbeddedKafkaClusterConfig.newClusterConfig; import static net.mguenther.kafka.junit.EmbeddedKafkaConfig.brokers; import static org.assertj.core.api.Assertions.assertThat; @Slf4j class SingleBrokerTest { private EmbeddedKafkaCluster kafka; @BeforeEach void prepareEnvironment() { kafka = provisionWith(newClusterConfig() .configure(brokers() .withNumberOfBrokers(1) .with(KafkaConfig$.MODULE$.ListenersProp(), "PLAINTEXT://localhost:9093"))); kafka.start(); } @AfterEach void tearDownEnvironment() { if (kafka != null) kafka.stop(); } @Test @DisplayName("should be able to override listener and switch to another local port") void shouldBeAbleToOverrideListenerAndSwitchToAnotherLocalPort() { assertThat(kafka.getBrokerList()).contains("localhost:9093"); } } <|start_filename|>src/test/java/net/mguenther/kafka/junit/ObserveKeyValuesTest.java<|end_filename|> package net.mguenther.kafka.junit; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.common.serialization.StringDeserializer; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.Properties; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; class ObserveKeyValuesTest { @Test @DisplayName("should preserve constructor arguments") void shouldPreserveConstructorArguments() { final ObserveKeyValues<String, String> observeRequest = ObserveKeyValues.on("test", 10).useDefaults(); assertThat(observeRequest.getTopic()).isEqualTo("test"); assertThat(observeRequest.getExpected()).isEqualTo(10); assertThat(observeRequest.getObservationTimeMillis()).isEqualTo(ObserveKeyValues.DEFAULT_OBSERVATION_TIME_MILLIS); } @Test @DisplayName("should use defaults if not overridden") void shouldUseDefaultsIfNotOverridden() { final ObserveKeyValues<String, String> observeRequest = ObserveKeyValues.on("test", 10).useDefaults(); final Properties props = observeRequest.getConsumerProps(); assertThat(props.get(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG)).isEqualTo("earliest"); assertThat(props.get(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG)).isEqualTo(false); assertThat(props.get(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG)).isEqualTo(StringDeserializer.class); assertThat(props.get(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG)).isEqualTo(StringDeserializer.class); assertThat(props.get(ConsumerConfig.MAX_POLL_RECORDS_CONFIG)).isEqualTo(100); assertThat(props.get(ConsumerConfig.ISOLATION_LEVEL_CONFIG)).isEqualTo("read_uncommitted"); assertThat(observeRequest.isIncludeMetadata()).isFalse(); assertThat(observeRequest.getSeekTo().isEmpty()).isTrue(); } @Test @DisplayName("observeFor should override default observation time") void observeForShouldOverrideDefaultObservationTime() { final ObserveKeyValues<String, String> observeRequest = ObserveKeyValues.on("test", 10) .observeFor(10, TimeUnit.SECONDS) .build(); assertThat(observeRequest.getObservationTimeMillis()).isEqualTo((int) TimeUnit.SECONDS.toMillis(10)); } @Test @DisplayName("with should override default setting of the given parameter with the given value") void withShouldOverrideDefaultSetting() { final ObserveKeyValues<String, String> observeRequest = ObserveKeyValues.on("test", 10) .with(ConsumerConfig.ISOLATION_LEVEL_CONFIG, "read_committed") .build(); assertThat(observeRequest.getConsumerProps().get(ConsumerConfig.ISOLATION_LEVEL_CONFIG)).isEqualTo("read_committed"); } @Test @DisplayName("withAll should override the default settings of the given parameters with the resp. values") void withAllShouldOverrideDefaultSettings() { final Properties overrides = new Properties(); overrides.put(ConsumerConfig.ISOLATION_LEVEL_CONFIG, "read_committed"); overrides.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 1000L); final ObserveKeyValues<String, String> observeRequest = ObserveKeyValues.on("test", 10) .withAll(overrides) .build(); assertThat(observeRequest.getConsumerProps().get(ConsumerConfig.ISOLATION_LEVEL_CONFIG)).isEqualTo("read_committed"); assertThat(observeRequest.getConsumerProps().get(ConsumerConfig.MAX_POLL_RECORDS_CONFIG)).isEqualTo(1000L); } @Test @DisplayName("includeMetadata should override its default setting") void includeMetadataShouldOverrideItsDefaultSetting() { final ObserveKeyValues<String, String> observeRequest = ObserveKeyValues.on("test", 10) .includeMetadata() .build(); assertThat(observeRequest.isIncludeMetadata()).isTrue(); } @Test @DisplayName("seekTo should preserve seek settings") void seekToShouldPreserveSeekSettings() { final ObserveKeyValues<String, String> observeRequest = ObserveKeyValues.on("test", 10) .seekTo(0, 1L) .seekTo(Collections.singletonMap(1, 2L)) .build(); assertThat(observeRequest.getSeekTo().size()).isEqualTo(2); assertThat(observeRequest.getSeekTo().get(0)).isEqualTo(1L); assertThat(observeRequest.getSeekTo().get(1)).isEqualTo(2L); } } <|start_filename|>src/test/java/net/mguenther/kafka/junit/TopicManagerTest.java<|end_filename|> package net.mguenther.kafka.junit; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.Map; import java.util.Properties; import java.util.UUID; import static net.mguenther.kafka.junit.EmbeddedKafkaCluster.provisionWith; import static net.mguenther.kafka.junit.EmbeddedKafkaClusterConfig.defaultClusterConfig; import static net.mguenther.kafka.junit.TopicConfig.withName; import static net.mguenther.kafka.junit.Wait.delay; import static org.assertj.core.api.Assertions.assertThat; @Slf4j class TopicManagerTest { private EmbeddedKafkaCluster kafka; @BeforeEach void prepareEnvironment() { kafka = provisionWith(defaultClusterConfig()); kafka.start(); } @AfterEach void tearDownEnvironment() { if (kafka != null) kafka.stop(); } @Test @DisplayName("should be able to create topics and mark them for deletion") void shouldBeAbleToCreateTopicsAndMarkThemForDeletion() { kafka.createTopic(withName("test-topic")); assertThat(kafka.exists("test-topic")).isTrue(); // the topic will not be deleted immediately, but "marked for deletion" // hence a check on exists would return "false" directly after deleting // the topic kafka.deleteTopic("test-topic"); } @Test @DisplayName("fetchLeaderAndIsr should retrieve the in-sync replica set") void fetchLeaderAndIsrShouldRetrieveTheIsr() throws Exception { kafka.createTopic(withName("test-topic") .withNumberOfPartitions(5) .withNumberOfReplicas(1)); // it takes a couple of seconds until topic-partition assignments are there delay(5); Map<Integer, LeaderAndIsr> isr = kafka.fetchLeaderAndIsr("test-topic"); assertThat(isr.size()).isEqualTo(5); assertThat(isr.values().stream().allMatch(lai -> lai.getLeader() == 1)).isTrue(); } @Test @DisplayName("fetchTopicConfig should retrieve the proper config") void fetchTopicConfigShouldRetrieveTheProperConfig() throws Exception { kafka.createTopic(withName("test-topic") .with("min.insync.replicas", "1")); delay(3); Properties topicConfig = kafka.fetchTopicConfig("test-topic"); assertThat(topicConfig.getProperty("min.insync.replicas")).isEqualTo("1"); } @Test @DisplayName("fetchTopicConfig should throw a RuntimeException if the topic does not exist") void fetchTopicConfigShouldThrowRuntimeExceptionIfTopicDoesNotExist() { Assertions.assertThrows(RuntimeException.class, () -> kafka.fetchTopicConfig(UUID.randomUUID().toString())); } } <|start_filename|>src/test/java/net/mguenther/kafka/junit/RecordConsumerTest.java<|end_filename|> package net.mguenther.kafka.junit; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.header.Headers; import org.apache.kafka.common.header.internals.RecordHeaders; import org.apache.kafka.common.serialization.IntegerDeserializer; import org.apache.kafka.common.serialization.IntegerSerializer; import org.apache.kafka.common.serialization.LongDeserializer; import org.apache.kafka.common.serialization.LongSerializer; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.util.Arrays.asList; import static net.mguenther.kafka.junit.EmbeddedKafkaCluster.provisionWith; import static net.mguenther.kafka.junit.EmbeddedKafkaClusterConfig.defaultClusterConfig; import static net.mguenther.kafka.junit.ReadKeyValues.from; import static net.mguenther.kafka.junit.SendKeyValues.to; import static org.assertj.core.api.Assertions.assertThat; class RecordConsumerTest { private EmbeddedKafkaCluster kafka; @BeforeEach void prepareEnvironment() throws Exception { kafka = provisionWith(defaultClusterConfig()); kafka.start(); final List<KeyValue<String, String>> records = asList( new KeyValue<>("aggregate", "a"), new KeyValue<>("aggregate", "b"), new KeyValue<>("aggregate", "c")); kafka.send(to("test-topic", records)); } @AfterEach void tearDownEnvironment() { if (kafka != null) kafka.stop(); } @Test @DisplayName("readValues should consume only values from previously sent records") void readValuesConsumesOnlyValuesFromPreviouslySentRecords() throws Exception { final List<String> values = kafka.readValues(from("test-topic")); assertThat(values.size()).isEqualTo(3); } @Test @DisplayName("read should consume only values from previously sent records") void readConsumesPreviouslySentRecords() throws Exception { final List<KeyValue<String, String>> consumedRecords = kafka.read(from("test-topic")); assertThat(consumedRecords.size()).isEqualTo(3); } @Test @DisplayName("read should consume only values with a custom type that have been sent previously") void readConsumesPreviouslySentCustomValueTypedRecords() throws Exception { final List<KeyValue<String, Long>> records = asList( new KeyValue<>("min", Long.MIN_VALUE), new KeyValue<>("max", Long.MAX_VALUE)); kafka.send(to("test-topic-value-types", records) .with(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, LongSerializer.class)); final List<KeyValue<String, Long>> consumedRecords = kafka.read(from("test-topic-value-types", Long.class) .with(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class)); assertThat(consumedRecords.size()).isEqualTo(records.size()); } @Test @DisplayName("read should only consume records with custom types for key and values that have been sent previously") void readConsumesPreviouslySentCustomKeyValueTypedRecords() throws Exception { final List<KeyValue<Integer, Long>> records = asList( new KeyValue<>(1, Long.MIN_VALUE), new KeyValue<>(2, Long.MAX_VALUE)); kafka.send(to("test-topic-key-value-types", records) .with(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class) .with(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, LongSerializer.class)); final List<KeyValue<Integer, Long>> consumedRecords = kafka.read(from("test-topic-key-value-types", Integer.class, Long.class) .with(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class) .with(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class)); assertThat(consumedRecords.size()).isEqualTo(records.size()); } @Test @DisplayName("read should only consume records that pass the key filter") void readConsumesOnlyRecordsThatPassKeyFilter() throws Exception { final List<KeyValue<String, Integer>> records = asList( new KeyValue<>("1", 1), new KeyValue<>("2", 2), new KeyValue<>("3", 3), new KeyValue<>("4", 4)); kafka.send(to("test-topic-key-filter", records) .with(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class)); final Predicate<String> keyFilter = k -> Integer.parseInt(k) % 2 == 0; final List<KeyValue<String, Integer>> consumedRecords = kafka.read(from("test-topic-key-filter", Integer.class) .with(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class) .filterOnKeys(keyFilter)); assertThat(consumedRecords.size()).isEqualTo(2); assertThat(consumedRecords.stream().map(KeyValue::getKey).allMatch(keyFilter)).isTrue(); } @Test @DisplayName("read should only consume those records that pass the value filter") void readConsumesOnlyRecordsThatPassValueFilter() throws Exception { final List<KeyValue<String, Integer>> records = asList( new KeyValue<>("1", 1), new KeyValue<>("2", 2), new KeyValue<>("3", 3), new KeyValue<>("4", 4)); kafka.send(to("test-topic-value-filter", records) .with(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class)); final Predicate<Integer> valueFilter = v -> v % 2 == 1; final List<KeyValue<String, Integer>> consumedRecords = kafka.read(from("test-topic-value-filter", Integer.class) .with(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class) .filterOnValues(valueFilter)); assertThat(consumedRecords.size()).isEqualTo(2); assertThat(consumedRecords.stream().map(KeyValue::getValue).allMatch(valueFilter)).isTrue(); } @Test @DisplayName("read should only consume those records that pass the header filter") void readConsumesOnlyRecordsThatPassHeaderFilter() throws Exception { final Headers headersA = new RecordHeaders().add("aggregate", "a".getBytes()); final Headers headersB = new RecordHeaders().add("aggregate", "b".getBytes()); final List<KeyValue<String, Integer>> records = asList( new KeyValue<>("1", 1, headersA), new KeyValue<>("2", 2, headersB)); kafka.send(to("test-topic-header-filter", records) .with(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class)); final Predicate<Headers> headerFilter = headers -> new String(headers.lastHeader("aggregate").value()).equals("a"); final List<KeyValue<String, Integer>> consumedRecords = kafka.read(from("test-topic-header-filter", Integer.class) .with(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class) .filterOnHeaders(headerFilter)); assertThat(consumedRecords.size()).isEqualTo(1); assertThat(new String(consumedRecords.get(0).getHeaders().lastHeader("aggregate").value())).isEqualTo("a"); } @Test @DisplayName("read should only consume those records that pass both key and value filter") void readConsumesOnlyRecordsThatPassBothKeyAndValueFilter() throws Exception { List<KeyValue<String, Integer>> records = Stream.iterate(1, k -> k + 1) .limit(30) .map(i -> new KeyValue<>(String.format("%s", i), i)) .collect(Collectors.toList()); SendKeyValues<String, Integer> sendRequest = to("test-topic-key-value-filter", records) .with(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class) .build(); kafka.send(sendRequest); Predicate<String> keyFilter = k -> Integer.parseInt(k) % 3 == 0; Predicate<Integer> valueFilter = v -> v % 5 == 0; ReadKeyValues<String, Integer> readRequest = from("test-topic-key-value-filter", Integer.class) .with(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class) .filterOnKeys(keyFilter) .filterOnValues(valueFilter) .build(); List<KeyValue<String, Integer>> consumedRecords = kafka.read(readRequest); Predicate<KeyValue<String, Integer>> combinedFilter = kv -> keyFilter.test(kv.getKey()) && valueFilter.test(kv.getValue()); assertThat(consumedRecords.size()).isEqualTo(2); assertThat(consumedRecords.stream().allMatch(combinedFilter)).isTrue(); } @Test @DisplayName("readValues should only consume those records that pass the header filter") void readValuesConsumesOnlyRecordsThatPassHeaderFilter() throws Exception { Headers headersA = new RecordHeaders().add("aggregate", "a".getBytes()); Headers headersB = new RecordHeaders().add("aggregate", "b".getBytes()); List<KeyValue<String, Integer>> records = new ArrayList<>(); records.add(new KeyValue<>("1", 1, headersA)); records.add(new KeyValue<>("2", 2, headersB)); SendKeyValues<String, Integer> sendRequest = to("test-topic-header-filter", records) .with(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class) .build(); kafka.send(sendRequest); Predicate<Headers> headerFilter = headers -> new String(headers.lastHeader("aggregate").value()).equals("a"); ReadKeyValues<String, Integer> readRequest = from("test-topic-header-filter", Integer.class) .with(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class) .filterOnHeaders(headerFilter) .build(); List<Integer> values = kafka.readValues(readRequest); assertThat(values.size()).isEqualTo(1); assertThat(values.get(0)).isEqualTo(1); } @Test @DisplayName("observe should wait until the requested number of records have been consumed") void observeWaitsUntilRequestedNumberOfRecordsHaveBeenConsumed() throws Exception { ObserveKeyValues<String, String> observeRequest = ObserveKeyValues.on("test-topic", 3).useDefaults(); int observedRecords = kafka.observe(observeRequest).size(); assertThat(observedRecords).isEqualTo(3); } @Test @DisplayName("observe should throw an AssertionError if its timeout elapses") void observeThrowsAnAssertionErrorIfTimeoutElapses() throws Exception { ObserveKeyValues<String, String> observeRequest = ObserveKeyValues.on("test-topic", 4) .observeFor(5, TimeUnit.SECONDS) .build(); Assertions.assertThrows(AssertionError.class, () -> kafka.observe(observeRequest)); } @Test @DisplayName("observe should wait until the requested number of records with a custom type have been consumed") void observeWaitsUntilRequestedNumberOfCustomValueTypedRecordsHaveBeenConsumed() throws Exception { List<KeyValue<String, Long>> records = new ArrayList<>(); records.add(new KeyValue<>("min", Long.MIN_VALUE)); records.add(new KeyValue<>("max", Long.MAX_VALUE)); SendKeyValues<String, Long> sendRequest = to("test-topic-value-types", records) .with(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, LongSerializer.class) .build(); kafka.send(sendRequest); ObserveKeyValues<String, Long> observeRequest = ObserveKeyValues.on("test-topic-value-types", 2, Long.class) .with(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class) .build(); int observedRecords = kafka.observe(observeRequest).size(); assertThat(observedRecords).isEqualTo(2); } @Test @DisplayName("observe should wait until the requested number of records with custom key and value have been consumed") void observeWaitsUntilRequestedNumberOfCustomKeyValueTypedRecordsHaveBeenConsumed() throws Exception { List<KeyValue<Integer, Long>> records = new ArrayList<>(); records.add(new KeyValue<>(1, Long.MIN_VALUE)); records.add(new KeyValue<>(2, Long.MAX_VALUE)); SendKeyValues<Integer, Long> sendRequest = to("test-topic-key-value-types", records) .with(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class) .with(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, LongSerializer.class) .build(); kafka.send(sendRequest); ObserveKeyValues<Integer, Long> observeRequest = ObserveKeyValues.on("test-topic-key-value-types", 2, Integer.class, Long.class) .with(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class) .with(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, LongDeserializer.class) .build(); int observedRecords = kafka.observe(observeRequest).size(); assertThat(observedRecords).isEqualTo(2); } @Test @DisplayName("observe should wait until the requested number of filtered records have been consumed") void observeWaitsUntilRequestedNumberOfFilteredRecordsHaveBeenConsumed() throws Exception { List<KeyValue<String, Integer>> records = Stream.iterate(1, k -> k + 1) .limit(30) .map(i -> new KeyValue<>(String.format("%s", i), i)) .collect(Collectors.toList()); SendKeyValues<String, Integer> sendRequest = to("test-topic-key-value-filter", records) .with(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class) .build(); kafka.send(sendRequest); Predicate<String> keyFilter = k -> Integer.parseInt(k) % 3 == 0; Predicate<Integer> valueFilter = v -> v % 5 == 0; ObserveKeyValues<String, Integer> observeRequest = ObserveKeyValues.on("test-topic-key-value-filter", 2, Integer.class) .with(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class) .observeFor(5, TimeUnit.SECONDS) .filterOnKeys(keyFilter) .filterOnValues(valueFilter) .build(); List<KeyValue<String, Integer>> observedRecords = kafka.observe(observeRequest); Predicate<KeyValue<String, Integer>> combinedFilter = kv -> keyFilter.test(kv.getKey()) && valueFilter.test(kv.getValue()); assertThat(observedRecords.stream().allMatch(combinedFilter)).isTrue(); } @Test @DisplayName("observe should retain header filters") void observeShouldRetainHeaderFilters() throws Exception { Headers headersA = new RecordHeaders().add("aggregate", "a".getBytes()); Headers headersB = new RecordHeaders().add("aggregate", "b".getBytes()); List<KeyValue<String, Integer>> records = new ArrayList<>(); records.add(new KeyValue<>("1", 1, headersA)); records.add(new KeyValue<>("2", 2, headersB)); SendKeyValues<String, Integer> sendRequest = to("test-topic-header-filter", records) .with(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class) .build(); kafka.send(sendRequest); Predicate<Headers> headerFilter = headers -> new String(headers.lastHeader("aggregate").value()).equals("b"); ObserveKeyValues<String, Integer> observeRequest = ObserveKeyValues.on("test-topic-header-filter", 1, Integer.class) .with(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class) .observeFor(5, TimeUnit.SECONDS) .filterOnHeaders(headerFilter) .build(); List<KeyValue<String, Integer>> observedRecords = kafka.observe(observeRequest); assertThat(observedRecords.size()).isEqualTo(1); assertThat(observedRecords.get(0).getValue()).isEqualTo(2); } @Test @DisplayName("observe should throw an AssertionError if no record passes the filter and its timeout elapses") void observeShouldThrowAnAssertionErrorIfNoRecordPassesTheFilterAndTimeoutElapses() throws Exception { List<KeyValue<String, Integer>> records = new ArrayList<>(); records.add(new KeyValue<>("1", 1)); records.add(new KeyValue<>("2", 2)); records.add(new KeyValue<>("3", 3)); records.add(new KeyValue<>("4", 4)); SendKeyValues<String, Integer> sendRequest = to("test-topic-key-value-filter", records) .with(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class) .build(); kafka.send(sendRequest); Predicate<String> keyFilter = k -> Integer.parseInt(k) % 2 == 0; Predicate<Integer> valueFilter = v -> v % 2 == 1; ObserveKeyValues<String, Integer> observeRequest = ObserveKeyValues.on("test-topic-key-value-filter", 1, Integer.class) .with(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class) .observeFor(5, TimeUnit.SECONDS) .filterOnKeys(keyFilter) .filterOnValues(valueFilter) .build(); Assertions.assertThrows(AssertionError.class, () -> { kafka.observe(observeRequest); }); } @Test @DisplayName("observe should throw an AssertionError if no record passes the header filter and its timeout elapses") void observeShouldThrowAnAssertionErrorIfNoRecordPassesTheHeaderFilterAndTimeoutElapses() throws Exception { Headers headersA = new RecordHeaders().add("aggregate", "a".getBytes()); Headers headersB = new RecordHeaders().add("aggregate", "b".getBytes()); List<KeyValue<String, Integer>> records = new ArrayList<>(); records.add(new KeyValue<>("1", 1, headersA)); records.add(new KeyValue<>("2", 2, headersB)); SendKeyValues<String, Integer> sendRequest = to("test-topic-header-filter", records) .with(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class) .build(); kafka.send(sendRequest); Predicate<Headers> headerFilter = headers -> new String(headers.lastHeader("aggregate").value()).equals("c"); // not existing ObserveKeyValues<String, Integer> observeRequest = ObserveKeyValues.on("test-topic-header-filter", 1, Integer.class) .with(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, IntegerDeserializer.class) .observeFor(5, TimeUnit.SECONDS) .filterOnHeaders(headerFilter) .build(); Assertions.assertThrows(AssertionError.class, () -> kafka.observe(observeRequest)); } @Test @DisplayName("read should include record metadata if explicitly enabled") void readShouldIncludeMetadataIfExplicitlyEnabled() throws Exception { ReadKeyValues<String, String> readRequest = from("test-topic") .includeMetadata() .build(); List<KeyValue<String, String>> records = kafka.read(readRequest); assertThat(records.stream().allMatch(kv -> kv.getMetadata().isPresent())) .withFailMessage("All records must include a reference to the topic-partition-offset if includeMetadata is set to true.") .isTrue(); assertThat(records .stream() .map(KeyValue::getMetadata) .map(Optional::get) .map(KeyValueMetadata::getTopic) .allMatch(topic -> topic.equalsIgnoreCase("test-topic"))) .withFailMessage("All records must include a reference to topic 'test-topic'.") .isTrue(); assertThat(records .stream() .map(KeyValue::getMetadata) .map(Optional::get) .map(KeyValueMetadata::getPartition) .allMatch(partition -> partition == 0)) .withFailMessage("All records must include the correct topic-partition.") .isTrue(); assertThat(records .stream() .map(KeyValue::getMetadata) .map(Optional::get) .map(KeyValueMetadata::getOffset) .allMatch(offset -> offset >= 0)) .withFailMessage("All records must include non-negative partition offsets.") .isTrue(); } @Test @DisplayName("read should not include any record metadata if not enabled") void readShouldNotIncludeMetadataIfNotExplicitlyEnabled() throws Exception { ReadKeyValues<String, String> readRequest = from("test-topic").useDefaults(); List<KeyValue<String, String>> records = kafka.read(readRequest); assertThat(records.stream().noneMatch(kv -> kv.getMetadata().isPresent())) .withFailMessage("None of the returned record must include a reference to topic-partition-offset.") .isTrue(); } @Test @DisplayName("observe should include record metadata if explicitly enabled") void observeShouldIncludeMetadataIfExplicitlyEnabled() throws Exception { ObserveKeyValues<String, String> observeRequest = ObserveKeyValues.on("test-topic", 3) .includeMetadata() .build(); List<KeyValue<String, String>> records = kafka.observe(observeRequest); assertThat(records.stream().allMatch(kv -> kv.getMetadata().isPresent())) .withFailMessage("All records must include a reference to the topic-partition-offset if includeMetadata is set to true.") .isTrue(); assertThat(records .stream() .map(KeyValue::getMetadata) .map(Optional::get) .map(KeyValueMetadata::getTopic) .allMatch(topic -> topic.equalsIgnoreCase("test-topic"))) .withFailMessage("All records must include a reference to topic 'test-topic'.") .isTrue(); assertThat(records .stream() .map(KeyValue::getMetadata) .map(Optional::get) .map(KeyValueMetadata::getPartition) .allMatch(partition -> partition == 0)) .withFailMessage("All records must include the correct topic-partition.") .isTrue(); assertThat(records .stream() .map(KeyValue::getMetadata) .map(Optional::get) .map(KeyValueMetadata::getOffset) .allMatch(offset -> offset >= 0)) .withFailMessage("All records must include non-negative partition offsets.") .isTrue(); } @Test @DisplayName("observe should not include any record metadata if not enabled") void observeShouldNotIncludeMetadataIfNotExplicitlyEnabled() throws Exception { ObserveKeyValues<String, String> observeRequest = ObserveKeyValues.on("test-topic", 3).useDefaults(); List<KeyValue<String, String>> records = kafka.observe(observeRequest); assertThat(records.stream().noneMatch(kv -> kv.getMetadata().isPresent())) .withFailMessage("None of the returned record must include a reference to topic-partition-offset.") .isTrue(); } @Test @DisplayName("a seekTo prior to a call to read should skip all messages before the given offset") void seekToShouldSkipAllMessagesBeforeGivenOffsetWhenReadingKeyValues() throws Exception { ReadKeyValues<String, String> readRequest = from("test-topic").seekTo(0, 2).build(); List<KeyValue<String, String>> records = kafka.read(readRequest); assertThat(records.size()).isEqualTo(1); assertThat(records.get(0).getValue()).isEqualTo("c"); } @Test @DisplayName("a seekTo prior to a call to readValues should skip all messages before the given offset") void seekToShouldSkipAllMessagesBeforeGivenOffsetWhenReadingValues() throws Exception { ReadKeyValues<String, String> readRequest = from("test-topic").seekTo(0, 2).build(); List<String> records = kafka.readValues(readRequest); assertThat(records.size()).isEqualTo(1); assertThat(records.get(0)).isEqualTo("c"); } @Test @DisplayName("a seekTo prior to a call to observe should skip all messages before the given offset") void seekToShouldSkipAllMessagesBeforeGivenOffsetWhenObservingKeyValues() throws Exception { ObserveKeyValues<String, String> observeRequest = ObserveKeyValues.on("test-topic", 1).seekTo(0, 2).build(); List<KeyValue<String, String>> records = kafka.observe(observeRequest); assertThat(records.size()).isEqualTo(1); assertThat(records.get(0).getValue()).isEqualTo("c"); } @Test @DisplayName("a seekTo prior to a call to observeValues should skip all messages before the given offset") void seekToShouldSkipAllMessagesBeforeGivenOffsetWhenObservingValues() throws Exception { ObserveKeyValues<String, String> observeRequest = ObserveKeyValues.on("test-topic", 1).seekTo(0, 2).build(); List<String> records = kafka.observeValues(observeRequest); assertThat(records.size()).isEqualTo(1); assertThat(records.get(0)).isEqualTo("c"); } @Test @DisplayName("when observing key-value pairs a call to seekTo should not restart observation at the given offset for subsequent reads") void whenObservingKeyValuesSeekToShouldNotRestartObservationAtGivenOffsetForSubsequentReads() throws Exception { ObserveKeyValues<String, String> observeRequest = ObserveKeyValues.on("test-topic", 2) .seekTo(0, 2) .observeFor(5, TimeUnit.SECONDS) .build(); // if the implementation of observe would start over at the given offset, then we would the record with value // "c" multiple times until the expected number (in this case 2) is met. if this times out and throws an // AssertionError, the implementation works as expected. Assertions.assertThrows(AssertionError.class, () -> kafka.observe(observeRequest)); } @Test @DisplayName("when observing values a call to seekTo should not restart observation at the given offset for subsequent reads") void whenObservingValuesSeekToShouldNotRestartObservationAtGivenOffsetForSubsequentReads() throws Exception { ObserveKeyValues<String, String> observeRequest = ObserveKeyValues.on("test-topic", 2) .seekTo(0, 2) .observeFor(5, TimeUnit.SECONDS) .build(); // if the implementation of observe would start over at the given offset, then we would the record with value // "c" multiple times until the expected number (in this case 2) is met. if this times out and throws an // AssertionError, the implementation works as expected. Assertions.assertThrows(AssertionError.class, () -> kafka.observeValues(observeRequest)); } } <|start_filename|>src/test/java/net/mguenther/kafka/junit/MultipleBrokersTest.java<|end_filename|> package net.mguenther.kafka.junit; import kafka.server.KafkaConfig$; import lombok.extern.slf4j.Slf4j; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.errors.NotEnoughReplicasException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import static java.util.Collections.singletonList; import static net.mguenther.kafka.junit.EmbeddedKafkaCluster.provisionWith; import static net.mguenther.kafka.junit.EmbeddedKafkaClusterConfig.newClusterConfig; import static net.mguenther.kafka.junit.EmbeddedKafkaConfig.brokers; import static net.mguenther.kafka.junit.ObserveKeyValues.on; import static net.mguenther.kafka.junit.SendKeyValuesTransactional.inTransaction; import static net.mguenther.kafka.junit.SendValues.to; import static net.mguenther.kafka.junit.SendValuesTransactional.inTransaction; import static net.mguenther.kafka.junit.TopicConfig.withName; import static net.mguenther.kafka.junit.Wait.delay; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Fail.fail; @Slf4j class MultipleBrokersTest { private EmbeddedKafkaCluster kafka; @BeforeEach void prepareEnvironment() { kafka = provisionWith(newClusterConfig() .configure(brokers() .withNumberOfBrokers(3) .with(KafkaConfig$.MODULE$.TransactionsTopicReplicationFactorProp(), "1") .with(KafkaConfig$.MODULE$.TransactionsTopicMinISRProp(), "1"))); kafka.start(); } @AfterEach void tearDownEnvironment() { if (kafka != null) kafka.stop(); } @Test @DisplayName("multiple brokers should comprise the in-sync replica set of topics") void multipleBrokersCompriseTheInSyncReplicaSetOfTopics() throws Exception { kafka.createTopic(withName("test-topic") .withNumberOfPartitions(5) .withNumberOfReplicas(3)); delay(5); final Set<Integer> leaders = leaders("test-topic"); assertThat(leaders.size()).isEqualTo(3); assertThat(leaders.contains(1)).isTrue(); assertThat(leaders.contains(2)).isTrue(); assertThat(leaders.contains(3)).isTrue(); } @Test @DisplayName("disconnected broker leaves in-sync replica set of topic and rejoins it after re-joining the cluster") void disconnectedBrokerLeavesIsrOfTopicAndRejoinsItAfterReconnecting() throws Exception { kafka.createTopic(withName("test-topic") .withNumberOfPartitions(5) .withNumberOfReplicas(3)); delay(5); Set<Integer> leaders = leaders("test-topic"); assertThat(leaders.contains(1)).isTrue(); assertThat(leaders.contains(2)).isTrue(); assertThat(leaders.contains(3)).isTrue(); kafka.disconnect(1); delay(5); Set<Integer> leadersAfterDisconnect = leaders("test-topic"); assertThat(leadersAfterDisconnect.contains(1)).isFalse(); assertThat(leadersAfterDisconnect.contains(2)).isTrue(); assertThat(leadersAfterDisconnect.contains(3)).isTrue(); kafka.connect(1); delay(10); Set<Integer> leadersAfterReconnect = leaders("test-topic"); assertThat(leadersAfterReconnect.contains(1)).isTrue(); assertThat(leadersAfterReconnect.contains(2)).isTrue(); assertThat(leadersAfterReconnect.contains(3)).isTrue(); } @Test @DisplayName("should throw NotEnoughReplicasException when trying to send non-keyed records and ISR has fallen below its minimum size") void disconnectUntilIsrFallsBelowMinimumSizeShouldThrowNotEnoughReplicasExceptionWhenSendingValues() throws Exception { kafka.createTopic(withName("test-topic") .withNumberOfPartitions(5) .withNumberOfReplicas(3) .with("min.insync.replicas", "2")); delay(5); kafka.disconnectUntilIsrFallsBelowMinimumSize("test-topic"); delay(5); Assertions.assertThrows(NotEnoughReplicasException.class, () -> { kafka.send(to("test-topic", "A")); }); } @Test @DisplayName("should throw NotEnoughReplicasException when trying to send non-keyed records within a transaction and ISR has fallen below its minimum size") void disconnectUntilIsrFallsBelowMinimumSizeShouldThrowNotEnoughReplicasExceptionWhenSendingValuesTransactionally() throws Exception { kafka.createTopic(withName("test-topic") .withNumberOfPartitions(5) .withNumberOfReplicas(3) .with("min.insync.replicas", "2")); delay(5); kafka.disconnectUntilIsrFallsBelowMinimumSize("test-topic"); delay(5); Assertions.assertThrows(NotEnoughReplicasException.class, () -> { kafka.send(inTransaction("test-topic", "A") .with(ProducerConfig.RETRIES_CONFIG, 1)); }); } @Test @DisplayName("should throw NotEnoughReplicasException when trying to send keyed records and ISR has fallen below its minimum size") void disconnectUntilIsrFallsBelowMinimumSizeShouldThrowNotEnoughReplicasExceptionWhenSendingKeyValues() throws Exception { kafka.createTopic(withName("test-topic") .withNumberOfPartitions(5) .withNumberOfReplicas(3) .with("min.insync.replicas", "2")); delay(5); kafka.disconnectUntilIsrFallsBelowMinimumSize("test-topic"); delay(5); Assertions.assertThrows(NotEnoughReplicasException.class, () -> { kafka.send(SendKeyValues.to("test-topic", singletonList(new KeyValue<>("a", "A")))); }); } @Test @DisplayName("should throw NotEnoughReplicasException when trying to send keyed records within a transaction and ISR has fallen below its minimum size") void disconnectUntilIsrFallsBelowMinimumSizeShouldThrowNotEnoughReplicasExceptionWhenSendingKeyValuesTransactionally() throws Exception { kafka.createTopic(withName("test-topic") .withNumberOfPartitions(5) .withNumberOfReplicas(3) .with("min.insync.replicas", "2")); delay(5); kafka.disconnectUntilIsrFallsBelowMinimumSize("test-topic"); delay(5); Assertions.assertThrows(NotEnoughReplicasException.class, () -> { kafka.send(inTransaction("test-topic", singletonList(new KeyValue<>("a", "A"))) .with(ProducerConfig.RETRIES_CONFIG, 1)); }); } @Test @DisplayName("should be able to submit reords after restoring previously disconnected in-sync replica set") void shouldBeAbleToWriteRecordsAfterRestoringDisconnectedIsr() throws Exception { kafka.createTopic(withName("test-topic") .withNumberOfPartitions(5) .withNumberOfReplicas(3) .with("min.insync.replicas", "2")); delay(5); final Set<Integer> disconnectedBrokers = kafka.disconnectUntilIsrFallsBelowMinimumSize("test-topic"); delay(5); try { kafka.send(to("test-topic", "A")); fail("A NotEnoughReplicasException is expected, but has not been raised."); } catch (NotEnoughReplicasException e) { // ignore, this is expected } kafka.connect(disconnectedBrokers); delay(5); kafka.send(to("test-topic", "A")); kafka.observeValues(on("test-topic", 1)); } @Test @DisplayName("a re-enabled broker should bind to the same port as it was bound before") void reActivatedBrokersShouldBindToTheSamePortAsTheyWereBoundToBefore() throws Exception { kafka.createTopic(withName("test-topic") .withNumberOfPartitions(5) .withNumberOfReplicas(3) .with("min.insync.replicas", "2")); final List<String> brokersBeforeDisconnect = Arrays.asList(kafka.getBrokerList().split(",")); final Set<Integer> disconnectedBrokers = kafka.disconnectUntilIsrFallsBelowMinimumSize("test-topic"); assertThat(disconnectedBrokers.size()).isEqualTo(2); delay(5); kafka.connect(disconnectedBrokers); delay(5); final List<String> brokersAfterReconnect = Arrays.asList(kafka.getBrokerList().split(",")); assertThat(brokersAfterReconnect).containsAll(brokersBeforeDisconnect); assertThat(brokersBeforeDisconnect).containsAll(brokersAfterReconnect); } private Set<Integer> leaders(final String topic) { return kafka.fetchLeaderAndIsr(topic) .values() .stream() .peek(leaderAndIsr -> log.info("Assignment: {}", leaderAndIsr.toString())) .map(LeaderAndIsr::getLeader) .collect(Collectors.toSet()); } } <|start_filename|>src/test/java/net/mguenther/kafka/junit/EmbeddedZooKeeperConfigTest.java<|end_filename|> package net.mguenther.kafka.junit; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; class EmbeddedZooKeeperConfigTest { @Test @DisplayName("should use a randomly chosen port per default") void useDefaultsShouldUseRandomPort() { final EmbeddedZooKeeperConfig config = EmbeddedZooKeeperConfig.defaultZooKeeper(); assertThat(config.getPort()).isEqualTo(EmbeddedZooKeeperConfig.USE_RANDOM_ZOOKEEPER_PORT); } @Test @DisplayName("withPort should override the default port") void withPortShouldOverrideDefaultPort() { final EmbeddedZooKeeperConfig config = EmbeddedZooKeeperConfig .zooKeeper() .withPort(8090) .build(); assertThat(config.getPort()).isEqualTo(8090); } } <|start_filename|>src/test/java/net/mguenther/kafka/junit/RecordProducerTest.java<|end_filename|> package net.mguenther.kafka.junit; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.producer.ProducerConfig; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static net.mguenther.kafka.junit.EmbeddedKafkaCluster.provisionWith; import static net.mguenther.kafka.junit.EmbeddedKafkaClusterConfig.defaultClusterConfig; import static net.mguenther.kafka.junit.ObserveKeyValues.on; import static net.mguenther.kafka.junit.SendKeyValuesTransactional.inTransaction; import static net.mguenther.kafka.junit.SendValues.to; import static org.assertj.core.api.Assertions.assertThat; class RecordProducerTest { private EmbeddedKafkaCluster kafka; @BeforeEach void prepareEnvironment() { kafka = provisionWith(defaultClusterConfig()); kafka.start(); } @AfterEach void tearDownEnvironment() { if (kafka != null) kafka.stop(); } @Test @DisplayName("calling send with non-keyed records and default settings should write all given records to the target topic") void sendingUnkeyedRecordsWithDefaults() throws Exception { kafka.send(to("test-topic", "a", "b", "c")); assertThat(kafka.observeValues(on("test-topic", 3)).size()) .isEqualTo(3); } @Test @DisplayName("calling send with keyed records and default settings should write all given records to the target topic") void sendingKeyedRecordsWithDefaults() throws Exception { final List<KeyValue<String, String>> records = new ArrayList<>(); records.add(new KeyValue<>("aggregate", "a")); records.add(new KeyValue<>("aggregate", "b")); records.add(new KeyValue<>("aggregate", "c")); kafka.send(SendKeyValues.to("test-topic", records)); assertThat(kafka.observeValues(on("test-topic", 3)).size()) .isEqualTo(3); } @Test @DisplayName("calling send with non-keyed records and altered producer settings should write all given records to the target topic") void sendingUnkeyedRecordsWithAlteredProducerSettings() throws Exception { final SendValues<String> sendRequest = to("test-topic", "a", "b", "c") .with(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, "true") .with(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, "1") .build(); kafka.send(sendRequest); assertThat(kafka.observeValues(on("test-topic", 3)).size()) .isEqualTo(3); } @Test @DisplayName("calling send with keyed records within a transaction should write all given records to the target topic") void sendingKeyedRecordsWithinTransaction() throws Exception { final List<KeyValue<String, String>> records = new ArrayList<>(); records.add(new KeyValue<>("aggregate", "a")); records.add(new KeyValue<>("aggregate", "b")); records.add(new KeyValue<>("aggregate", "c")); kafka.send(inTransaction("test-topic", records)); kafka.observeValues(on("test-topic", 3)); } @Test @DisplayName("calling send with non-keyed records within a transaction should write all given records to the target topic") void sendingUnkeyedRecordsWithinTransaction() throws Exception { kafka.send(SendValuesTransactional.inTransaction("test-topic", asList("a", "b", "c"))); kafka.observeValues(on("test-topic", 3)); } @Test @DisplayName("calling send with non-keyed records for multiple topics should write all given records to the correct topic") void sendingUnkeyedRecordsToMultipleTopics() throws Exception { kafka.send(SendValuesTransactional .inTransaction("test-topic-1", asList("a", "b")) .inTransaction("test-topic-2", asList("c", "d"))); kafka.observeValues(on("test-topic-1", 2).useDefaults()); kafka.observeValues(on("test-topic-2", 2).useDefaults()); } @Test @DisplayName("record headers should be retained") void usingRecordHeaders() throws Exception { final KeyValue<String, String> record = new KeyValue<>("a", "b"); record.addHeader("client", "kafka-junit-test".getBytes(StandardCharsets.UTF_8)); kafka.send(SendKeyValues.to("test-topic", singletonList(record))); final List<KeyValue<String, String>> consumedRecords = kafka.read(ReadKeyValues.from("test-topic")); assertThat(consumedRecords.size()).isEqualTo(1); assertThat(new String(consumedRecords.get(0).getHeaders().lastHeader("client").value())).isEqualTo("kafka-junit-test"); } @Test @DisplayName("non-keyed records written during a failed transaction should not be visible by a transactional consumer") void valuesOfAbortedTransactionsShouldNotBeVisibleByTransactionalConsumer() throws Exception { kafka.send(SendValuesTransactional .inTransaction("test-topic", asList("a", "b")) .failTransaction()); Assertions.assertThrows(AssertionError.class, () -> kafka.observe(on("test-topic", 2) .with(ConsumerConfig.ISOLATION_LEVEL_CONFIG, "read_committed") .observeFor(5, TimeUnit.SECONDS) .build())); } @Test @DisplayName("keyed records written during a failed transaction should be not visible by a transactional consumer") void keyValuesOfAbortedTransactionsShouldNotBeVisibleByTransactionalConsumer() throws Exception { kafka.send(inTransaction("test-topic", singletonList(new KeyValue<>("a", "b"))).failTransaction()); Assertions.assertThrows(AssertionError.class, () -> kafka.observe(on("test-topic", 1) .with(ConsumerConfig.ISOLATION_LEVEL_CONFIG, "read_committed") .observeFor(5, TimeUnit.SECONDS))); } } <|start_filename|>src/main/java/net/mguenther/kafka/junit/EmbeddedKafka.java<|end_filename|> package net.mguenther.kafka.junit; import kafka.server.KafkaConfig; import kafka.server.KafkaConfig$; import kafka.server.KafkaServer; import kafka.utils.TestUtils; import lombok.extern.slf4j.Slf4j; import org.apache.kafka.common.network.ListenerName; import org.apache.kafka.common.security.auth.SecurityProtocol; import org.apache.kafka.common.utils.Time; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.Properties; import static org.apache.kafka.common.network.ListenerName.forSecurityProtocol; @Slf4j public class EmbeddedKafka implements EmbeddedLifecycle { private static final int UNDEFINED_BOUND_PORT = -1; private final int brokerId; private final Properties brokerConfig; private final Path logDirectory; private KafkaServer kafka; private int boundPort = UNDEFINED_BOUND_PORT; public EmbeddedKafka(final int brokerId, final String listener, final EmbeddedKafkaConfig config, final String zooKeeperConnectUrl) throws IOException { this.brokerId = brokerId; this.brokerConfig = new Properties(); this.brokerConfig.putAll(config.getBrokerProperties()); this.brokerConfig.put(KafkaConfig$.MODULE$.ListenersProp(), listener); this.brokerConfig.put(KafkaConfig$.MODULE$.ZkConnectProp(), zooKeeperConnectUrl); this.logDirectory = Files.createTempDirectory("kafka-junit"); this.brokerConfig.put(KafkaConfig$.MODULE$.BrokerIdProp(), brokerId); this.brokerConfig.put(KafkaConfig$.MODULE$.LogDirProp(), logDirectory.toFile().getAbsolutePath()); } @Override public void start() { activate(); } public void activate() { if (kafka != null) { log.info("The embedded Kafka broker with ID {} is already running.", brokerId); return; } try { log.info("Embedded Kafka broker with ID {} is starting.", brokerId); if (boundPort != UNDEFINED_BOUND_PORT) { this.brokerConfig.put(KafkaConfig$.MODULE$.ListenersProp(), String.format("PLAINTEXT://localhost:%s", boundPort)); } final KafkaConfig config = new KafkaConfig(brokerConfig, true); kafka = TestUtils.createServer(config, Time.SYSTEM); boundPort = kafka.boundPort(config.interBrokerListenerName()); log.info("The embedded Kafka broker with ID {} has been started. Its logs can be found at {}.", brokerId, logDirectory); } catch (Exception e) { throw new RuntimeException(String.format("Unable to start the embedded Kafka broker with ID %s.", brokerId), e); } } @Override public void stop() { if (kafka == null) { log.info("The embedded Kafka broker with ID {} is not running or was already shut down.", brokerId); return; } deactivate(); log.info("Removing working directory at {}. This directory contains Kafka logs for Kafka broker with ID {} as well.", logDirectory, brokerId); try { recursivelyDelete(logDirectory); } catch (IOException e) { log.warn("Unable to remove working directory at {}.", logDirectory); } log.info("The embedded Kafka broker with ID {} has been stopped.", brokerId); } private void recursivelyDelete(final Path path) throws IOException { Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, @SuppressWarnings("unused") BasicFileAttributes attrs) { file.toFile().delete(); return FileVisitResult.CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, @SuppressWarnings("unused") BasicFileAttributes attrs) { return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) { dir.toFile().delete(); return FileVisitResult.CONTINUE; } }); } public void deactivate() { if (kafka == null) return; boundPort = kafka.boundPort(ListenerName.forSecurityProtocol(SecurityProtocol.PLAINTEXT)); log.info("The embedded Kafka broker with ID {} is stopping.", brokerId); kafka.shutdown(); kafka.awaitShutdown(); kafka = null; } public String getBrokerList() { return String.format("localhost:%s", kafka.boundPort(forSecurityProtocol(SecurityProtocol.PLAINTEXT))); } public String getClusterId() { return kafka.clusterId(); } public Integer getBrokerId() { return brokerId; } public boolean isActive() { return kafka != null; } } <|start_filename|>src/test/java/net/mguenther/kafka/junit/PropsTest.java<|end_filename|> package net.mguenther.kafka.junit; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.Properties; import static org.assertj.core.api.Assertions.assertThat; class PropsTest { @Test @DisplayName("build should retain properties that were added using a call to with") void buildShouldRetainPreviouslyAddedPropertiesUsingWith() { final Properties props = Props.create().with("test", "some-value").build(); assertThat(props.getProperty("test")).isEqualTo("some-value"); } @Test @DisplayName("build should retain properties that were added using a call to withAll") void buildShouldRetainPreviouslyAddedPropertiesUsingWithAll() { final Properties props = Props.create().with("test", "some-value").build(); final Properties withAllProps = Props.create().withAll(props).build(); assertThat(withAllProps.getProperty("test")).isEqualTo("some-value"); } } <|start_filename|>src/test/java/net/mguenther/kafka/junit/KeyValueTest.java<|end_filename|> package net.mguenther.kafka.junit; import org.apache.kafka.common.header.Headers; import org.apache.kafka.common.header.internals.RecordHeaders; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.nio.charset.StandardCharsets; import static org.assertj.core.api.Assertions.assertThat; class KeyValueTest { @Test @DisplayName("should preserve added headers") void shouldPreserveAddedHeaders() { final KeyValue<String, String> keyValue = new KeyValue<>("k", "v"); keyValue.addHeader("headerName", "headerValue", StandardCharsets.UTF_8); assertThat(keyValue.getHeaders().lastHeader("headerName").value()).isEqualTo("headerValue".getBytes(StandardCharsets.UTF_8)); } @Test @DisplayName("should preserve headers given on construction") void shouldPreserveHeadersGivenOnConstruction() { final Headers headers = new RecordHeaders(); headers.add("headerName", "headerValue".getBytes(StandardCharsets.UTF_8)); final KeyValue<String, String> keyValue = new KeyValue<>("k", "v", headers); assertThat(keyValue.getHeaders().lastHeader("headerName").value()).isEqualTo("headerValue".getBytes(StandardCharsets.UTF_8)); } } <|start_filename|>src/test/java/net/mguenther/kafka/junit/ConnectorTest.java<|end_filename|> package net.mguenther.kafka.junit; import net.mguenther.kafka.junit.connector.InstrumentingConfigBuilder; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.Properties; import java.util.UUID; import static net.mguenther.kafka.junit.EmbeddedConnectConfig.kafkaConnect; import static net.mguenther.kafka.junit.EmbeddedKafkaCluster.provisionWith; import static net.mguenther.kafka.junit.EmbeddedKafkaClusterConfig.newClusterConfig; class ConnectorTest { private final String topic = String.format("topic-%s", UUID.randomUUID().toString()); private final String key = String.format("key-%s", UUID.randomUUID().toString()); private EmbeddedKafkaCluster kafka; @BeforeEach void prepareEnvironment() { kafka = provisionWith(newClusterConfig() .configure(kafkaConnect() .deployConnector(connectorConfig(topic, key)))); kafka.start(); } @AfterEach public void tearDownEnvironment() { if (kafka != null) kafka.stop(); } @Test @DisplayName("A given Kafka Connect connector should be provisioned and able to emit records") void connectorShouldBeProvisionedAndEmitRecords() throws Exception { kafka.observe(ObserveKeyValues.on(topic, 1) .filterOnKeys(k -> k.equalsIgnoreCase(key)) .build()); } private Properties connectorConfig(final String topic, final String key) { return InstrumentingConfigBuilder.create() .withTopic(topic) .withKey(key) .with("consumer.override.auto.offset.reset", "latest") .build(); } } <|start_filename|>src/test/java/net/mguenther/kafka/junit/ReadKeyValuesTest.java<|end_filename|> package net.mguenther.kafka.junit; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.common.serialization.StringDeserializer; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.Properties; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; class ReadKeyValuesTest { @Test @DisplayName("should preserve constructor arguments") void shouldPreserveConstructorArguments() { final ReadKeyValues<String, String> readRequest = ReadKeyValues.from("test").useDefaults(); assertThat(readRequest.getTopic()).isEqualTo("test"); assertThat(readRequest.getLimit()).isEqualTo(ReadKeyValues.WITHOUT_LIMIT); assertThat(readRequest.getMaxTotalPollTimeMillis()).isEqualTo(ReadKeyValues.DEFAULT_MAX_TOTAL_POLL_TIME_MILLIS); } @Test @DisplayName("should use defaults if not overridden") void shouldUseDefaultsIfNotOverridden() { final ReadKeyValues<String, String> readRequest = ReadKeyValues.from("test").useDefaults(); final Properties props = readRequest.getConsumerProps(); assertThat(props.get(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG)).isEqualTo("earliest"); assertThat(props.get(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG)).isEqualTo(false); assertThat(props.get(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG)).isEqualTo(StringDeserializer.class); assertThat(props.get(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG)).isEqualTo(StringDeserializer.class); assertThat(props.get(ConsumerConfig.MAX_POLL_RECORDS_CONFIG)).isEqualTo(100); assertThat(props.get(ConsumerConfig.ISOLATION_LEVEL_CONFIG)).isEqualTo("read_uncommitted"); assertThat(readRequest.isIncludeMetadata()).isFalse(); assertThat(readRequest.getSeekTo().isEmpty()).isTrue(); } @Test @DisplayName("unlimited should not restrict limit setting") void unlimitedShouldNotRestrictLimitSetting() { final ReadKeyValues<String, String> readRequest = ReadKeyValues.from("test") .withLimit(1) .unlimited() .build(); assertThat(readRequest.getLimit()).isEqualTo(ReadKeyValues.WITHOUT_LIMIT); } @Test @DisplayName("withLimit should restrict limit setting") void withLimitShouldRestrictLimitSetting() { final ReadKeyValues<String, String> readRequest = ReadKeyValues.from("test") .withLimit(1) .build(); assertThat(readRequest.getLimit()).isEqualTo(1); } @Test @DisplayName("withMaxPollTime should override its default setting") void withMaxPollTimeShouldOverrideItsDefault() { final ReadKeyValues<String, String> readRequest = ReadKeyValues.from("test") .withMaxTotalPollTime(10, TimeUnit.SECONDS) .build(); assertThat(readRequest.getMaxTotalPollTimeMillis()).isEqualTo((int) TimeUnit.SECONDS.toMillis(10)); } @Test @DisplayName("includeMetadata should override its default setting") void includeMetadataShouldOverrideItsDefaultSetting() { final ReadKeyValues<String, String> readRequest = ReadKeyValues.from("test") .includeMetadata() .build(); assertThat(readRequest.isIncludeMetadata()).isTrue(); } @Test @DisplayName("seekTo should preserve seek settings") void seekToShouldPreserveSeekSettings() { final ReadKeyValues<String, String> readRequest = ReadKeyValues.from("test") .seekTo(0, 1L) .seekTo(Collections.singletonMap(1, 2L)) .build(); assertThat(readRequest.getSeekTo().size()).isEqualTo(2); assertThat(readRequest.getSeekTo().get(0)).isEqualTo(1L); assertThat(readRequest.getSeekTo().get(1)).isEqualTo(2L); } @Test @DisplayName("with should override the default setting of the given parameter with the given value") void withShouldOverrideDefaultSetting() { final ReadKeyValues<String, String> readRequest = ReadKeyValues.from("test") .with(ConsumerConfig.ISOLATION_LEVEL_CONFIG, "read_committed") .build(); assertThat(readRequest.getConsumerProps().get(ConsumerConfig.ISOLATION_LEVEL_CONFIG)).isEqualTo("read_committed"); } @Test @DisplayName("withAll should override the default settings of the given parameters with the resp. values") void withAllShouldOverrideDefaultSettings() { final Properties overrides = new Properties(); overrides.put(ConsumerConfig.ISOLATION_LEVEL_CONFIG, "read_committed"); overrides.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 1000L); final ReadKeyValues<String, String> readRequest = ReadKeyValues.from("test") .withAll(overrides) .build(); assertThat(readRequest.getConsumerProps().get(ConsumerConfig.ISOLATION_LEVEL_CONFIG)).isEqualTo("read_committed"); assertThat(readRequest.getConsumerProps().get(ConsumerConfig.MAX_POLL_RECORDS_CONFIG)).isEqualTo(1000L); } } <|start_filename|>src/test/java/net/mguenther/kafka/junit/TopicConfigTest.java<|end_filename|> package net.mguenther.kafka.junit; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.Properties; import static org.assertj.core.api.Assertions.assertThat; class TopicConfigTest { @Test @DisplayName("should preserve constructor arguments") void shouldPreserveConstructorArguments() { final TopicConfig topicConfig = TopicConfig.withName("test").useDefaults(); assertThat(topicConfig.getTopic()).isEqualTo("test"); } @Test @DisplayName("should use defaults if not overridden") void shouldUseDefaultsIfNotOverridden() { final TopicConfig topicConfig = TopicConfig.withName("test").useDefaults(); assertThat(topicConfig.getNumberOfPartitions()).isEqualTo(1); assertThat(topicConfig.getNumberOfReplicas()).isEqualTo(1); assertThat(topicConfig.getProperties().getProperty("cleanup.policy")).isEqualTo("delete"); assertThat(topicConfig.getProperties().getProperty("delete.retention.ms")).isEqualTo("86400000"); assertThat(topicConfig.getProperties().getProperty("min.insync.replicas")).isEqualTo("1"); } @Test @DisplayName("withNumberOfReplicas should override its default setting") void withNumberOfReplicasShouldOverrideDefaultSetting() { final TopicConfig topicConfig = TopicConfig.withName("test") .withNumberOfReplicas(99) .build(); assertThat(topicConfig.getNumberOfReplicas()).isEqualTo(99); } @Test @DisplayName("withNumberOfPartitions should override its default setting") void withNumberOfPartitionsShouldOverrideDefaultSetting() { final TopicConfig topicConfig = TopicConfig.withName("test") .withNumberOfPartitions(99) .build(); assertThat(topicConfig.getNumberOfPartitions()).isEqualTo(99); } @Test @DisplayName("with should override the default setting of the given parameter with the given value") void withShouldOverrideDefaultSetting() { final TopicConfig topicConfig = TopicConfig.withName("test") .with("min.insync.replicas", "2") .build(); assertThat(topicConfig.getProperties().getProperty("min.insync.replicas")).isEqualTo("2"); } @Test @DisplayName("withAll should override the default settings of the given parameters with the resp. values") void withAllShouldOverrideDefaulSettings() { final Properties overrides = new Properties(); overrides.put("min.insync.replicas", "2"); overrides.put("delete.retention.ms", "1000"); final TopicConfig topicConfig = TopicConfig.withName("test") .withAll(overrides) .build(); assertThat(topicConfig.getProperties().getProperty("min.insync.replicas")).isEqualTo("2"); assertThat(topicConfig.getProperties().getProperty("delete.retention.ms")).isEqualTo("1000"); } } <|start_filename|>src/test/java/net/mguenther/kafka/junit/EmbeddedConnectConfigTest.java<|end_filename|> package net.mguenther.kafka.junit; import org.apache.kafka.connect.runtime.WorkerConfig; import org.apache.kafka.connect.runtime.distributed.DistributedConfig; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.Properties; import static org.assertj.core.api.Assertions.assertThat; class EmbeddedConnectConfigTest { @Test @DisplayName("should use defaults if not explicitly overriden") void shouldUseDefaultsIfNotOverridden() { final EmbeddedConnectConfig config = EmbeddedConnectConfig.useDefaults(); final Properties props = config.getConnectProperties(); assertThat(props.get(WorkerConfig.KEY_CONVERTER_CLASS_CONFIG)).isEqualTo("org.apache.kafka.connect.storage.StringConverter"); assertThat(props.get(WorkerConfig.VALUE_CONVERTER_CLASS_CONFIG)).isEqualTo("org.apache.kafka.connect.storage.StringConverter"); assertThat(props.get("internal.key.converter.schemas.enable")).isEqualTo("false"); assertThat(props.get("internal.value.converter.schemas.enable")).isEqualTo("false"); assertThat(props.get(DistributedConfig.CONFIG_STORAGE_REPLICATION_FACTOR_CONFIG)).isEqualTo("1"); assertThat(props.get(DistributedConfig.CONFIG_TOPIC_CONFIG)).isEqualTo("embedded-connect-config"); assertThat(props.get(DistributedConfig.OFFSET_STORAGE_REPLICATION_FACTOR_CONFIG)).isEqualTo("1"); assertThat(props.get(DistributedConfig.OFFSET_STORAGE_TOPIC_CONFIG)).isEqualTo("embedded-connect-offsets"); assertThat(props.get(DistributedConfig.STATUS_STORAGE_REPLICATION_FACTOR_CONFIG)).isEqualTo("1"); assertThat(props.get(DistributedConfig.STATUS_STORAGE_TOPIC_CONFIG)).isEqualTo("embedded-connect-status"); assertThat(props.get(DistributedConfig.GROUP_ID_CONFIG)).isNotNull(); } @Test @DisplayName("with(param) should override the corresponding default setting") void withShouldOverrideDefaultSetting() { final EmbeddedConnectConfig config = EmbeddedConnectConfig .kafkaConnect() .with(DistributedConfig.GROUP_ID_CONFIG, "test-group") .build(); final Properties props = config.getConnectProperties(); assertThat(props.get(DistributedConfig.GROUP_ID_CONFIG)).isEqualTo("test-group"); } @Test @DisplayName("withAll(params) should override the corresponding default settings") void withAllShouldOverrideDefaultSettings() { final Properties overrides = new Properties(); overrides.put(DistributedConfig.GROUP_ID_CONFIG, "test-group"); overrides.put(DistributedConfig.STATUS_STORAGE_TOPIC_CONFIG, "status-topic"); final EmbeddedConnectConfig config = EmbeddedConnectConfig .kafkaConnect() .withAll(overrides) .build(); final Properties props = config.getConnectProperties(); assertThat(props.get(DistributedConfig.GROUP_ID_CONFIG)).isEqualTo("test-group"); assertThat(props.get(DistributedConfig.STATUS_STORAGE_TOPIC_CONFIG)).isEqualTo("status-topic"); } @Test @DisplayName("deployConnector should retain the configuration of the connector") void deployConnectorShouldStoreConnectorConfig() { final Properties connectorConfig = new Properties(); final EmbeddedConnectConfig config = EmbeddedConnectConfig .kafkaConnect() .deployConnector(connectorConfig) .build(); assertThat(config.getConnectors().size()).isEqualTo(1); assertThat(config.getConnectors().contains(connectorConfig)).isTrue(); } @Test @DisplayName("deployConnectors should retain all configurations for the given connectors") void deployConnectorsShouldStoreConnectorConfigs() { final EmbeddedConnectConfig config = EmbeddedConnectConfig .kafkaConnect() .deployConnectors(new Properties(), new Properties()) .build(); assertThat(config.getConnectors().size()).isEqualTo(2); } } <|start_filename|>src/test/java/net/mguenther/kafka/junit/SendKeyValuesTest.java<|end_filename|> package net.mguenther.kafka.junit; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.IntegerSerializer; import org.apache.kafka.common.serialization.StringSerializer; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.Collection; import java.util.Collections; import java.util.Properties; import static org.assertj.core.api.Assertions.assertThat; class SendKeyValuesTest { @Test @DisplayName("should preserve constructor arguments") void shouldPreserveConstructorArguments() { final Collection<KeyValue<String, String>> records = Collections.singletonList(new KeyValue<>("k", "v")); final SendKeyValues<String, String> sendRequest = SendKeyValues.to("test-topic", records).useDefaults(); assertThat(sendRequest.getTopic()).isEqualTo("test-topic"); assertThat(sendRequest.getRecords().size()).isEqualTo(1); assertThat(sendRequest.getRecords()).contains(new KeyValue<>("k", "v")); } @Test @DisplayName("should use defaults if not overridden") void shouldUseDefaultsIfNotOverridden() { final Collection<KeyValue<String, String>> records = Collections.singletonList(new KeyValue<>("k", "v")); final SendKeyValues<String, String> sendRequest = SendKeyValues.to("test-topic", records).useDefaults(); final Properties props = sendRequest.getProducerProps(); assertThat(props.get(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)).isEqualTo(StringSerializer.class); assertThat(props.get(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)).isEqualTo(StringSerializer.class); } @Test @DisplayName("with should override the default setting of the given parameter with the given value") void withShouldOverrideDefaultSetting() { final Collection<KeyValue<String, Integer>> records = Collections.singletonList(new KeyValue<>("k", 1)); final SendKeyValues<String, Integer> sendRequest = SendKeyValues.to("test-topic", records) .with(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class) .build(); final Properties props = sendRequest.getProducerProps(); assertThat(props.get(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)).isEqualTo(IntegerSerializer.class); } @Test @DisplayName("withAll should override the default settings of the given parameters with the resp. values") void withAllShouldOverrideDefaultSettings() { final Properties overrides = new Properties(); overrides.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class); overrides.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class); final Collection<KeyValue<Integer, Integer>> records = Collections.singletonList(new KeyValue<>(1, 1)); final SendKeyValues<Integer, Integer> sendRequest = SendKeyValues.to("test-topic", records) .withAll(overrides) .build(); final Properties props = sendRequest.getProducerProps(); assertThat(props.get(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)).isEqualTo(IntegerSerializer.class); assertThat(props.get(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)).isEqualTo(IntegerSerializer.class); } } <|start_filename|>src/main/java/net/mguenther/kafka/junit/EmbeddedKafkaConfig.java<|end_filename|> package net.mguenther.kafka.junit; import kafka.server.KafkaConfig$; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.ToString; import lombok.extern.slf4j.Slf4j; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.stream.Collectors; @Slf4j @ToString @RequiredArgsConstructor public class EmbeddedKafkaConfig { public static final int DEFAULT_NUMBER_OF_BROKERS = 1; public static final String DEFAULT_LISTENER = "PLAINTEXT://localhost:9092"; private static final String LISTENER_TEMPLATE = "PLAINTEXT://localhost:%s"; public static class EmbeddedKafkaConfigBuilder { private final Properties properties = new Properties(); private int numberOfBrokers = DEFAULT_NUMBER_OF_BROKERS; private EmbeddedKafkaConfigBuilder() { } public EmbeddedKafkaConfigBuilder withNumberOfBrokers(final int numberOfBrokers) { this.numberOfBrokers = numberOfBrokers; return this; } public <T> EmbeddedKafkaConfigBuilder with(final String propertyName, final T value) { properties.put(propertyName, value); return this; } public EmbeddedKafkaConfigBuilder withAll(final Properties overrides) { properties.putAll(overrides); return this; } private <T> void ifNonExisting(final String propertyName, final T value) { if (properties.get(propertyName) != null) return; properties.put(propertyName, value); } public EmbeddedKafkaConfig build() { final List<String> listeners = new ArrayList<>(numberOfBrokers); if (numberOfBrokers > 1) { listeners.addAll(getUniqueEphemeralPorts(numberOfBrokers) .stream() .map(port -> String.format(LISTENER_TEMPLATE, port)) .collect(Collectors.toList())); } else { listeners.add(DEFAULT_LISTENER); } ifNonExisting(KafkaConfig$.MODULE$.ZkSessionTimeoutMsProp(), "8000"); ifNonExisting(KafkaConfig$.MODULE$.ZkConnectionTimeoutMsProp(), "10000"); ifNonExisting(KafkaConfig$.MODULE$.NumPartitionsProp(), "1"); ifNonExisting(KafkaConfig$.MODULE$.DefaultReplicationFactorProp(), "1"); ifNonExisting(KafkaConfig$.MODULE$.MinInSyncReplicasProp(), "1"); ifNonExisting(KafkaConfig$.MODULE$.AutoCreateTopicsEnableProp(), "true"); ifNonExisting(KafkaConfig$.MODULE$.MessageMaxBytesProp(), "1000000"); ifNonExisting(KafkaConfig$.MODULE$.ControlledShutdownEnableProp(), "true"); ifNonExisting(KafkaConfig$.MODULE$.OffsetsTopicReplicationFactorProp(), "1"); ifNonExisting(KafkaConfig$.MODULE$.GroupInitialRebalanceDelayMsProp(), 0); ifNonExisting(KafkaConfig$.MODULE$.TransactionsTopicReplicationFactorProp(), "1"); ifNonExisting(KafkaConfig$.MODULE$.TransactionsTopicMinISRProp(), "1"); ifNonExisting(KafkaConfig$.MODULE$.SslClientAuthProp(), "none"); ifNonExisting(KafkaConfig$.MODULE$.AutoLeaderRebalanceEnableProp(), "true"); ifNonExisting(KafkaConfig$.MODULE$.ControlledShutdownEnableProp(), "true"); ifNonExisting(KafkaConfig$.MODULE$.LeaderImbalanceCheckIntervalSecondsProp(), 5); ifNonExisting(KafkaConfig$.MODULE$.LeaderImbalancePerBrokerPercentageProp(), 1); ifNonExisting(KafkaConfig$.MODULE$.UncleanLeaderElectionEnableProp(), "false"); return new EmbeddedKafkaConfig(numberOfBrokers, listeners, properties); } private List<Integer> getUniqueEphemeralPorts(final int howMany) { final List<Integer> ephemeralPorts = new ArrayList<>(howMany); while (ephemeralPorts.size() < howMany) { final int port = generateRandomEphemeralPort(); if (!ephemeralPorts.contains(port)) { ephemeralPorts.add(port); } } return ephemeralPorts; } private int generateRandomEphemeralPort() { return Math.min((int) (Math.random() * 65535) + 1024, 65535); } } @Getter private final int numberOfBrokers; private final List<String> uniqueListeners; @Getter private final Properties brokerProperties; public String listenerFor(final int brokerIndex) { if (brokerProperties.containsKey(KafkaConfig$.MODULE$.ListenersProp())) { return brokerProperties.getProperty(KafkaConfig$.MODULE$.ListenersProp()); } else { return uniqueListeners.get(brokerIndex); } } public static EmbeddedKafkaConfigBuilder brokers() { return new EmbeddedKafkaConfigBuilder(); } /** * @return instance of {@link EmbeddedKafkaConfigBuilder} * @deprecated This method is deprecated since 2.7.0. Expect it to be removed in a future release. * Use {@link #brokers()} instead. */ @Deprecated public static EmbeddedKafkaConfigBuilder create() { return brokers(); } public static EmbeddedKafkaConfig defaultBrokers() { return brokers().build(); } /** * @return instance of {@link EmbeddedKafkaConfig} that contains the default configuration * for all brokers in an embedded Kafka cluster * @deprecated This method is deprecated since 2.7.0. Expect it to be removed in a future release. * Use {@link #defaultBrokers()} instead. */ @Deprecated public static EmbeddedKafkaConfig useDefaults() { return defaultBrokers(); } } <|start_filename|>src/test/java/net/mguenther/kafka/junit/SendKeyValuesTransactionalTest.java<|end_filename|> package net.mguenther.kafka.junit; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.IntegerSerializer; import org.apache.kafka.common.serialization.LongSerializer; import org.apache.kafka.common.serialization.StringSerializer; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.Properties; import static org.assertj.core.api.Assertions.assertThat; class SendKeyValuesTransactionalTest { @Test @DisplayName("should preserve constructor arguments") void shouldPreserveConstructorArguments() { final SendKeyValuesTransactional<String, String> sendRequest = SendKeyValuesTransactional .inTransaction("test-topic", Collections.singletonList(new KeyValue<>("k", "v"))) .useDefaults(); assertThat(sendRequest.getRecordsPerTopic().containsKey("test-topic")).isTrue(); assertThat(sendRequest.getRecordsPerTopic().get("test-topic").contains(new KeyValue<>("k", "v"))).isTrue(); } @Test @DisplayName("should be able to close over records for multiple topics") void shouldBeAbleToCloseOverRecordsForMultipleTopics() { final SendKeyValuesTransactional<String, String> sendRequest = SendKeyValuesTransactional .inTransaction("test-topic", Collections.singletonList(new KeyValue<>("k", "v"))) .inTransaction("test-topic-2", Collections.singletonList(new KeyValue<>("a", "b"))) .useDefaults(); assertThat(sendRequest.getRecordsPerTopic().containsKey("test-topic-2")).isTrue(); assertThat(sendRequest.getRecordsPerTopic().get("test-topic-2").contains(new KeyValue<>("a", "b"))).isTrue(); } @Test @DisplayName("should use defaults if not overridden") void shouldUseDefaultsIfNotOverridden() { final SendKeyValuesTransactional<String, String> sendRequest = SendKeyValuesTransactional .inTransaction("test-topic", Collections.singletonList(new KeyValue<>("k", "v"))) .useDefaults(); final Properties props = sendRequest.getProducerProps(); assertThat(props.get(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)).isEqualTo(StringSerializer.class); assertThat(props.get(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)).isEqualTo(StringSerializer.class); assertThat(sendRequest.shouldFailTransaction()).isFalse(); } @Test @DisplayName("should preserve fail transaction setting if overridden") void shouldPreserveFailTransactionSettingIfOverridden() { final SendKeyValuesTransactional<String, String> sendRequest = SendKeyValuesTransactional .inTransaction("test-topic", Collections.singletonList(new KeyValue<>("k", "v"))) .failTransaction() .build(); assertThat(sendRequest.shouldFailTransaction()).isTrue(); } @Test @DisplayName("with should override the default setting of the given parameter with the given value") void withShouldOverrideDefaultSetting() { final SendKeyValuesTransactional<String, Integer> sendRequest = SendKeyValuesTransactional .inTransaction("test-topic", Collections.singletonList(new KeyValue<>("a", 1))) .with(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class) .build(); final Properties props = sendRequest.getProducerProps(); assertThat(props.get(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)).isEqualTo(IntegerSerializer.class); } @Test @DisplayName("withAll should override the default settings of the given parameters with the resp. values") void withAllShouldOverrideDefaultSettings() { final Properties overrides = new Properties(); overrides.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class); overrides.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, IntegerSerializer.class); final SendKeyValuesTransactional<Long, Integer> sendRequest = SendKeyValuesTransactional .inTransaction("test-topic", Collections.singletonList(new KeyValue<>(1L, 2))) .withAll(overrides) .build(); final Properties props = sendRequest.getProducerProps(); assertThat(props.get(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)).isEqualTo(LongSerializer.class); assertThat(props.get(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)).isEqualTo(IntegerSerializer.class); } }
mguenther/kafka-jun
<|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/BaseEntity.java<|end_filename|> package org.needle.bookingdiscount.domain; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.MappedSuperclass; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import lombok.Getter; import lombok.Setter; @Getter @Setter @MappedSuperclass @EntityListeners(AuditingEntityListener.class) public abstract class BaseEntity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) protected Long id; // @CreatedBy // @Column(name="created_by", length=30) // private String createdBy; // // @CreatedDate // @Column(name="created_date") // private Date createdDate; // // @LastModifiedBy // @Column(name="last_modified_by", length=30) // private String lastModifiedBy; // // @LastModifiedDate // @Column(name="last_modified_date") // private Date lastModifiedDate; // // @Column(name="group_id") // private Long groupId; } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/api/SearchController.java<|end_filename|> package org.needle.bookingdiscount.server.api; import java.util.Optional; import javax.servlet.http.HttpServletRequest; import org.needle.bookingdiscount.domain.member.MemberUser; import org.needle.bookingdiscount.server.api.handler.ResponseHandler; import org.needle.bookingdiscount.server.security.SecurityContext; import org.needle.bookingdiscount.server.service.SearchService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/search") public class SearchController { // Long userId = CartController.userId; @Autowired private SearchService seachService; @Autowired private SecurityContext securityContext; //搜索页面数据 @RequestMapping("/index") @ResponseBody public Object index(@RequestHeader(name="X-Nideshop-Token") String token, String keywords, HttpServletRequest request) { return ResponseHandler.doResponse(() -> { Optional<MemberUser> user = securityContext.getUserByToken(token); return seachService.index(keywords, user.isPresent() ? user.get().getId() : null); }); } //搜索帮助 @RequestMapping("/helper") @ResponseBody public Object helper(String keywords, HttpServletRequest request) { return ResponseHandler.doResponse(() -> { return seachService.helper(keywords); }); } @RequestMapping("/clearHistory") @ResponseBody public Object clearHistory(@RequestHeader(name="X-Nideshop-Token") String token, HttpServletRequest request) { return ResponseHandler.doResponse(() -> { Optional<MemberUser> user = securityContext.getUserByToken(token); seachService.clearHistory(user.isPresent() ? user.get().getId() : null); return "{}"; }); } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/api/handler/RequestHandler.java<|end_filename|> package org.needle.bookingdiscount.server.api.handler; @FunctionalInterface public interface RequestHandler { Object doRequest() throws Exception; } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/service/AddressService.java<|end_filename|> package org.needle.bookingdiscount.server.service; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.needle.bookingdiscount.domain.member.Address; import org.needle.bookingdiscount.domain.member.Address.JsonAddress; import org.needle.bookingdiscount.domain.member.MemberUser; import org.needle.bookingdiscount.server.exception.ServiceException; import org.needle.bookingdiscount.server.repository.member.AddressRepository; import org.needle.bookingdiscount.server.repository.support.RegionRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class AddressService { @Autowired private AddressRepository addressRepository; @Autowired private RegionRepository regionRepository; public List<JsonAddress> getAddresses(Long userId) { List<Address> addressList = addressRepository.findByUserAndIsDelete(userId, false); for(int i = 0; i < addressList.size(); i++) { Address addressItem = addressList.get(i); addressItem.setProvinceName(regionRepository.findById(addressItem.getProvinceId()).get().getName()); addressItem.setCityName(regionRepository.findById(addressItem.getCityId()).get().getName()); addressItem.setDistrictName(regionRepository.findById(addressItem.getDistrictId()).get().getName()); addressItem.setFullRegion(addressItem.getProvinceName() + addressItem.getCityName() + addressItem.getDistrictName()); } return addressList.stream().map(a -> new JsonAddress(a)).collect(Collectors.toList()); } //收货地址详情 public JsonAddress addressDetail(Long userId, Long id) { Long addressId = id; Optional<Address> addressOpt = addressRepository.findById(addressId); if(addressOpt.isPresent()) { Address addressInfo = addressOpt.get(); addressInfo.setProvinceName(regionRepository.findById(addressInfo.getProvinceId()).get().getName()); addressInfo.setCityName(regionRepository.findById(addressInfo.getCityId()).get().getName()); addressInfo.setDistrictName(regionRepository.findById(addressInfo.getDistrictId()).get().getName()); addressInfo.setFullRegion(addressInfo.getProvinceName() + addressInfo.getCityName() + addressInfo.getDistrictName()); return new JsonAddress(addressInfo); } return new JsonAddress(); } //保存收货地址 public JsonAddress saveAddress(Long userId, Long id, String name, String mobile, Long province_id, Long city_id, Long district_id, String address, Boolean is_default) { Long addressId = id; Address addressData = new Address(); addressData.setId(id); addressData.setName(name); addressData.setMobile(mobile); addressData.setCountryId(1L); addressData.setProvinceId(province_id); addressData.setCityId(city_id); addressData.setDistrictId(district_id); addressData.setAddress(address); addressData.setIsDefault(is_default); addressData.setIsDelete(false); addressData.setUser(new MemberUser(userId)); addressRepository.save(addressData); if(Boolean.TRUE.equals(is_default)) { addressRepository.findByUserAndIsDelete(userId, false).forEach(adds -> { if(addressId != null && adds.getId() != addressId) { if(Boolean.TRUE.equals(adds.getIsDefault())) { adds.setIsDefault(false); addressRepository.save(adds); } } }); } return new JsonAddress(addressData); } public JsonAddress deleteAddress(Long userId, Long id) { Optional<Address> addressOpt = addressRepository.findById(id); if(!addressOpt.isPresent()) { throw new ServiceException("地址不存在"); } Address address = addressOpt.get(); address.setIsDefault(true); addressRepository.save(address); return new JsonAddress(address); } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/exception/ServiceException.java<|end_filename|> package org.needle.bookingdiscount.server.exception; import java.text.MessageFormat; public class ServiceException extends RuntimeException { private static final long serialVersionUID = 3149885123244982860L; private int code; private String message; private Throwable cause; public static ServiceException error(String message, Object... arguments) { ServiceException exception = new ServiceException(1, message, arguments); return exception; } public static ServiceException error(int code, String message, Object... arguments) { ServiceException exception = new ServiceException(code, message, arguments); return exception; } public ServiceException() { this.cause = null; } public ServiceException(String message, Object... arguments) { this.code = 1; this.message = MessageFormat.format(message, arguments); this.cause = null; } public ServiceException(int code, String message, Object... arguments) { this.code = code; this.message = MessageFormat.format(message, arguments); this.cause = null; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Throwable getCause() { return cause; } public void setCause(Throwable cause) { this.cause = cause; } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/api/AuthController.java<|end_filename|> package org.needle.bookingdiscount.server.api; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.needle.bookingdiscount.domain.member.MemberUser.JsonMemberUser; import org.needle.bookingdiscount.server.api.handler.ResponseHandler; import org.needle.bookingdiscount.server.security.SecurityContext; import org.needle.bookingdiscount.server.service.AuthService; import org.needle.bookingdiscount.server.service.AuthService.WxUserInfo; import org.needle.bookingdiscount.utils.RequestUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import lombok.Data; import lombok.extern.slf4j.Slf4j; @Slf4j @Controller @RequestMapping("/auth") public class AuthController { @Autowired private AuthService authService; @Autowired private SecurityContext securityContext; @Data public static class SessionUser { private Long id; private String nickname; private String appid; } @Data static class LoginData { String appid; String code; WxUserInfo userInfo; } // http://localhost:8080/auth/loginByWeixin @RequestMapping("/loginByWeixin") @ResponseBody public Object loginByWeixin( @RequestBody LoginData data, HttpServletRequest request, HttpServletResponse response) { log.info("loginByWeixin(..) => appid={}, code={}, userInfo={}", data.appid, data.code, data.userInfo); return ResponseHandler.doResponse(() -> { WxUserInfo fullUserInfo = data.getUserInfo(); String clientIp = RequestUtils.getClientIp(request); log.info("clientIp={}", clientIp); ModelMap model = authService.login(fullUserInfo, data.appid, data.code, clientIp); JsonMemberUser user = (JsonMemberUser) model.get("userInfo"); String token = request.getSession().getId(); model.put("token", token); securityContext.setUserToken(user.getId(), token); log.debug("loginByWeixin(..) => JSESSIONID={}", token); return model; }); } @RequestMapping("/logout") @ResponseBody public Object logout() { return ResponseHandler.doResponse(() -> { return new ModelMap(); }); } } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/support/Region.java<|end_filename|> package org.needle.bookingdiscount.domain.support; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.needle.bookingdiscount.domain.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper=true) @Entity @Table(name="needle_region") public class Region extends BaseEntity { @Column(name="name", length=120) private String name; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="parent_id") private Region parent; @Column(name="type", columnDefinition="int default 2") private Integer type; @Column(name="agency_id", columnDefinition="smallint(5) unsigned default 0") private Long agencyId; @Column(name="area", columnDefinition="smallint(5) unsigned default 0") private Integer area; @Column(name="area_code", length=10) private String areaCode; @Column(name="far_area", columnDefinition="int(2) unsigned default 0") private Integer farArea; @Column(name="is_delete", columnDefinition="tinyint default 0") private Boolean isDelete; @Data public static class JsonRegion { private Long id; private Long parent_id; private String name; private Integer type; private Long agency_id; private Integer area; private String area_code; private Integer far_area; public JsonRegion(Region region) { this.id = region.getId(); this.parent_id = region.getParent() == null ? null : region.getParent().getId(); this.name = region.getName(); this.type = region.getType(); this.agency_id = region.getAgencyId(); this.area = region.getArea(); this.area_code = region.getAreaCode(); this.far_area = region.getFarArea(); } } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/repository/product/GoodsSpecificationRepository.java<|end_filename|> package org.needle.bookingdiscount.server.repository.product; import java.util.List; import org.needle.bookingdiscount.domain.product.GoodsSpecification; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; public interface GoodsSpecificationRepository extends PagingAndSortingRepository<GoodsSpecification, Long> { @Query("from GoodsSpecification t where t.goods.id=?1 and t.isDelete=false ") public List<GoodsSpecification> findByGoods(Long goodsId); @Query("from GoodsSpecification t where t.goods.id=?1 and t.isDelete=?2 and t.id in (?3) ") public List<GoodsSpecification> findByGoodsAndIsDeleteAndIdIn(Long goodsId, Boolean isDelete, List<Long> ids); } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/repository/support/AdRepository.java<|end_filename|> package org.needle.bookingdiscount.server.repository.support; import java.util.List; import org.needle.bookingdiscount.domain.support.Ad; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; public interface AdRepository extends PagingAndSortingRepository<Ad, Long> { @Query("from Ad t where t.enabled=?1 and t.isDelete=?2 order by t.sortOrder asc") public List<Ad> findByEnabledAndIsDelete(Boolean enabled, Boolean isDelete); } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/api/AddressController.java<|end_filename|> package org.needle.bookingdiscount.server.api; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.needle.bookingdiscount.domain.member.MemberUser; import org.needle.bookingdiscount.server.api.handler.ResponseHandler; import org.needle.bookingdiscount.server.exception.ServiceException; import org.needle.bookingdiscount.server.security.SecurityContext; import org.needle.bookingdiscount.server.service.AddressService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/address") public class AddressController { @Autowired private AddressService addressService; @Autowired private SecurityContext securityContext; // 收货地址详情 @RequestMapping("/addressDetail") @ResponseBody public Object addressDetail(@RequestHeader(name="X-Nideshop-Token") String token, Long id, HttpServletRequest request) { return ResponseHandler.doResponse(() -> { MemberUser user = securityContext.getUserByToken(token) .orElseThrow(() -> new ServiceException(401, "用户未登录")); return addressService.addressDetail(user.getId(), id); }); } // 保存收货地址 @RequestMapping("/deleteAddress") @ResponseBody public Object deleteAddress(@RequestHeader(name="X-Nideshop-Token") String token, Long id, HttpServletRequest request) { return ResponseHandler.doResponse(() -> { MemberUser user = securityContext.getUserByToken(token) .orElseThrow(() -> new ServiceException(401, "用户未登录")); return addressService.deleteAddress(user.getId(), id); }); } // 保存收货地址 @RequestMapping("/saveAddress") @ResponseBody public Object saveAddress(@RequestHeader(name="X-Nideshop-Token") String token, @RequestBody Map<String,Object> data, HttpServletRequest request) { Object idObject = data.get("id"); Long id = idObject == null ? null : Long.valueOf(idObject.toString()); String name = (String) data.get("name"); String mobile = (String) data.get("mobile"); Long province_id = Long.valueOf(data.get("province_id").toString()); Long city_id = Long.valueOf(data.get("city_id").toString()); Long district_id = Long.valueOf(data.get("district_id").toString()); String address = (String) data.get("address"); Integer is_default = (Integer) data.get("is_default"); return ResponseHandler.doResponse(() -> { MemberUser user = securityContext.getUserByToken(token) .orElseThrow(() -> new ServiceException(401, "用户未登录")); return addressService.saveAddress(user.getId(), id, name, mobile, province_id, city_id, district_id, address, 1 == is_default ? true : false); }); } // 查詢收货地址 @RequestMapping("/getAddresses") @ResponseBody public Object getAddresses(@RequestHeader(name="X-Nideshop-Token") String token, HttpServletRequest request) { return ResponseHandler.doResponse(() -> { MemberUser user = securityContext.getUserByToken(token) .orElseThrow(() -> new ServiceException(401, "用户未登录")); return addressService.getAddresses(user.getId()); }); } } <|start_filename|>booking-admin/src/main/java/org/needle/bookingdiscount/BookingAdminContextService.java<|end_filename|> package org.needle.bookingdiscount; import java.util.Date; import org.needle.bookingdiscount.domain.cart.Cart; import org.needle.bookingdiscount.domain.freight.FreightTemplate; import org.needle.bookingdiscount.domain.freight.FreightTemplateDetail; import org.needle.bookingdiscount.domain.freight.FreightTemplateGroup; import org.needle.bookingdiscount.domain.freight.Settings; import org.needle.bookingdiscount.domain.freight.Shipper; import org.needle.bookingdiscount.domain.member.Address; import org.needle.bookingdiscount.domain.member.Footprint; import org.needle.bookingdiscount.domain.member.MemberUser; import org.needle.bookingdiscount.domain.member.SearchHistory; import org.needle.bookingdiscount.domain.order.Formid; import org.needle.bookingdiscount.domain.order.Order; import org.needle.bookingdiscount.domain.order.OrderExpress; import org.needle.bookingdiscount.domain.order.OrderGoods; import org.needle.bookingdiscount.domain.product.Category; import org.needle.bookingdiscount.domain.product.Goods; import org.needle.bookingdiscount.domain.product.GoodsGallery; import org.needle.bookingdiscount.domain.product.GoodsSpecification; import org.needle.bookingdiscount.domain.product.Product; import org.needle.bookingdiscount.domain.product.Specification; import org.needle.bookingdiscount.domain.support.Ad; import org.needle.bookingdiscount.domain.support.ExceptArea; import org.needle.bookingdiscount.domain.support.ExceptAreaDetail; import org.needle.bookingdiscount.domain.support.Keywords; import org.needle.bookingdiscount.domain.support.Notice; import org.needle.bookingdiscount.domain.support.Region; import org.needle.bookingdiscount.domain.support.ShowSettings; import org.needleframe.AbstractContextService; import org.needleframe.context.ModuleFactory; import org.needleframe.context.ModuleFactory.MenuFactory; import org.needleframe.core.model.ModuleProp.Decoder; import org.needleframe.core.model.ModuleProp.Encoder; import org.needleframe.core.model.ModuleProp.Feature; import org.needleframe.core.model.ViewFilter.Op; import org.needleframe.utils.Base64Utils; import org.needleframe.utils.DateUtils; import org.springframework.stereotype.Service; @Service public class BookingAdminContextService extends AbstractContextService { @Override protected void defModules(ModuleFactory mf) { mf.build(Cart.class).addCRUD() .filters("goodsName").op(Op.RLIKE) .showList("user.id", "user.nickName", "goods.id", "listPicUrl", "goodsName", "goodsSpecificationNameValue", "number", "retailPrice", "addTime", "isDelete") .fk("user").show("nickName").end() .fk("goods").show("name").end() .prop("listPicUrl").absoluteImage().end() .prop("isDelete").feature(Feature.SELECT).values(new Object[]{1, 0}).end() .prop("addTime").dateTime().encoder(new DateEncoder("yyyy-MM-dd HH:mm:ss")).decoder(new DateDecoder("yyyy-MM-dd HH:mm:ss")).end() .prop("isDelete").values(new Object[] {"true", "false"}) .encoder(v -> "true".equals(v) ? 1 : 0) .decoder(v -> v == null ? v : Integer.valueOf(v.toString()) == 1 ? "true" : "false").end() .prop("product").hide().end() .prop("goodsAka").hide().end() .prop("goodsWeight").hide().end() .prop("addPrice").hide().end() .prop("goodsSpecificationIds").hide().end() .prop("checked").hide().end() .prop("freightTemplateId").hide().end() .prop("isOnSale").hide().end() .prop("goodsSn").hide().end() .prop("isFast").hide().end() .prop("weightCount").hide() .prop("goodsNumber").hide().end() .addProp("user.id", Long.class).hide().end() .addProp("goods.id", Long.class).hide().end(); mf.build(FreightTemplate.class) .filters("name").op(Op.RLIKE) .prop("name").required().end() .prop("packagePrice").required().end() .prop("freightType") .values(new Object[] {"按件", "按重"}).encoder(new FreightTypeConverter()).decoder(new FreightTypeConverter()).end() .prop("isDelete").encoder(new BooleanConverter()).decoder(new BooleanConverter()).end(); mf.build(FreightTemplateDetail.class); mf.build(FreightTemplateGroup.class); mf.build(Order.class).addCRUD() .filters("orderSn").op(Op.RLIKE) .filters("user").eq() .filters("consignee").op(Op.RLIKE) .deletedProp("isDelete", true) .fk("user").ref("id").show("nickname").end() .prop("orderStatus") .values(new Object[] {"待付款", "已关闭", "待发货", "待收货", "已收货"}) .encoder(new OrderStatusConvert()).decoder(new OrderStatusConvert()).end() .prop("orderSn").rule().noUpdate().end() .prop("addTime").dateTime().encoder(new DateEncoder("yyyy-MM-dd HH:mm:ss")).decoder(new DateDecoder("yyyy-MM-dd HH:mm:ss")).rule().noUpdate().end() .prop("payTime").dateTime().encoder(new DateEncoder("yyyy-MM-dd HH:mm:ss")).decoder(new DateDecoder("yyyy-MM-dd HH:mm:ss")).rule().noUpdate().end() .prop("shippingTime").dateTime().encoder(new DateEncoder("yyyy-MM-dd HH:mm:ss")).decoder(new DateDecoder("yyyy-MM-dd HH:mm:ss")).end() .prop("confirmTime").dateTime().encoder(new DateEncoder("yyyy-MM-dd HH:mm:ss")).decoder(new DateDecoder("yyyy-MM-dd HH:mm:ss")).end() .prop("dealdoneTime").dateTime().encoder(new DateEncoder("yyyy-MM-dd HH:mm:ss")).decoder(new DateDecoder("yyyy-MM-dd HH:mm:ss")).end() .prop("changePrice").pattern("0.00").end() .prop("actualPrice").end() .prop("orderPrice").end() .prop("goodsPrice").end() .prop("freightPrice").end() .prop("remark").inRow().end() .prop("adminMemo").inRow().end() .prop("postscript") .encoder(v -> Base64Utils.encode(v.toString())) .decoder(v -> Base64Utils.decode(v.toString())).end() .prop("country").hide().end() .prop("province").hide().end() .prop("city").hide().end() .prop("district").hide().end() .prop("address").hide().end() .prop("printInfo").hide().end() .prop("postscript").hide().end() .prop("postscript").hide().end() .prop("shippingFee").hide().end() .prop("payName").hide().end() .prop("payId").hide().end() .prop("expressValue").hide().end() .prop("orderType").hide().end() .prop("offlinePay").values(new Object[] {"true", "false"}).encoder(new BooleanConverter()).decoder(new BooleanConverter()).end() .prop("shippingStatus").values(new Object[] {"true", "false"}).encoder(new BooleanConverter()).decoder(new BooleanConverter()).end() .prop("printStatus").values(new Object[] {"true", "false"}).encoder(new BooleanConverter()).decoder(new BooleanConverter()).end() .prop("payStatus").values(new Object[] {"true", "false"}).encoder(new BooleanConverter()).decoder(new BooleanConverter()).end() .addChild(OrderGoods.class).addCRUD() .fk("order").show("orderSn").hideList().end() .fk("goods").show("name").hide().end() .fk("user").show("nickname").hide().end() .prop("goodsAka").hide().end() .prop("product").hide().end() .prop("goodsSpecificationIds").hide().end() .prop("listPicUrl").absoluteImage().end() .endChild() .addChild(OrderExpress.class).addCRUD() .fk("order").show("orderSn").hideList().end() .fk("shipper").show("name").hide().end() .prop("shipperName").end() .prop("logisticCode").end() .prop("traces").end() .prop("isFinish").end() .prop("requestTime").dateTime().encoder(new DateEncoder("yyyy-MM-dd HH:mm:ss")).decoder(new DateDecoder("yyyy-MM-dd HH:mm:ss")).end() .prop("addTime").dateTime().encoder(new DateEncoder("yyyy-MM-dd HH:mm:ss")).decoder(new DateDecoder("yyyy-MM-dd HH:mm:ss")).end() .prop("updateTime").dateTime().encoder(new DateEncoder("yyyy-MM-dd HH:mm:ss")).decoder(new DateDecoder("yyyy-MM-dd HH:mm:ss")).end() .prop("expressType").end() .endChild(); mf.build(MemberUser.class) .filters("nickname").op(Op.RLIKE) .showList("avatar", "nickname", "gender", "registerTime", "lastLoginTime") .prop("avatar").absoluteImage().end() .prop("nickname") .encoder(v -> Base64Utils.encode(v.toString())) .decoder(v -> Base64Utils.decode(v.toString())) .end() .prop("gender").values(new Object[] {"女", "男"}).encoder(v -> "女".equals(v) ? 2 : 1).decoder(v -> ((int) v) == 2 ? "女" : "男").end() .prop("registerTime").dateTime().encoder(new DateEncoder("yyyy-MM-dd HH:mm:ss")).decoder(new DateDecoder("yyyy-MM-dd HH:mm:ss")).end() .prop("lastLoginTime").dateTime().encoder(new DateEncoder("yyyy-MM-dd HH:mm:ss")).decoder(new DateDecoder("yyyy-MM-dd HH:mm:ss")).end() .prop("birthday").date().encoder(new DateEncoder("yyyy-MM-dd")).decoder(new DateDecoder("yyyy-MM-dd")).end() .prop("nameMobile").hide().end() .prop("token").hide().end() .addChild(Cart.class).addCRUD() .fk("user").show("nickname").end() .fk("goods").show("name").end() .fk("product").show("goodsName").end() .endChild() .addChild(Order.class).addCRUD() .fk("user").show("nickname").end() .endChild() .addChild(Address.class).addCRUD() .showList("name", "mobile", "address") .fk("user").show("nickname").end() .endChild() .addChild(Footprint.class).addCRUD() .showList("goods.id", "goods.listPicUrl", "goods.name", "addTime") .fk("user").show("nickname").end() .fk("goods").show("name").end() .addProp("goods.id", Long.class).end() .addProp("goods.listPicUrl", String.class).absoluteImage().end() .addProp("goods.name", String.class).end() .endChild(); mf.build(SearchHistory.class); mf.build(Formid.class); mf.build(Settings.class) .fk("province").map("name", "provinceName").show("name").hide().showForm().showEdit().end() .fk("city").map("name", "cityName").show("name").hide().showForm().showEdit().end() .fk("district").map("name", "expAreaName").show("name").hide().showForm().showEdit().end() .fk("goods").show("name").hide().end() .prop("name").required().end() .prop("tel").required().end() .prop("autoDelivery").values(new Object[] {"true", "false"}).encoder(new BooleanConverter()).decoder(new BooleanConverter()).end() .prop("discoveryImg").absoluteImage().hide().end() .prop("countdown").hide() .prop("reset").hide() .prop("provinceName").show().hideForm().hideEdit().end() .prop("cityName").show().hideForm().hideEdit().end() .prop("expAreaName").show().hideForm().hideEdit().end(); mf.build(Shipper.class) .filters("name", "code").op(Op.RLIKE) .prop("name").required().end() .prop("code").required().end() .prop("enabled").values(new Object[] {"true", "false"}).encoder(new BooleanConverter()).decoder(new BooleanConverter()).end(); mf.build(Category.class).addCRUD() .showList("iconUrl", "name", "isChannel", "isShow", "isCategory", "sortOrder") .filters("name").op(Op.RLIKE) .prop("iconUrl").absoluteImage().inRow().sortOrder(1).required().end() .prop("name").required().sortOrder(2) .prop("isChannel").defaultValue("true").required().sortOrder(3).end() .prop("keywords").sortOrder(4) .prop("isShow").defaultValue("true").sortOrder(5) .prop("isCategory").defaultValue("true").sortOrder(6) .prop("pHeight").sortOrder(7) .prop("sortOrder").sortOrder(8) .prop("imgUrl").absoluteImage().inRow().sortOrder(9).end() .prop("parentId").hide() .prop("showIndex").hide() .prop("level").hide() .prop("frontName").hide() .prop("frontDesc").hide(); mf.build(Goods.class).addCRUD() .showList("listPicUrl", "name", "category", "sortOrder", "sellVolume", "retailPrice", "goodsNumber", "isIndex", "isOnSale") .filters("name").op(Op.RLIKE) .filters("category").eq() .filters("retailPrice").ops(Op.LARGE_EQUAL, Op.LESS_EQUAL) .filters("goodsNumber").ops(Op.LARGE_EQUAL, Op.LESS_EQUAL) .deletedProp("isDelete", Boolean.TRUE) .fk("category").show("name").end() .fk("freightTemplate").show("name").end() .prop("goodsNumber").feature(Feature.NUMBER).end() .prop("sellVolume").feature(Feature.NUMBER).end() .prop("goodsBrief").inRow().end() .prop("httpsPicUrl").absoluteImage().inRow().hide().end() .prop("listPicUrl").absoluteImage().inRow().end() .prop("freightTemplate").fk().ref("id").map("id", "freightTemplateId").show("name").end() .prop("freightType").values(new Object[] {"按件", "按重"}).encoder(new FreightTypeConverter()).decoder(new FreightTypeConverter()).end() .prop("goodsDesc").editor().end() .prop("freightTemplateId").hide().end() .prop("specificationId1").hide().end() .prop("isIndex").values(new Object[] {true, false}).defaultValue(true) .prop("keywords").hide().end() .addChild(GoodsGallery.class).addCRUD() .showList("goods", "imgUrl", "imgDesc", "sortOrder", "isDelete") .deletedProp("isDelete", true) .prop("imgUrl").absoluteImage().inRow().end() .endChild() .addChild(GoodsSpecification.class).addCRUD() .fk("goods").show("name").end() .fk("specification").show("name").end() .prop("picUrl").absoluteImage().end() .endChild() .addChild(Product.class).addCRUD() .fk("goods").show("name").show().hideList().end() .deletedProp("isDelete", true) .prop("goodsSpecificationIds").hide().end() .prop("goodsSn").end() .prop("goodsName").hide().showList().end() .prop("goodsNumber").end() .prop("retailPrice").end() .prop("cost").end() .prop("goodsWeight").end() .prop("hasChange").end() .prop("isOnSale").end() .prop("isDelete").end() .endChild(); mf.build(Specification.class) .prop("name").required(); mf.build(Product.class); mf.build(Ad.class) .filters("endTime").ops(Op.LARGE_EQUAL, Op.LESS_EQUAL) .fk("goods").show("name").end() .prop("linkType").hide().end() .prop("link").hide().end() .prop("imageUrl").absoluteImage().showList().end() .prop("endTime").dateTime().encoder(new DateEncoder("yyyy-MM-dd HH:mm:ss")).decoder(new DateDecoder("yyyy-MM-dd HH:mm:ss")).end() .prop("enabled").values(new Object[] {"true", "false"}) .prop("isDelete").values(new Object[] {"true", "false"}) .encoder(new BooleanConverter()) .decoder(new BooleanConverter()).end(); mf.build(ExceptArea.class); mf.build(ExceptAreaDetail.class); mf.build(Keywords.class); mf.build(Notice.class) .filters("content").op(Op.RLIKE) .filters("endTime").ops(Op.LARGE_EQUAL, Op.LESS_EQUAL) .prop("content").end() .prop("endTime").dateTime().encoder(new DateEncoder("yyyy-MM-dd HH:mm:ss")).decoder(new DateDecoder("yyyy-MM-dd HH:mm:ss")).end() .prop("isDelete").encoder(new BooleanConverter()).decoder(new BooleanConverter()).end(); mf.build(Region.class) .filters("parent.name").eq() .filters("name").op(Op.RLIKE) .filters("type").eq() .fk("parent").show("name").end() .prop("type").values(new Object[] {"一级", "二级", "三级", "四级"}) .encoder(v -> { if("一级".equals(v)) return 0; else if("二级".equals(v)) return 1; else if("三级".equals(v)) return 2; else return 3;}) .decoder(v -> { if(v == null) return v; else { int level = Boolean.TRUE.equals(v) ? 1 : Integer.valueOf(v.toString()); if(level == 0) return "一级"; else if(level==1) return "二级"; else if(level==2) return "三级";else return "四级"; }}) .prop("areaCode").end() .prop("agencyId").hide().end() .prop("area").hide().end() .prop("farArea").hide().end(); mf.build(ShowSettings.class) .prop("banner").values(new Object[] {"true", "false"}).encoder(new BooleanConverter()).decoder(new BooleanConverter()).end() .prop("channel").values(new Object[] {"true", "false"}).encoder(new BooleanConverter()).decoder(new BooleanConverter()).end() .prop("indexBannerImg").values(new Object[] {"true", "false"}).encoder(new BooleanConverter()).decoder(new BooleanConverter()).end() .prop("notice").values(new Object[] {"true", "false"}).encoder(new BooleanConverter()).decoder(new BooleanConverter()).end(); } protected void defMenus(MenuFactory mf) { mf.build("订单列表").uri("/orderList").icon("el-icon-s-grid") .addItem(Order.class).name("订单列表").uri("/order").icon("el-icon-s-shop"); mf.build("商品管理").uri("/prod").icon("el-icon-s-grid") .addItem(Category.class).name("商品分类").icon("el-icon-office-building") .addItem(Specification.class).name("商品型号").icon("el-icon-notebook-2") .addItem(Goods.class).name("商品列表").icon("el-icon-goods"); mf.build("购物车").uri("/cartList").icon("el-icon-s-grid") .addItem(Cart.class).name("购物车").uri("/cart").icon("el-icon-shopping-cart-1"); mf.build("用户列表").uri("/memberList").icon("el-icon-s-grid") .addItem(MemberUser.class).name("用户列表").uri("/memberUser").icon("el-icon-user"); mf.build("店铺设置").uri("/store").icon("el-icon-setting") .addItem(ShowSettings.class).name("显示设置").uri("/showSettings").icon("el-icon-s-data") .addItem(Ad.class).name("广告列表").uri("/ad").icon("el-icon-s-operation") .addItem(Notice.class).name("公告管理").uri("/notice").icon("el-icon-date") .addItem(FreightTemplate.class).name("运费模板").uri("/freightTemplate").icon("el-icon-tickets") .addItem(Shipper.class).name("快递设置").uri("/shipper").icon("el-icon-s-shop") .addItem(Settings.class).name("寄件设置").uri("/settings").icon("el-icon-truck"); } public class DateEncoder implements Encoder { private String pattern = "yyyy-MM-dd HH:mm:ss"; private DateEncoder(String pattern) { this.pattern = pattern; } public Object encode(Object v) { if(v == null || "0".equals(v.toString())) return ""; return DateUtils.parseDate(v.toString(), this.pattern).getTime()/1000; } } public class DateDecoder implements Decoder { private String pattern = "yyyy-MM-dd HH:mm:ss"; private DateDecoder(String pattern) { this.pattern = pattern; } public Object decode(Object v) { if(v == null || "0".equals(v.toString())) return ""; return DateUtils.formatDate(new Date(Integer.valueOf(v.toString()) * 1000L), pattern); } } public class OrderStatusConvert implements Encoder, Decoder { @Override public Object decode(Object value) { if(value != null) { int v = Integer.valueOf(value.toString()); if(300 == v) { return "待发货"; } else if(301 == v) { return "待收货"; } else if(401 == v) { return "已收货"; } else if(102 == v) { return "已关闭"; } else if(101 == v) { return "待付款"; } } return value; } @Override public Object encode(Object value) { if("待发货".equals(value)) { return 300; } else if("待收货".equals(value)) { return 301; } else if("已收货".equals(value)) { return 401; } else if("已关闭".equals(value)) { return 102; } else if("待付款".equals(value)) { return 101; } return value; } } public class BooleanConverter implements Encoder, Decoder { @Override public Object encode(Object value) { return "true".equals(value) ? 1 : 0; } @Override public Object decode(Object value) { if(value == null) { return value; } if("true".equals(value.toString()) || "false".equals(value.toString())) { return value; } return Integer.valueOf(value.toString()) == 1 ? "true" : "false"; } } public class FreightTypeConverter implements Encoder, Decoder { public Object encode(Object value) { return "按件".equals(value) ? 0 : 1; } public Object decode(Object value) { if(value == null) return value; if("true".equals(value.toString())) return "按重"; else if("false".equals(value.toString())) return "按件"; return Integer.valueOf(value.toString()) == 0 ? "按件" : "按重"; } } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/service/SettingsService.java<|end_filename|> package org.needle.bookingdiscount.server.service; import java.util.Optional; import java.util.regex.Pattern; import org.needle.bookingdiscount.domain.member.MemberUser; import org.needle.bookingdiscount.domain.member.MemberUser.JsonMemberUser; import org.needle.bookingdiscount.domain.support.ShowSettings; import org.needle.bookingdiscount.domain.support.ShowSettings.JsonShowSettings; import org.needle.bookingdiscount.server.exception.ServiceException; import org.needle.bookingdiscount.server.repository.member.MemberUserRepository; import org.needle.bookingdiscount.server.repository.support.ShowSettingsRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; @Service @Transactional public class SettingsService { private Pattern mobilePattern = Pattern.compile("^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1})|(16[0-9]{1})|(19[0-9]{1}))+\\d{8})$"); @Autowired private ShowSettingsRepository showSettingsRepository; @Autowired private MemberUserRepository memberUserRepository; public JsonShowSettings showSettings() { Optional<ShowSettings> ssOpt = showSettingsRepository.findById(1L); ShowSettings info = ssOpt.isPresent() ? ssOpt.get() : new ShowSettings(); return new JsonShowSettings(info); } public JsonMemberUser save(Long userId, String name, String mobile) { if(mobile.length() < 11) { throw new ServiceException(200, "手机号长度不对"); } else if(mobilePattern.matcher(mobile).find()) { throw new ServiceException(300, "手机号不对"); } if(StringUtils.hasText(name) || StringUtils.hasText(mobile)) { throw new ServiceException(100, "姓名或手机不能为空"); } MemberUser user = memberUserRepository.findById(userId).get(); user.setName(name); user.setMobile(mobile); user.setNameMobile(1); memberUserRepository.save(user); return new JsonMemberUser(user); } public JsonMemberUser userDetail(Long userId) { MemberUser user = memberUserRepository.findById(userId).get(); return new JsonMemberUser(user); } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/repository/product/SpecificationRepository.java<|end_filename|> package org.needle.bookingdiscount.server.repository.product; import org.needle.bookingdiscount.domain.product.Specification; import org.springframework.data.repository.PagingAndSortingRepository; public interface SpecificationRepository extends PagingAndSortingRepository<Specification, Long> { } <|start_filename|>booking-admin/src/main/java/org/needle/bookingdiscount/admin/service/RegionService.java<|end_filename|> package org.needle.bookingdiscount.admin.service; import org.needle.bookingdiscount.admin.repository.RegionRepository; import org.needle.bookingdiscount.domain.support.Region; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class RegionService { @Autowired private RegionRepository regionRepository; public Region findById(Long id) { return regionRepository.findById(id).get(); } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/repository/order/OrderExpressRepository.java<|end_filename|> package org.needle.bookingdiscount.server.repository.order; import java.util.List; import org.needle.bookingdiscount.domain.order.OrderExpress; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; public interface OrderExpressRepository extends PagingAndSortingRepository<OrderExpress, Long> { @Query("from OrderExpress t where t.order.id=?1 ") public List<OrderExpress> findByOrder(Long orderId); } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/freight/FreightTemplateDetail.java<|end_filename|> package org.needle.bookingdiscount.domain.freight; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.needle.bookingdiscount.domain.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper=true) @Entity @Table(name="needle_freight_template_detail") public class FreightTemplateDetail extends BaseEntity { @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="template_id") private FreightTemplate template; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="group_id") private FreightTemplateGroup group; @Column(name="area") private Integer area; @Column(name="is_delete", columnDefinition="tinyint(1) default 0") private Boolean isDelete; } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/repository/support/NoticeRepository.java<|end_filename|> package org.needle.bookingdiscount.server.repository.support; import java.util.List; import org.needle.bookingdiscount.domain.support.Notice; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; public interface NoticeRepository extends PagingAndSortingRepository<Notice, Long> { @Query("from Notice t where t.isDelete=?1 order by t.id asc") public List<Notice> findByIsDelete(Boolean isDelete); } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/member/Address.java<|end_filename|> package org.needle.bookingdiscount.domain.member; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Transient; import org.needle.bookingdiscount.domain.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper=true) @Entity @Table(name="needle_address") public class Address extends BaseEntity { @Column(name="name", length=50) private String name; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="user_id") private MemberUser user; @Column(name="country_id") private Long countryId; @Column(name="province_id") private Long provinceId; @Column(name="city_id") private Long cityId; @Column(name="district_id") private Long districtId; @Column(name="address", length=120) private String address; @Column(name="mobile", length=60) private String mobile; @Column(name="is_default", columnDefinition="tinyint(1) unsigned default 0") private Boolean isDefault; @Column(name="is_delete", columnDefinition="tinyint(1) default 0") private Boolean isDelete; @Transient private String provinceName; @Transient private String cityName; @Transient private String districtName; @Transient private String fullRegion; @Data public static class JsonAddress { private Long id; private String name; private Long user_id; private Long country_id; private Long province_id; private Long city_id; private Long district_id; private String address; private String mobile; private Boolean is_default; private Boolean is_delete; private String province_name; private String city_name; private String district_name; private String full_region; public JsonAddress() {} public JsonAddress(Address address) { this.id = address.getId(); this.name = address.getName(); this.user_id = address.getUser() == null ? null : address.getUser().getId(); this.country_id = address.getCountryId(); this.province_id = address.getProvinceId(); this.city_id = address.getCityId(); this.district_id = address.getDistrictId(); this.address = address.getAddress(); this.mobile = address.getMobile(); this.is_default = address.getIsDefault(); this.is_delete = address.getIsDelete(); this.province_name = address.getProvinceName(); this.city_name = address.getCityName(); this.district_name = address.getDistrictName(); this.full_region = address.getFullRegion(); } } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/repository/product/GoodsGalleryRepository.java<|end_filename|> package org.needle.bookingdiscount.server.repository.product; import java.util.List; import org.needle.bookingdiscount.domain.product.GoodsGallery; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; public interface GoodsGalleryRepository extends PagingAndSortingRepository<GoodsGallery, Long> { @Query("from GoodsGallery t where t.goods.id=?1 and t.isDelete=false order by t.sortOrder") public List<GoodsGallery> findByGoods(Long goodsId, Pageable pageable); } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/order/Formid.java<|end_filename|> package org.needle.bookingdiscount.domain.order; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.needle.bookingdiscount.domain.BaseEntity; import org.needle.bookingdiscount.domain.member.MemberUser; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper=true) @Entity @Table(name="needle_formid") public class Formid extends BaseEntity { @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="user_id") private MemberUser user; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="order_id") private Order order; @Column(name="form_id", length=255) private String formId; @Column(name="add_time") private Integer addTime; @Column(name="use_times", columnDefinition="tinyint(1) default 0") private Integer useTimes; } <|start_filename|>booking-admin/src/main/java/org/needle/bookingdiscount/error/ExceptionController.java<|end_filename|> package org.needle.bookingdiscount.error; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.needleframe.core.MessageCode; import org.needleframe.core.web.response.ResponseMessage; import org.needleframe.security.SecurityUtils; import org.needleframe.security.UserDetailsServiceImpl.SessionUser; import org.needleframe.utils.JsonUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.boot.web.servlet.error.ErrorController; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.context.request.WebRequest; @Controller public class ExceptionController implements ErrorController { private Logger logger = LoggerFactory.getLogger(ExceptionController.class); @Autowired private ErrorAttributes errorAttributes; private static final String error_default = "/error"; public String getErrorPath() { return error_default; } @RequestMapping(value = error_default, produces = {MediaType.APPLICATION_JSON_VALUE}) @ResponseBody public ResponseMessage error(WebRequest wRequest, HttpServletRequest request, HttpServletResponse response) { logger.info("error(..) => Error: url={}, error:url={}", request.getRequestURL()); response.setCharacterEncoding("UTF-8"); Map<String, Object> body = errorAttributes.getErrorAttributes(wRequest, true); logger.info("error(..) => Error: url={}, error:url={}, body={}", request.getRequestURL(), body); SessionUser user = SecurityUtils.getUser(); if(user == null) { return ResponseMessage.failed(MessageCode.SESSION_EXPIRED, "会话已过期"); } return ResponseMessage.failed(JsonUtils.toJSON(body)); } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/repository/support/ShowSettingsRepository.java<|end_filename|> package org.needle.bookingdiscount.server.repository.support; import org.needle.bookingdiscount.domain.support.ShowSettings; import org.springframework.data.repository.PagingAndSortingRepository; public interface ShowSettingsRepository extends PagingAndSortingRepository<ShowSettings, Long> { } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/service/CatalogService.java<|end_filename|> package org.needle.bookingdiscount.server.service; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.needle.bookingdiscount.domain.product.Category; import org.needle.bookingdiscount.domain.product.Category.JsonCategory; import org.needle.bookingdiscount.domain.product.Goods; import org.needle.bookingdiscount.domain.product.Goods.JsonGoods; import org.needle.bookingdiscount.server.repository.product.CategoryRepository; import org.needle.bookingdiscount.server.repository.product.GoodsRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.ModelMap; @Service @Transactional public class CatalogService { @Autowired private CategoryRepository categoryRepository; @Autowired private GoodsRepository goodsRepository; public ModelMap getIndexData(Long id) { Pageable pageable = PageRequest.of(0, 10); List<Category> data = categoryRepository.findByIsCategoryAndParentId(true, 0L, pageable); Category currentCategory = null; if(id != null) { Optional<Category> current = categoryRepository.findById(id); currentCategory = current.isPresent() ? current.get() : null; } if(currentCategory == null && !data.isEmpty()) { currentCategory = data.get(0); } // if(currentCategory != null) { // categoryList.add(new JsonCategory(currentCategory)); // } return new ModelMap().addAttribute("categoryList", data.stream().map(c -> new JsonCategory(c)).collect(Collectors.toList())); } public ModelMap getCurrentData(Long id) { Category currentCategory = null; if(id != null) { Optional<Category> current = categoryRepository.findById(id); currentCategory = current.isPresent() ? current.get() : null; } ModelMap model = new ModelMap(); if(currentCategory != null) { model.addAttribute("id", currentCategory.getId()); model.addAttribute("name", currentCategory.getName()); model.addAttribute("img_url", currentCategory.getImgUrl()); model.addAttribute("p_height", currentCategory.getParentId()); } return model; } public List<JsonGoods> getCurrentListData(int page, int size, Long id) { Long categoryId = id; Pageable pageable = PageRequest.of(page, size); if (categoryId == null || categoryId == 0) { List<Goods> list = goodsRepository.findByIsOnSaleAndIsDelete(true, false, pageable); return list.stream().map(g -> new JsonGoods(g)).collect(Collectors.toList()); } else { List<Goods> list = goodsRepository.findByCategoryAndIsOnSaleAndIsDelete(categoryId, true, false, pageable); return list.stream().map(g -> new JsonGoods(g)).collect(Collectors.toList()); } } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/service/OrderService.java<|end_filename|> package org.needle.bookingdiscount.server.service; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Optional; import java.util.Random; import java.util.stream.Collectors; import org.needle.bookingdiscount.domain.cart.Cart; import org.needle.bookingdiscount.domain.cart.Cart.JsonCart; import org.needle.bookingdiscount.domain.member.Address; import org.needle.bookingdiscount.domain.member.MemberUser; import org.needle.bookingdiscount.domain.order.Order; import org.needle.bookingdiscount.domain.order.Order.HandleOption; import org.needle.bookingdiscount.domain.order.Order.JsonOrder; import org.needle.bookingdiscount.domain.order.Order.TextCode; import org.needle.bookingdiscount.domain.order.OrderExpress; import org.needle.bookingdiscount.domain.order.OrderExpress.JsonOrderExpress; import org.needle.bookingdiscount.domain.order.OrderGoods; import org.needle.bookingdiscount.domain.order.OrderGoods.JsonOrderGoods; import org.needle.bookingdiscount.domain.product.Product; import org.needle.bookingdiscount.server.exception.ServiceException; import org.needle.bookingdiscount.server.repository.cart.CartRepository; import org.needle.bookingdiscount.server.repository.member.AddressRepository; import org.needle.bookingdiscount.server.repository.member.MemberUserRepository; import org.needle.bookingdiscount.server.repository.order.OrderExpressRepository; import org.needle.bookingdiscount.server.repository.order.OrderGoodsRepository; import org.needle.bookingdiscount.server.repository.order.OrderRepository; import org.needle.bookingdiscount.server.repository.product.GoodsRepository; import org.needle.bookingdiscount.server.repository.product.ProductRepository; import org.needle.bookingdiscount.server.repository.support.RegionRepository; import org.needle.bookingdiscount.utils.JsonUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.ModelMap; import org.springframework.util.Base64Utils; @Service @Transactional public class OrderService { @Autowired private OrderRepository orderRepository; @Autowired private AddressRepository addressRepository; @Autowired private CartRepository cartRepository; @Autowired private MemberUserRepository memberUserRepository; @Autowired private GoodsRepository goodsRepository; @Autowired private ProductRepository productRepository; @Autowired private OrderGoodsRepository orderGoodsRepository; @Autowired private RegionRepository regionRepository; @Autowired private OrderExpressRepository orderExpressRepository; @Value("${aliexpress.sfLastNo}") private String sfLastNo; @Value("${aliexpress.appcode}") private String appcode; public static void main(String[] args) { System.out.println(String.format("%08d", 1)); System.out.println(new OrderService().generateOrderNumber(1L)); System.out.println(new Date().getTime() / 1000); System.out.println(new Long(new Date().getTime() / 1000).intValue()); System.out.println((int) (new Date().getTime() / 1000)); System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(1613141392 * 1000L))); System.out.println(new Random().nextInt(100)); System.out.println(new Random().nextInt(100)); System.out.println(new Random().nextInt(100)); System.out.println(new Random().nextInt(100)); System.out.println(new Random().nextInt(100)); System.out.println(new Random().nextInt(100)); System.out.println(new Random().nextInt(100)); System.out.println(new Random().nextInt(100)); } private String generateOrderNumber(Long id) { String yyyyMMdd = new SimpleDateFormat("yyyyMMdd").format(new Date()); Long seq = id % 99999999; return new StringBuilder() .append(yyyyMMdd.charAt(3)) .append(yyyyMMdd.charAt(2)) .append(yyyyMMdd.substring(0, 2)) .append(yyyyMMdd.substring(4)) .append(new Random().nextInt(100)) .append(String.format("%09d", seq)).toString(); } public ModelMap submit(Long userId, Long addressId, BigDecimal freightPrice, int offlinePay, String postscript) { if(addressId == null) { throw new ServiceException("请选择收货 地址"); } Optional<Address> addressOpt = addressRepository.findById(addressId); if(!addressOpt.isPresent()) { throw new ServiceException("收货地址不存在 "); } Address checkedAddress = addressOpt.get(); // 获取要购买的商品 List<Cart> checkedGoodsList = cartRepository.findByUserAndCheckedAndIsDelete(userId, 1, false); if(checkedGoodsList.isEmpty()) { throw new ServiceException("请选择商品 "); } int checkPrice = 0; int checkStock = 0; for (Cart item : checkedGoodsList) { Product product = item.getProduct(); if(item.getNumber() > product.getGoodsNumber()) { checkStock++; } if(Math.abs(item.getRetailPrice().subtract(item.getAddPrice()).doubleValue()) > 0.01) { checkPrice++; } } if(checkStock > 0) { throw new ServiceException(400, "库存不足,请重新下单 "); } if(checkPrice > 0) { throw new ServiceException(400, "价格发生变化,请重新下单 "); } // 获取订单使用的红包 // 如果有用红包,则将红包的数量减少,当减到0时,将该条红包删除 // 统计商品总价 BigDecimal goodsTotalPrice = new BigDecimal(0.00); for (Cart cartItem : checkedGoodsList) { goodsTotalPrice = goodsTotalPrice.add(new BigDecimal(cartItem.getNumber()).multiply(cartItem.getRetailPrice())); } // 订单价格计算 BigDecimal orderTotalPrice = goodsTotalPrice.add(freightPrice); // 订单的总价 BigDecimal actualPrice = orderTotalPrice.subtract(new BigDecimal(0.00)); // 减去其它支付的金额后,要实际支付的金额 比如满减等优惠 int currentTime = new Long(new Date().getTime() / 1000).intValue(); String print_info = ""; for(int i = 0; i < checkedGoodsList.size(); i++) { Cart item = checkedGoodsList.get(i); print_info = print_info + (i + 1) + '、' + item.getGoodsAka() + "【" + item.getNumber() + "】 "; } MemberUser user = memberUserRepository.findById(userId).get(); Order orderInfo = new Order(); orderInfo.setUser(user); orderInfo.setOrderSn(System.currentTimeMillis() + ""); orderInfo.setConsignee(checkedAddress.getName()); orderInfo.setMobile(checkedAddress.getMobile()); orderInfo.setCountry(1L); orderInfo.setProvince(checkedAddress.getProvinceId()); orderInfo.setCity(checkedAddress.getCityId()); orderInfo.setDistrict(checkedAddress.getDistrictId()); orderInfo.setAddress(checkedAddress.getAddress()); orderInfo.setOrderStatus(101); orderInfo.setFreightPrice(freightPrice.intValue()); orderInfo.setPostscript(Base64Utils.encodeToString(postscript.getBytes())); orderInfo.setAddTime(currentTime); orderInfo.setConfirmTime(0); orderInfo.setPayTime(0); orderInfo.setShippingTime(0); orderInfo.setDealdoneTime(0); orderInfo.setGoodsPrice(goodsTotalPrice); orderInfo.setOrderPrice(orderTotalPrice); orderInfo.setActualPrice(actualPrice); orderInfo.setChangePrice(actualPrice); orderInfo.setPrintInfo(print_info); orderInfo.setOfflinePay(offlinePay); orderInfo.setExpressValue(new BigDecimal(0.0)); orderInfo.setPayId("0"); orderInfo.setPayName(""); orderInfo.setPayStatus(0); orderInfo.setPrintStatus(0); orderInfo.setOrderType(0); orderInfo.setRemark(""); orderInfo.setShippingFee(new BigDecimal(0)); orderInfo.setShippingStatus(0); orderInfo.setIsDelete(false); orderRepository.save(orderInfo); orderInfo.setOrderSn(generateOrderNumber(orderInfo.getId())); orderRepository.save(orderInfo); // 将商品信息录入数据库 for(Cart goodsItem : checkedGoodsList) { OrderGoods orderGoods = new OrderGoods(); orderGoods.setUser(user); orderGoods.setOrder(orderInfo); orderGoods.setGoods(goodsItem.getGoods()); orderGoods.setProduct(goodsItem.getProduct()); orderGoods.setGoodsName(goodsItem.getGoodsName()); orderGoods.setGoodsAka(goodsItem.getGoodsAka()); orderGoods.setListPicUrl(goodsItem.getListPicUrl()); orderGoods.setRetailPrice(goodsItem.getRetailPrice()); orderGoods.setNumber(goodsItem.getNumber()); orderGoods.setGoodsSpecificationNameValue(goodsItem.getGoodsSpecificationNameValue()); orderGoods.setGoodsSpecificationIds(goodsItem.getGoodsSpecificationIds()); orderGoods.setIsDelete(false); orderGoodsRepository.save(orderGoods); } cartRepository.findByUserAndCheckedAndIsDelete(userId, 1, false).forEach(cart -> { cart.setIsDelete(true); cartRepository.save(cart); }); return new ModelMap().addAttribute("orderInfo", new JsonOrder(orderInfo)); } public List<JsonOrder> list(Long userId, int showType, int page, int size) { List<Integer> status = getOrderStatus(showType); Pageable pageable = PageRequest.of(page, size); List<Order> orderList = orderRepository.findByUserAndIsDeleteAndOrderTypeLessThanAndOrderStatusIn(userId, false, 7, status, pageable); List<JsonOrder> newOrderList = new ArrayList<JsonOrder>(); for(Order order : orderList) { JsonOrder item = new JsonOrder(order); List<OrderGoods> orderGoods = orderGoodsRepository.findByOrder(order.getId()); item.setGoodsList(orderGoods.stream().map(og -> new JsonOrderGoods(og)).collect(Collectors.toList())); item.setGoodsCount(0); item.getGoodsList().forEach(goodsOrder -> { item.setGoodsCount(item.getGoodsCount() + goodsOrder.getNumber()); }); item.setAdd_time(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(order.getAddTime() * 1000L))); item.setOrder_status_text(getOrderStatusText(order)); item.setHandleOption(getOrderHandleOption(order)); newOrderList.add(item); } return newOrderList; } public ModelMap detail(Long orderId, Long userId) { int currentTime = (int) (new Date().getTime() / 1000); Optional<Order> orderInfoOpt = orderRepository.findById(orderId); if(!orderInfoOpt.isPresent()) { throw new ServiceException("订单不存在"); } Order order = orderInfoOpt.get(); if(order.getUser().getId().longValue() != userId.longValue()) { throw new ServiceException("没有查看权限"); } JsonOrder orderInfo = new JsonOrder(order); orderInfo.setProvince_name(regionRepository.findById(order.getProvince()).get().getName()); orderInfo.setCity_name(regionRepository.findById(order.getCity()).get().getName()); orderInfo.setDistrict_name(regionRepository.findById(order.getDistrict()).get().getName()); orderInfo.setFull_region(orderInfo.getProvince_name() + orderInfo.getCity_name() + orderInfo.getDistrict_name()); orderInfo.setPostscript(org.needle.bookingdiscount.utils.Base64Utils.decode(order.getPostscript())); List<OrderGoods> orderGoods = orderGoodsRepository.findByOrder(order.getId()); int goodsCount = 0; for(OrderGoods gitem : orderGoods) { goodsCount += gitem.getNumber(); } orderInfo.setOrder_status_text(getOrderStatusText(order)); // 订单状态的处理 if(order.getConfirmTime() == null || order.getConfirmTime() <= 0) { orderInfo.setConfirm_time(""); } else { orderInfo.setConfirm_time(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(order.getConfirmTime() * 1000L))); } if(order.getDealdoneTime() == null || order.getDealdoneTime() <= 0) { orderInfo.setDealdone_time(""); } else { orderInfo.setDealdone_time(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(order.getDealdoneTime() * 1000L))); } if(order.getPayTime() == null || order.getPayTime() <= 0) { orderInfo.setPay_time(""); } else { orderInfo.setPay_time((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(order.getDealdoneTime() * 1000L)))); } if(order.getShippingTime() == null || order.getShippingTime() <= 0) { orderInfo.setShipping_time(""); } else { orderInfo.setShipping_time((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(order.getShippingTime() * 1000L)))); orderInfo.setConfirm_remainTime(order.getShippingTime() + 10 * 24 * 60 * 60); } if(order.getOrderStatus() == 101 || order.getOrderStatus() == 801) { orderInfo.setFinal_pay_time(order.getAddTime() + 24 * 60 * 60); if(orderInfo.getFinal_pay_time() < currentTime) { //超过时间不支付,更新订单状态为取消 order.setOrderStatus(102); orderRepository.save(order); } } orderInfo.setAdd_time((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(order.getAddTime() * 1000L)))); // 订单可操作的选择,删除,支付,收货,评论,退换货 HandleOption handleOption = getOrderHandleOption(order); TextCode textCode = getOrderTextCode(order); ModelMap model = new ModelMap(); model.addAttribute("orderInfo", orderInfo); model.addAttribute("orderGoods", orderGoods.stream().map(og -> new JsonOrderGoods(og)).collect(Collectors.toList())); model.addAttribute("handleOption", handleOption); model.addAttribute("textCode", textCode); model.addAttribute("goodsCount", goodsCount); return model; } public JsonOrder delete(Long orderId, Long userId) { Order order = orderRepository.findById(orderId).get(); if(order.getUser().getId() != userId) { throw new ServiceException("没有删除权限"); } // 检测是否能够取消 HandleOption handleOption = getOrderHandleOption(order); if(!handleOption.delete) { throw new ServiceException("订单不能删除"); } order.setIsDelete(true); orderRepository.save(order); return new JsonOrder(order); } public JsonOrder cancel(Long orderId, Long userId) { Order order = orderRepository.findById(orderId).get(); if(order.getUser().getId().longValue() != userId.longValue()) { throw new ServiceException("没有取消权限"); } // 检测是否能够取消 HandleOption handleOption = getOrderHandleOption(order); if (!handleOption.cancel) { throw new ServiceException("订单不能取消"); } List<OrderGoods> goodsInfo = orderGoodsRepository.findByOrder(orderId); //取消订单,还原库存 for (OrderGoods item : goodsInfo) { int number = item.getNumber(); goodsRepository.increment(number, item.getGoods().getId()); productRepository.increment(number, item.getProduct().getId()); } // 设置订单已取消状态 order.setOrderStatus(102); orderRepository.save(order); return new JsonOrder(order); } public JsonOrder confirm(Long orderId, Long userId) { Order order = orderRepository.findById(orderId).get(); if(order.getUser().getId().longValue() != userId.longValue()) { throw new ServiceException("没有确认权限"); } // 检测是否能够取消 HandleOption handleOption = getOrderHandleOption(order); if (!handleOption.confirm) { throw new ServiceException("订单不能确认"); } // 设置订单已取消状态 int currentTime = (int) (new Date().getTime() / 1000); order.setOrderStatus(401); order.setConfirmTime(currentTime); orderRepository.save(order); return new JsonOrder(order); } public ModelMap count(int showType, Long userId) { List<Integer> status = getOrderStatus(showType); long allCount = orderRepository.countByUserAndIsDeleteAndOrderStatus(userId, false, status); return new ModelMap().addAttribute("allCount", allCount); } public ModelMap orderCount(Long userId) { long toPay = orderRepository.countByUserAndIsDeleteAndOrderTypeLessThanAndOrderStatusIn(userId, false, 7, Arrays.asList(101, 801)); long toDelivery = orderRepository.countByUserAndIsDeleteAndOrderTypeLessThanAndOrderStatusIn(userId, false, 7, Arrays.asList(300)); long toReceive = orderRepository.countByUserAndIsDeleteAndOrderTypeLessThanAndOrderStatusIn(userId, false, 7, Arrays.asList(301)); ModelMap model = new ModelMap(); model.addAttribute("toPay", toPay); model.addAttribute("toDelivery", toDelivery); model.addAttribute("toReceive", toReceive); return model; } public JsonOrderExpress express(Long orderId) { int currentTime = (int) (new Date().getTime() / 1000); List<OrderExpress> orderExpressList = orderExpressRepository.findByOrder(orderId); if(orderExpressList.isEmpty()) { throw new ServiceException(400, "暂无物流信息"); } OrderExpress info = orderExpressList.get(0); OrderExpress expressInfo = info; // 如果is_finish == 1;或者 updateTime 小于 10分钟, int updateTime = info.getUpdateTime(); int com = (currentTime - updateTime) / 60; boolean is_finish = info.getIsFinish() == null ? false : info.getIsFinish(); if(is_finish) { return new JsonOrderExpress(expressInfo); } else if (updateTime != 0 && com < 20) { return new JsonOrderExpress(expressInfo); } else { String shipperCode = expressInfo.getShipperCode(); String expressNo = expressInfo.getLogisticCode(); String code = shipperCode.substring(0, 2); String shipperName = ""; if(code == "SF") { shipperName = "SFEXPRESS"; expressNo = expressNo + ':' + sfLastNo; } else { shipperName = shipperCode; } ExpressInfo lastExpressInfo = getExpressInfo(shipperName, expressNo); int deliverystatus = lastExpressInfo.deliverystatus; int newUpdateTime = lastExpressInfo.updateTime; newUpdateTime = (int) (new Date(newUpdateTime).getTime() / 1000); String deliverystatusString = getDeliverystatus(deliverystatus); Boolean issign = lastExpressInfo.issign; List<?> list = lastExpressInfo.list; String traces = JsonUtils.toJSON(list); info.setExpressStatus(deliverystatusString); info.setIsFinish(issign); info.setTraces(traces); info.setUpdateTime(updateTime); orderExpressRepository.save(info); return new JsonOrderExpress(expressInfo); } } private String getDeliverystatus(int status) { if (status == 0) { return "快递收件(揽件)"; } else if (status == 1) { return "在途中"; } else if (status == 2) { return "正在派件"; } else if (status == 3) { return "已签收"; } else if (status == 4) { return "派送失败(无法联系到收件人或客户要求择日派送,地址不详或手机号不清)"; } else if (status == 5) { return "疑难件(收件人拒绝签收,地址有误或不能送达派送区域,收费等原因无法正常派送)"; } else if (status == 6) { return "退件签收"; } return "未知状态"; } class ExpressInfo { int deliverystatus; int updateTime; Boolean issign; List<?> list = new ArrayList<Object>(); } private ExpressInfo getExpressInfo(String shipperName, String expressNo) { // String appCode = "APPCODE " + appcode; // String options = { // method: 'GET', // url: 'http://wuliu.market.alicloudapi.com/kdi?no=' + expressNo + '&type=' + shipperName, // headers: { // "Content-Type": "application/json; charset=utf-8", // "Authorization": appCode // } // }; // let sessionData = yield rp(options); // sessionData = JSON.parse(sessionData); // return sessionData.result; return new ExpressInfo(); } public List<?> orderGoods(Long orderId, Long userId) { if (orderId != null && orderId > 0) { List<OrderGoods> orderGoodsList = orderGoodsRepository.findByOrder(orderId); List<JsonOrderGoods> newOrderGoodsList = new ArrayList<JsonOrderGoods>(); for(OrderGoods gitem : orderGoodsList) { JsonOrderGoods jsonOrderGoods = new JsonOrderGoods(gitem); newOrderGoodsList.add(jsonOrderGoods); } return newOrderGoodsList; } else { List<Cart> cartList = cartRepository.findByUserAndCheckedAndIsFastAndIsDelete(userId, 1, true, false); return cartList.stream().map(c -> new JsonCart(c)).collect(Collectors.toList()); } } private List<Integer> getOrderStatus(int showType) { return Order.getOrderStatus(showType); } private String getOrderStatusText(Order order) { return Order.getOrderStatusText(order); } private HandleOption getOrderHandleOption(Order orderInfo) { HandleOption handleOption = new HandleOption(); // 订单流程:下单成功-》支付订单-》发货-》收货-》评论 // 订单相关状态字段设计,采用单个字段表示全部的订单状态 // 1xx表示订单取消和删除等状态: 101订单创建成功等待付款、102订单已取消、103订单已取消(自动) // 2xx表示订单支付状态: 201订单已付款,等待发货、202订单取消,退款中、203已退款 // 3xx表示订单物流相关状态: 301订单已发货,302用户确认收货、303系统自动收货 // 4xx表示订单完成的状态: 401已收货已评价 // 5xx表示订单退换货相关的状态: 501已收货,退款退货 TODO // 如果订单已经取消或是已完成,则可删除和再次购买 // if (status == 101) "未付款"; // if (status == 102) "已取消"; // if (status == 103) "已取消(系统)"; // if (status == 201) "已付款"; // if (status == 301) "已发货"; // if (status == 302) "已收货"; // if (status == 303) "已收货(系统)"; // TODO 设置一个定时器,自动将有些订单设为完成 // 订单刚创建,可以取消订单,可以继续支付 if(orderInfo.getOrderStatus() == 101 || orderInfo.getOrderStatus() == 801) { handleOption.cancel = true; handleOption.pay = true; } // 如果订单被取消 if(orderInfo.getOrderStatus() == 102 || orderInfo.getOrderStatus() == 103) { handleOption.delete = true; } // 如果订单已付款,没有发货,则可退款操作 if(orderInfo.getOrderStatus() == 201) { } // handleOption.return = true; // 如果订单申请退款中,没有相关操作 if(orderInfo.getOrderStatus() == 202) { handleOption.cancel_refund = true; } if(orderInfo.getOrderStatus() == 300) {} // 如果订单已经退款,则可删除 if(orderInfo.getOrderStatus() == 203) { handleOption.delete = true; } // 如果订单已经发货,没有收货,则可收货操作, // 此时不能取消订单 if(orderInfo.getOrderStatus() == 301) { handleOption.confirm = true; } if(orderInfo.getOrderStatus() == 401) { handleOption.delete = true; } return handleOption; } private TextCode getOrderTextCode(Order orderInfo) { TextCode textCode = new TextCode(); if(orderInfo.getOrderStatus() == 101) { textCode.pay = true; textCode.countdown = true; } if(orderInfo.getOrderStatus() == 102 || orderInfo.getOrderStatus() == 103) { textCode.close = true; } if(orderInfo.getOrderStatus() == 201 || orderInfo.getOrderStatus() == 300) { textCode.delivery = true; } if(orderInfo.getOrderStatus() == 301) { textCode.receive = true; } if(orderInfo.getOrderStatus() == 401) { textCode.success = true; } return textCode; } // OrderSubmit: ApiRootUrl + 'order/submit', // 提交订单 // OrderList: ApiRootUrl + 'order/list', //订单列表 // OrderDetail: ApiRootUrl + 'order/detail', //订单详情 // OrderDelete: ApiRootUrl + 'order/delete', //订单删除 // OrderCancel: ApiRootUrl + 'order/cancel', //取消订单 // OrderConfirm: ApiRootUrl + 'order/confirm', //物流详情 // OrderCount: ApiRootUrl + 'order/count', // 获取订单数 // OrderCountInfo: ApiRootUrl + 'order/orderCount', // 我的页面获取订单数状态 // OrderExpressInfo: ApiRootUrl + 'order/express', //物流信息 // OrderGoods: ApiRootUrl + 'order/orderGoods', // 获取checkout页面的商品列表 } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/api/FootprintController.java<|end_filename|> package org.needle.bookingdiscount.server.api; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import javax.servlet.http.HttpServletRequest; import org.needle.bookingdiscount.domain.member.Footprint.JsonFootprint; import org.needle.bookingdiscount.domain.member.MemberUser; import org.needle.bookingdiscount.server.api.handler.ResponseHandler; import org.needle.bookingdiscount.server.data.DataPage; import org.needle.bookingdiscount.server.security.SecurityContext; import org.needle.bookingdiscount.server.service.FootprintService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/footprint") public class FootprintController { @Autowired private FootprintService footprintService; @Autowired private SecurityContext securityContext; //足迹列表 @RequestMapping("/list") @ResponseBody public Object list(@RequestHeader(name="X-Nideshop-Token") String token, @RequestParam(defaultValue="1") int page, @RequestParam(defaultValue="20") int size, HttpServletRequest request) { return ResponseHandler.doResponse(() -> { int pageIndex = page > 0 ? page - 1 : page; Optional<MemberUser> userOpt = securityContext.getUserByToken(token); List<JsonFootprint> dataList = userOpt.isPresent() ? footprintService.list(userOpt.get().getId(), pageIndex, size) : new ArrayList<JsonFootprint>(); return new DataPage(page, dataList); }); } //删除足迹 @RequestMapping("/delete") @ResponseBody public Object delete(@RequestHeader(name="X-Nideshop-Token") String token, @RequestBody Map<String,Object> data, HttpServletRequest request) { Long footprintId = Long.valueOf(data.get("footprintId").toString()); return ResponseHandler.doResponse(() -> { Optional<MemberUser> userOpt = securityContext.getUserByToken(token); return userOpt.isPresent() ? footprintService.delete(userOpt.get().getId(), footprintId) : "未登录"; }); } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/repository/freight/FreightTemplateGroupRepository.java<|end_filename|> package org.needle.bookingdiscount.server.repository.freight; import java.util.List; import org.needle.bookingdiscount.domain.freight.FreightTemplateGroup; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; public interface FreightTemplateGroupRepository extends PagingAndSortingRepository<FreightTemplateGroup, Long> { @Query("from FreightTemplateGroup t where t.template.id=?1 and t.area=?2 ") public List<FreightTemplateGroup> findByTemplateAndArea(Long templateId, String area); } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/api/SettingsController.java<|end_filename|> package org.needle.bookingdiscount.server.api; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.needle.bookingdiscount.domain.member.MemberUser; import org.needle.bookingdiscount.server.api.handler.ResponseHandler; import org.needle.bookingdiscount.server.exception.ServiceException; import org.needle.bookingdiscount.server.security.SecurityContext; import org.needle.bookingdiscount.server.service.SettingsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/settings") public class SettingsController { @Autowired private SettingsService settingsService; @Autowired private SecurityContext securityContext; @RequestMapping("/showSettings") @ResponseBody public Object showSettings() { return ResponseHandler.doResponse(() -> { return settingsService.showSettings(); }); } @RequestMapping("/save") @ResponseBody public Object save(@RequestHeader(name="X-Nideshop-Token") String token, @RequestBody Map<String,Object> data, HttpServletRequest request) { String name = (String) data.get("name"); String mobile = (String) data.get("mobile"); return ResponseHandler.doResponse(() -> { MemberUser user = securityContext.getUserByToken(token) .orElseThrow(() -> new ServiceException(401, "未登录")); return settingsService.save(user.getId(), name, mobile); }); } @RequestMapping("/userDetail") @ResponseBody public Object userDetail(@RequestHeader(name="X-Nideshop-Token") String token, HttpServletRequest request) { return ResponseHandler.doResponse(() -> { MemberUser user = securityContext.getUserByToken(token) .orElseThrow(() -> new ServiceException(401, "未登录")); return settingsService.userDetail(user.getId()); }); } } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/support/ExceptArea.java<|end_filename|> package org.needle.bookingdiscount.domain.support; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import org.needle.bookingdiscount.domain.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper=true) @Entity @Table(name="needle_except_area") public class ExceptArea extends BaseEntity { @Column(name="content", length=255) private String content; @Column(name="area", length=3000) private String area; @Column(name="is_delete", columnDefinition="tinyint(1) default 0") private Boolean isDelete; } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/product/Goods.java<|end_filename|> package org.needle.bookingdiscount.domain.product; import java.math.BigDecimal; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.needle.bookingdiscount.domain.BaseEntity; import org.needle.bookingdiscount.domain.freight.FreightTemplate; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; @Data @EqualsAndHashCode(callSuper=true) @Entity @Table(name="needle_goods") public class Goods extends BaseEntity { // 分类 @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="category_id") private Category category; @Column(name="https_pic_url", length=200) private String httpsPicUrl; @Column(name="list_pic_url", length=200) private String listPicUrl; @Column(name="name", length=120) private String name; @Column(name="goods_brief", length=200) private String goodsBrief; @Column(name="keywords", length=200) private String keywords; @Column(name="goods_number") private Integer goodsNumber; @Column(name="goods_unit", length=45) private String goodsUnit; @Column(name="sell_volume") private Integer sellVolume; @Column(name="is_index", columnDefinition="tinyint default 0") private Boolean isIndex; @Column(name="is_new", columnDefinition="tinyint default 0") private Boolean isNew; @Column(name="retail_price", length=100) private String retailPrice; @Column(name="min_retail_price", columnDefinition="decimal(10,2)") private BigDecimal minRetailPrice; @Column(name="cost_price", length=100) private String costPrice; @Column(name="min_cost_price") private BigDecimal minCostPrice; @Column(name="freight_template_id") private Long freightTemplateId; @Column(name="freight_type", columnDefinition="tinyint default 0") private Boolean freightType; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="freight_template") private FreightTemplate freightTemplate; @Column(name="sort_order") private Integer sortOrder; @Column(name="is_on_sale", columnDefinition="tinyint default 1") private Boolean isOnSale; @Column(name="is_delete", columnDefinition="tinyint default 0") private Boolean isDelete; @Column(name="goods_desc", columnDefinition="text") private String goodsDesc; // 型号和价格 @Column(name="specification_id1") private Long specificationId1; public Long getFreightTemplateId() { if(this.freightTemplateId != null) { return this.freightTemplateId; } return this.freightTemplate == null ? null : this.freightTemplate.getId(); } @Getter @Setter public static class JsonGoods { private Long id; private Long category_id; private String https_pic_url; private String list_pic_url; private String name; private String goods_brief; private String keywords; private Integer goods_number; private String goods_unit; private Integer sell_volume; private Boolean is_index; private Boolean is_new; private String retail_price; private BigDecimal min_retail_price; private String cost_price; private BigDecimal min_cost_price; private Long freight_template_id; private Boolean freight_type; private Integer sort_order; private Boolean is_on_sale; private Boolean is_delete; private String goods_desc; public JsonGoods(Goods goods) { this.id = goods.getId(); this.category_id = goods.getCategory() == null ? null : goods.getCategory().getId(); this.https_pic_url = goods.getHttpsPicUrl(); this.list_pic_url = goods.getListPicUrl(); this.name = goods.getName(); this.goods_brief = goods.getGoodsBrief(); this.keywords = goods.getKeywords(); this.goods_number = goods.getGoodsNumber(); this.goods_unit = goods.getGoodsUnit(); this.sell_volume = goods.getSellVolume(); this.is_index = goods.getIsIndex(); this.is_new = goods.getIsNew(); this.retail_price = goods.getRetailPrice(); this.min_retail_price = goods.getMinRetailPrice(); this.cost_price = goods.getCostPrice(); this.min_cost_price = goods.getMinCostPrice(); this.freight_template_id = goods.getFreightTemplateId(); this.freight_type = goods.getFreightType(); this.sort_order = goods.getSortOrder(); this.is_on_sale = goods.getIsOnSale(); this.is_delete = goods.getIsDelete(); this.goods_desc = goods.getGoodsDesc(); } } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/api/QrcodeController.java<|end_filename|> package org.needle.bookingdiscount.server.api; import java.util.Base64; import java.util.Map; import org.needle.bookingdiscount.server.data.ResponseMessage; import org.needle.bookingdiscount.wechat.WxMaConfiguration; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import cn.binarywang.wx.miniapp.api.WxMaService; import cn.binarywang.wx.miniapp.bean.WxMaCodeLineColor; import lombok.extern.slf4j.Slf4j; import me.chanjar.weixin.common.error.WxErrorException; @Slf4j @Controller @RequestMapping("/qrcode") public class QrcodeController { @RequestMapping("/getBase64") @ResponseBody public Object getBase64(@RequestBody Map<String,Object> data) { String appid = (String) data.get("appid"); Long goodsId = Long.valueOf(data.get("goodsId").toString()); final WxMaService wxService = WxMaConfiguration.getMaService(appid); String scene = goodsId.toString(); String page = "pages/goods/goods"; int width = 200; WxMaCodeLineColor lineColor = new WxMaCodeLineColor("0", "0", "0"); byte[] bytes = new byte[0]; try { bytes = wxService.getQrcodeService().createWxaCodeUnlimitBytes(scene, page, width, true, lineColor, true); } catch (WxErrorException e) { log.error("getBase64(..) => createWxaCodeUnlimitBytes失败:{}", e.getMessage()); } String base64 = Base64.getEncoder().encodeToString(bytes); log.debug("base64:{}", base64); return ResponseMessage.success(base64); } } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/product/Product.java<|end_filename|> package org.needle.bookingdiscount.domain.product; import java.math.BigDecimal; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Transient; import org.needle.bookingdiscount.domain.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper=true) @Entity @Table(name="needle_product") public class Product extends BaseEntity { @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="goods_id") private Goods goods; // 型号/规格 @Column(name="goods_specification_ids", length=50) private String goodsSpecificationIds; // 商品SKU @Column(name="goods_sn", length=60) private String goodsSn; // 快递单上的简称 @Column(name="goods_name", length=120) private String goodsName; // 等于GoodsSpecification.value @Column(name="value", length=50) private String value; // 成本 @Column(name="cost", columnDefinition="decimal(10,2)") private BigDecimal cost; // 零售 @Column(name="retail_price", columnDefinition="decimal(10,2) unsigned") private BigDecimal retailPrice; // 重量 @Column(name="goods_weight", columnDefinition="double(6,2)") private Double goodsWeight; // 库存 @Column(name="goods_number") private Integer goodsNumber; @Column(name="has_change", columnDefinition="tinyint default 0") private Boolean hasChange; @Column(name="is_on_sale", columnDefinition="tinyint(1) default 1") private Boolean isOnSale; @Column(name="is_delete", columnDefinition="tinyint(1) default 0") private Boolean isDelete; @Transient private Long goodsId; @Data public static class JsonProduct { private Long id; private Long goods_id; private String goods_specification_ids; private String goods_sn; private String goods_name; private Integer goods_number; private BigDecimal retail_price; private BigDecimal cost; private Double goods_weight; private Boolean has_change; private Boolean is_on_sale; private Boolean is_delete; public JsonProduct(Product p) { this.id = p.getId(); this.goods_id = p.getGoods() == null ? null : p.getGoods().getId(); this.goods_specification_ids = p.getGoodsSpecificationIds(); this.goods_sn = p.getGoodsSn(); this.goods_name = p.getGoodsName(); this.goods_number = p.getGoodsNumber(); this.retail_price = p.getRetailPrice(); this.cost = p.getCost(); this.goods_weight = p.getGoodsWeight(); this.has_change = p.getHasChange(); this.is_on_sale = p.getIsOnSale(); this.is_delete = p.getIsDelete(); } } } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/utils/Base64Utils.java<|end_filename|> package org.needle.bookingdiscount.utils; import java.io.UnsupportedEncodingException; import org.apache.tomcat.util.codec.binary.Base64; import org.springframework.util.StringUtils; public class Base64Utils { public static String encode(String text) { if(!StringUtils.hasText(text)) { return text; } Base64 base64 = new Base64(); try { return base64.encodeToString(text.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } public static String decode(String text) { if(!StringUtils.hasText(text)) { return text; } Base64 base64 = new Base64(); try { return new String(base64.decode(text), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/freight/Settings.java<|end_filename|> package org.needle.bookingdiscount.domain.freight; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.needle.bookingdiscount.domain.BaseEntity; import org.needle.bookingdiscount.domain.product.Goods; import org.needle.bookingdiscount.domain.support.Region; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper=true) @Entity @Table(name="needle_settings") public class Settings extends BaseEntity { @Column(name="autoDelivery", columnDefinition="tinyint(1) NOT NULL DEFAULT '0'") private Integer autoDelivery; @Column(name="name") private String name; @Column(name="tel") private String tel; @Column(name="provinceName") private String provinceName; @Column(name="cityName", length=20) private String cityName; @Column(name="expAreaName", length=20) private String expAreaName; @Column(name="address", length=20) private String address; @Column(name="discovery_img_height") private Integer discoveryImgHeight; @Column(name="discovery_img", length=255) private String discoveryImg; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="goods_id") private Goods goods; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="province_id") private Region province; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="city_id") private Region city; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="district_id") private Region district; @Column(name="countdown", columnDefinition="int(11) default 0") private Integer countdown; @Column(name="reset", columnDefinition="tinyint(1) default 0") private Integer reset; } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/order/OrderGoods.java<|end_filename|> package org.needle.bookingdiscount.domain.order; import java.math.BigDecimal; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.needle.bookingdiscount.domain.BaseEntity; import org.needle.bookingdiscount.domain.member.MemberUser; import org.needle.bookingdiscount.domain.product.Goods; import org.needle.bookingdiscount.domain.product.Product; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper=true) @Entity @Table(name="needle_order_goods") public class OrderGoods extends BaseEntity { @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="order_id") private Order order; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="goods_id") private Goods goods; @Column(name="goods_name", length=120) private String goodsName; @Column(name="goods_aka", length=120) private String goodsAka; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="product_id") private Product product; @Column(name="number", columnDefinition="smallint(5) unsigned") private Integer number; @Column(name="retail_price") private BigDecimal retailPrice; @Column(name="goods_specifition_name_value", columnDefinition="TEXT") private String goodsSpecificationNameValue; @Column(name="goods_specifition_ids", length=255) private String goodsSpecificationIds; @Column(name="list_pic_url", length=255) private String listPicUrl; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="user_id") private MemberUser user; @Column(name="is_delete", columnDefinition="tinyint(1) default 0") private Boolean isDelete; @Data public static class JsonOrderGoods { private Long id; private Long order_id; private Long goods_id; private String goods_name; private String goods_aka; private Long product_id; private Integer number; private BigDecimal retail_price; private String goods_specifition_name_value; private String goods_specifition_ids; private String list_pic_url; private Long user_id; private Boolean is_delete; private String specificationName; public JsonOrderGoods(OrderGoods orderGoods) { this.id = orderGoods.getId(); this.order_id = orderGoods.getOrder().getId(); this.goods_id = orderGoods.getGoods().getId(); this.goods_name = orderGoods.getGoodsName(); this.goods_aka = orderGoods.getGoodsAka(); this.product_id = orderGoods.getProduct().getId(); this.number = orderGoods.getNumber(); this.retail_price = orderGoods.getRetailPrice(); this.goods_specifition_name_value = orderGoods.getGoodsSpecificationNameValue(); this.goods_specifition_ids = orderGoods.getGoodsSpecificationIds(); this.list_pic_url = orderGoods.getListPicUrl(); this.user_id = orderGoods.getUser().getId(); this.is_delete = orderGoods.getIsDelete(); } } } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/freight/FreightTemplateGroup.java<|end_filename|> package org.needle.bookingdiscount.domain.freight; import java.math.BigDecimal; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.needle.bookingdiscount.domain.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper=true) @Entity @Table(name="needle_freight_template_group") public class FreightTemplateGroup extends BaseEntity { @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="template_id") private FreightTemplate template; @Column(name="is_default", columnDefinition="tinyint(1)") private Boolean isDefault; @Column(name="area", length=3000) private String area; @Column(name="start", columnDefinition="int(3)") private Integer start; @Column(name="start_fee", columnDefinition="decimal(10,2)") private BigDecimal startFee; @Column(name="add", columnDefinition="int(3)") private Integer add; @Column(name="add_fee", columnDefinition="decimal(10,2)") private BigDecimal addFee; @Column(name="free_by_number", columnDefinition="int(3)") private Integer freeByNumber; @Column(name="free_by_money", columnDefinition="decimal(10,2)") private BigDecimal freeByMoney; @Column(name="is_delete", columnDefinition="tinyint(1)") private Boolean isDelete; } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/repository/order/OrderRepository.java<|end_filename|> package org.needle.bookingdiscount.server.repository.order; import java.util.List; import org.needle.bookingdiscount.domain.order.Order; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; public interface OrderRepository extends PagingAndSortingRepository<Order, Long> { @Query("from Order t where t.orderSn=?1") public Order getByOrderSn(String orderSn); @Query("from Order t where t.user.id=?1 and t.isDelete=?2 and t.orderType<?3 and t.orderStatus in (?4) order by t.addTime desc") public List<Order> findByUserAndIsDeleteAndOrderTypeLessThanAndOrderStatusIn(Long userId, boolean isDelete, int orderType, List<Integer> orderStatus, Pageable pageable); @Query("select count(t) from Order t where t.user.id=?1 and t.isDelete=?2 and t.orderType<?3 and t.orderStatus in (?4)") public Long countByUserAndIsDeleteAndOrderTypeLessThanAndOrderStatusIn(Long userId, boolean isDelete, int orderType, List<Integer> orderStatus); @Query("select count(t) from Order t where t.user.id=?1 and t.isDelete=?2 and t.orderStatus in (?3)") public Long countByUserAndIsDeleteAndOrderStatus(Long userId, Boolean isDelete, List<Integer> orderStatus); } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/repository/freight/FreightTemplateDetailRepository.java<|end_filename|> package org.needle.bookingdiscount.server.repository.freight; import java.util.List; import org.needle.bookingdiscount.domain.freight.FreightTemplateDetail; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; public interface FreightTemplateDetailRepository extends PagingAndSortingRepository<FreightTemplateDetail, Long> { @Query("from FreightTemplateDetail t where t.template.id=?1 and t.area=?2 and t.isDelete=false") public List<FreightTemplateDetail> findByTemplateAndArea(Long freightTemplateId, Integer area); } <|start_filename|>booking-admin/src/main/java/org/needle/bookingdiscount/admin/web/OrderController.java<|end_filename|> package org.needle.bookingdiscount.admin.web; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.needle.bookingdiscount.admin.service.MemberUserService; import org.needle.bookingdiscount.admin.service.OrderService; import org.needle.bookingdiscount.admin.service.RegionService; import org.needle.bookingdiscount.domain.member.MemberUser; import org.needle.bookingdiscount.domain.order.Order; import org.needle.bookingdiscount.domain.order.OrderGoods.JsonOrderGoods; import org.needle.bookingdiscount.domain.product.GoodsSpecification; import org.needle.bookingdiscount.domain.product.Specification; import org.needle.bookingdiscount.domain.support.Region; import org.needle.bookingdiscount.utils.Base64Utils; import org.needleframe.core.model.Module; import org.needleframe.core.web.AbstractDataController; import org.needleframe.core.web.response.ResponseMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/data") public class OrderController extends AbstractDataController { @Autowired private OrderService orderService; @Autowired private MemberUserService memberUserService; @Autowired private RegionService regionService; @Override protected Module getModule(String moduleName) { return appContextService.getModuleContext().getModule(Order.class); } @RequestMapping("/order/get") @ResponseBody public ResponseMessage getData(String id, HttpServletRequest request, HttpServletResponse response) { return super.getData("order", id, request, response); } @SuppressWarnings("unchecked") @RequestMapping("/order/list") @ResponseBody public ResponseMessage findList(String[] _vp, String _vf, String _sf, int _page, int _size, String _sort, String _direction, HttpServletRequest request, HttpServletResponse response) { ResponseMessage responseMessage = super.findList("order", _vp, _vf, _sf, _page, _size, _sort, _direction, request, response); if(responseMessage.isSuccess()) { Page<Map<String,Object>> dataPage = (Page<Map<String,Object>>) responseMessage.getData(); dataPage.getContent().forEach(data -> { Long id = Long.valueOf(data.get("id").toString()); List<JsonOrderGoods> orderGoods = orderService.findGoodsByOrder(id); data.put("orderGoods", orderGoods); orderGoods.forEach(og -> { String sid = og.getGoods_specifition_ids(); GoodsSpecification gs = orderService.getGoodsSpecificationById(Long.valueOf(sid)); if(gs != null) { Specification s = gs.getSpecification(); og.setSpecificationName(s.getName()); } }); Region province = regionService.findById(Long.valueOf(data.get("province").toString())); Region city = regionService.findById(Long.valueOf(data.get("city").toString())); Region district = regionService.findById(Long.valueOf(data.get("district").toString())); data.put("full_region", String.join("", province.getName(), city.getName(), district.getName())); Object userIdObject = data.get("user"); if(userIdObject != null) { Long userId = Long.valueOf(userIdObject.toString()); MemberUser user = memberUserService.getById(userId); data.put("userNickname", Base64Utils.decode(user.getNickname())); data.put("username", user.getName()); data.put("userAvatar", user.getAvatar()); data.put("userMobile", user.getMobile()); } }); } return responseMessage; } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/repository/member/FootprintRepository.java<|end_filename|> package org.needle.bookingdiscount.server.repository.member; import java.util.List; import org.needle.bookingdiscount.domain.member.Footprint; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; public interface FootprintRepository extends PagingAndSortingRepository<Footprint, Long> { @Query("select t from Footprint t left join t.goods t1 where t.user.id=?1 order by t.addTime desc") public List<Footprint> findByUser(Long userId, Pageable pageable); } <|start_filename|>booking-admin/src/main/java/org/needle/bookingdiscount/admin/repository/MemberUserRepository.java<|end_filename|> package org.needle.bookingdiscount.admin.repository; import org.needle.bookingdiscount.domain.member.MemberUser; import org.springframework.data.repository.PagingAndSortingRepository; public interface MemberUserRepository extends PagingAndSortingRepository<MemberUser, Long> { } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/product/Category.java<|end_filename|> package org.needle.bookingdiscount.domain.product; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import org.needle.bookingdiscount.domain.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; @Data @EqualsAndHashCode(callSuper=true) @Entity @Table(name="needle_category") public class Category extends BaseEntity { @Column(name="parent_id") private Long parentId; @Column(name="name", length=100) private String name; @Column(name="keywords", length=200) private String keywords; @Column(name="img_url", length=200) private String imgUrl; @Column(name="p_height") private Integer pHeight; @Column(name="icon_url", length=200) private String iconUrl; @Column(name="sort_order") private Integer sortOrder; @Column(name="show_index", columnDefinition="tinyint default 0") private Boolean showIndex; @Column(name="is_show", columnDefinition="tinyint default 1") private Boolean isShow; @Column(name="is_category", columnDefinition="tinyint default 0") private Boolean isCategory; @Column(name="is_channel", columnDefinition="tinyint default 0") private Boolean isChannel; @Column(name="level", length=200) private String level; @Column(name="front_name", length=200) private String frontName; @Column(name="front_desc", length=200) private String frontDesc; @Getter @Setter public static class JsonCategory { private Long id; private Long parent_id; private String name; private String keywords; private String img_url; private Integer p_height; private String icon_url; private Integer sort_order; private Boolean show_index; private Boolean is_show; private Boolean is_category; private Boolean is_channel; private String level; private String front_name; private String front_desc; public JsonCategory(Category category) { this.id = category.getId(); this.parent_id = category.getParentId(); this.name = category.getName(); this.keywords = category.getKeywords(); this.img_url = category.getImgUrl(); this.p_height = category.getPHeight(); this.icon_url = category.getIconUrl(); this.sort_order = category.getSortOrder(); this.show_index = category.getShowIndex(); this.is_category = category.getIsCategory(); this.is_channel = category.getIsChannel(); this.level = category.getLevel(); this.front_name = category.getFrontName(); this.front_desc = category.getFrontDesc(); } } } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/member/MemberUser.java<|end_filename|> package org.needle.bookingdiscount.domain.member; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import org.needle.bookingdiscount.domain.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper=true) @Entity @Table(name="needle_user") public class MemberUser extends BaseEntity { @Column(name="avatar", length=255) private String avatar; @Column(name="nickname", length=120) private String nickname; @Column(name="name", length=60) private String name; @Column(name="username", length=60) private String username; @Column(name="password", length=32) private String password; @Column(name="gender", columnDefinition="int default 0") private int gender; @Column(name="birthday") private Integer birthday; @Column(name="mobile", length=20) private String mobile; @Column(name="register_time") private Integer registerTime; @Column(name="register_ip", length=45) private String registerIp; @Column(name="last_login_ip", length=15) private String lastLoginIp; @Column(name="last_login_time") private Integer lastLoginTime; @Column(name="weixin_openid", length=50) private String weixinOpenid; @Column(name="name_mobile", columnDefinition="tinyint default 0") private Integer nameMobile; @Column(name="country", length=255) private String country; @Column(name="province", length=100) private String province; @Column(name="city", length=100) private String city; @Column(name="token", length=120) private String token; public MemberUser() {} public MemberUser(Long id) { this.id = id; } @Data public static class JsonMemberUser { private Long id; private String avatar; private String nickname; private String name; private String username; private String password; private int gender; private Integer birthday; private String mobile; private Integer register_time; private String register_ip; private String last_login_ip; private Integer last_login_time; private String weixin_openid; private Integer name_mobile; private String country; private String province; private String city; public JsonMemberUser(MemberUser user) { this.id = user.getId(); this.avatar = user.getAvatar(); this.nickname = user.getNickname(); this.name = user.getName(); this.username = user.getUsername(); this.password = <PASSWORD>(); this.gender = user.getGender(); this.birthday = user.getBirthday(); this.mobile = user.getMobile(); this.register_time = user.getRegisterTime(); this.register_ip = user.getRegisterIp(); this.last_login_ip = user.getLastLoginIp(); this.last_login_time = user.getLastLoginTime(); this.weixin_openid = user.getWeixinOpenid(); this.name_mobile = user.getNameMobile(); this.country = user.getCountry(); this.province = user.getProvince(); this.city = user.getCity(); } } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/repository/member/MemberUserRepository.java<|end_filename|> package org.needle.bookingdiscount.server.repository.member; import java.util.List; import org.needle.bookingdiscount.domain.member.MemberUser; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; public interface MemberUserRepository extends PagingAndSortingRepository<MemberUser, Long> { @Query("from MemberUser t where t.weixinOpenid=?1 ") public List<MemberUser> findByWeixinOpenid(String weixinOpenid); @Query("from MemberUser t where t.token=?1") public List<MemberUser> findByToken(String token); } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/service/GoodsService.java<|end_filename|> package org.needle.bookingdiscount.server.service; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.needle.bookingdiscount.domain.member.Footprint; import org.needle.bookingdiscount.domain.member.MemberUser; import org.needle.bookingdiscount.domain.member.SearchHistory; import org.needle.bookingdiscount.domain.product.Goods; import org.needle.bookingdiscount.domain.product.Goods.JsonGoods; import org.needle.bookingdiscount.domain.product.GoodsGallery; import org.needle.bookingdiscount.domain.product.GoodsGallery.JsonGoodsGallery; import org.needle.bookingdiscount.domain.product.GoodsSpecification; import org.needle.bookingdiscount.domain.product.GoodsSpecification.JsonGoodsSpecification; import org.needle.bookingdiscount.domain.product.Product; import org.needle.bookingdiscount.domain.product.Product.JsonProduct; import org.needle.bookingdiscount.domain.product.Specification; import org.needle.bookingdiscount.server.exception.ServiceException; import org.needle.bookingdiscount.server.repository.member.FootprintRepository; import org.needle.bookingdiscount.server.repository.member.SearchHistoryRepository; import org.needle.bookingdiscount.server.repository.product.GoodsGalleryRepository; import org.needle.bookingdiscount.server.repository.product.GoodsRepository; import org.needle.bookingdiscount.server.repository.product.GoodsSpecificationRepository; import org.needle.bookingdiscount.server.repository.product.ProductRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.ModelMap; import org.springframework.util.StringUtils; @Service @Transactional public class GoodsService { @Autowired private GoodsRepository goodsRepository; @Autowired private GoodsGalleryRepository goodsGalleryRepository; @Autowired private FootprintRepository footprintRepository; @Autowired private ProductRepository productRepository; @Autowired private GoodsSpecificationRepository goodsSpecificationRepository; @Autowired private SearchHistoryRepository searchHistoryRepository; //统计商品总数 public ModelMap count() { long count = goodsRepository.countByIsOnSaleAndIsDelete(true, false); return new ModelMap().addAttribute("goodsCount", count); } //获得商品的详情 public ModelMap detail(Long id, Long userId) { Long goodsId = id; Optional<Goods> goodsOpt = goodsRepository.findById(goodsId); if(!goodsOpt.isPresent() || Boolean.TRUE.equals(goodsOpt.get().getIsDelete())) { throw new ServiceException("商品不存在"); } Goods info = goodsOpt.get(); if(Boolean.FALSE.equals(info.getIsOnSale())) { throw new ServiceException("商品已下架"); } List<GoodsGallery> gallery = goodsGalleryRepository.findByGoods(goodsId, PageRequest.of(0, 6)); if(userId != null) { MemberUser user = new MemberUser(userId); Footprint footprint = new Footprint(); footprint.setUser(user); footprint.setGoods(info); footprint.setAddTime((int)(new Date().getTime() / 1000)); footprintRepository.save(footprint); } List<Product> productList = productRepository.findByGoods(goodsId); int goodsNumber = 0; for(Product item : productList) { if(item.getGoodsNumber() > 0) { goodsNumber = goodsNumber + item.getGoodsNumber(); } } info.setGoodsNumber(goodsNumber); ModelMap specificationList = getSpecificationList(goodsId); ModelMap model = new ModelMap(); model.addAttribute("info", new JsonGoods(info)); model.addAttribute("gallery", gallery.stream().map(g -> new JsonGoodsGallery(g)).collect(Collectors.toList())); model.addAttribute("specificationList", specificationList); model.addAttribute("productList", productList.stream().map(p -> new JsonProduct(p)).collect(Collectors.toList())); return model; } //获得商品列表 public List<JsonGoods> list(Long userId, String keyword, String sort, String order, String sales) { boolean isOnSale = true; boolean isDelete = false; List<Goods> goodsData = new ArrayList<Goods>(); Pageable pageable = PageRequest.of(0, 100); if(StringUtils.hasText(keyword)) { if(userId != null) { SearchHistory sh = new SearchHistory(); sh.setUser(new MemberUser(userId)); sh.setFrom(""); sh.setKeyword(keyword); sh.setAddTime((int) (new Date().getTime() / 1000)); searchHistoryRepository.save(sh); } keyword = "%" + keyword + "%"; if("price".equals(sort)) { goodsData = "asc".equals(order.trim().toLowerCase()) ? goodsRepository.findByIsOnSaleAndIsDeleteAndKeywordOrderByPriceAsc(isOnSale, isDelete, keyword, pageable) : goodsRepository.findByIsOnSaleAndIsDeleteAndKeywordOrderByPriceDesc(isOnSale, isDelete, keyword, pageable); } else if("sales".equals(sort)) { goodsData = "asc".equals(sales.trim().toLowerCase()) ? goodsRepository.findByIsOnSaleAndIsDeleteAndKeywordOrderBySaleAsc(isOnSale, isDelete, keyword, pageable) : goodsRepository.findByIsOnSaleAndIsDeleteAndKeywordOrderBySaleDesc(isOnSale, isDelete, keyword, pageable); } else { goodsData = goodsRepository.findByIsOnSaleAndIsDeleteAndKeyword(isOnSale, isDelete, keyword, pageable); } } else { if("price".equals(sort)) { goodsData = "asc".equals(order.trim().toLowerCase()) ? goodsRepository.findByIsOnSaleAndIsDeleteOrderByPriceAsc(isOnSale, isDelete, pageable) : goodsRepository.findByIsOnSaleAndIsDeleteOrderByPriceDesc(isOnSale, isDelete, pageable); } else if("sales".equals(sort)) { goodsData = "asc".equals(sales.trim().toLowerCase()) ? goodsRepository.findByIsOnSaleAndIsDeleteOrderBySaleAsc(isOnSale, isDelete, pageable) : goodsRepository.findByIsOnSaleAndIsDeleteOrderBySaleDesc(isOnSale, isDelete, pageable); } else { goodsData = goodsRepository.findByIsOnSaleAndIsDelete(isOnSale, isDelete, pageable); } } return goodsData.stream().map(g -> new JsonGoods(g)).collect(Collectors.toList()); } public JsonGoods goodsShare(Long id) { Goods info = goodsRepository.findById(id).get(); return new JsonGoods(info); } public void saveUserId() { } private ModelMap getSpecificationList(Long goodsId) { List<GoodsSpecification> gsInfo = goodsSpecificationRepository.findByGoods(goodsId); for(GoodsSpecification item : gsInfo) { List<Product> gsProductList = productRepository.findByGoodsSpecificationIds(item.getId().toString()); if(gsProductList.size() > 0) { Product product = gsProductList.get(0); item.setGoodsNumber(product.getGoodsNumber()); } } ModelMap model = new ModelMap(); Long spec_id = null; String name = ""; for(GoodsSpecification gs : gsInfo) { try { Specification specification = gs.getSpecification(); spec_id = specification.getId(); name = specification.getName(); } catch(Exception e) {} } model.addAttribute("specification_id", spec_id); model.addAttribute("name", name); model.addAttribute("valueList", gsInfo.stream().map(i -> new JsonGoodsSpecification(i)).collect(Collectors.toList())); return model; } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/service/HomeService.java<|end_filename|> package org.needle.bookingdiscount.server.service; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.needle.bookingdiscount.domain.product.Category; import org.needle.bookingdiscount.domain.product.Category.JsonCategory; import org.needle.bookingdiscount.domain.product.Goods; import org.needle.bookingdiscount.domain.product.Goods.JsonGoods; import org.needle.bookingdiscount.domain.support.Ad; import org.needle.bookingdiscount.domain.support.Ad.JsonAd; import org.needle.bookingdiscount.domain.support.Notice; import org.needle.bookingdiscount.domain.support.Notice.JsonNotice; import org.needle.bookingdiscount.server.repository.product.CategoryRepository; import org.needle.bookingdiscount.server.repository.product.GoodsRepository; import org.needle.bookingdiscount.server.repository.support.AdRepository; import org.needle.bookingdiscount.server.repository.support.NoticeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.ModelMap; @Service @Transactional public class HomeService { @Autowired private NoticeRepository noticeRepository; @Autowired private AdRepository adRepository; @Autowired private CategoryRepository categoryRepository; @Autowired private GoodsRepository goodsRepository; public ModelMap getHomeData() { List<Ad> bannerList = adRepository.findByEnabledAndIsDelete(true, false); List<Notice> noticeList = noticeRepository.findByIsDelete(false); List<Category> channelList = categoryRepository.findByIsChannelAndParent(true, 0L); List<Category> categoryList = categoryRepository.findByIsShowAndParent(true, 0L); List<Map<String,Object>> newCategoryList = new ArrayList<Map<String,Object>>(); categoryList.forEach(category -> { List<Goods> categoryGoods = goodsRepository.findGoods(category.getId(), 0, true, true, false); Map<String,Object> dataMap = new LinkedHashMap<String,Object>(); dataMap.put("id", category.getId()); dataMap.put("name", category.getName()); dataMap.put("goodsList", categoryGoods.stream().map(goods -> new JsonGoods(goods)).collect(Collectors.toList())); dataMap.put("banner", category.getImgUrl()); dataMap.put("height", category.getPHeight()); newCategoryList.add(dataMap); }); ModelMap model = new ModelMap(); model.addAttribute("channel", channelList.stream().map(c -> new JsonCategory(c)).collect(Collectors.toList())); model.addAttribute("banner", bannerList.stream().map(ad -> new JsonAd(ad)).collect(Collectors.toList())); model.addAttribute("notice", noticeList.stream().map(n -> new JsonNotice(n)).collect(Collectors.toList())); model.addAttribute("categoryList", newCategoryList); return model; } } <|start_filename|>booking-admin/src/main/java/org/needle/bookingdiscount/admin/service/OrderService.java<|end_filename|> package org.needle.bookingdiscount.admin.service; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.needle.bookingdiscount.admin.repository.GoodsSpecificationRepository; import org.needle.bookingdiscount.admin.repository.OrderGoodsRepository; import org.needle.bookingdiscount.admin.repository.OrderRepository; import org.needle.bookingdiscount.domain.order.Order; import org.needle.bookingdiscount.domain.order.OrderGoods; import org.needle.bookingdiscount.domain.order.OrderGoods.JsonOrderGoods; import org.needle.bookingdiscount.domain.product.GoodsSpecification; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class OrderService { @Autowired private OrderRepository orderRepository; @Autowired private OrderGoodsRepository orderGoodsRepository; @Autowired private GoodsSpecificationRepository goodsSpecificationRepository; public Order getById(Long orderId) { return orderRepository.findById(orderId).get(); } public GoodsSpecification getGoodsSpecificationById(Long goodsSpecificationId) { Optional<GoodsSpecification> gsOpt = goodsSpecificationRepository.findById(goodsSpecificationId); return gsOpt.isPresent() ? gsOpt.get() : null; } public List<JsonOrderGoods> findGoodsByOrder(Long orderId) { List<OrderGoods> orderGoods = orderGoodsRepository.findByOrder(orderId); return orderGoods.stream().map(og -> new JsonOrderGoods(og)).collect(Collectors.toList()); } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/data/ResponseMessage.java<|end_filename|> package org.needle.bookingdiscount.server.data; import java.io.Serializable; import lombok.Data; @Data public class ResponseMessage implements Serializable { private static final long serialVersionUID = -8335867611256170670L; private int errno; private String errmsg; private Object data; public static ResponseMessage success(Object data) { return success(0, "", data); } public static ResponseMessage success(int errno, String errmsg, Object data) { ResponseMessage rm = new ResponseMessage(); rm.setErrmsg(errmsg); rm.setErrno(errno); rm.setData(data); return rm; } public static ResponseMessage failed(int errno, String errmsg) { ResponseMessage rm = new ResponseMessage(); rm.setErrmsg(errmsg); rm.setErrno(errno); return rm; } public static ResponseMessage failed(String errmsg) { ResponseMessage rm = new ResponseMessage(); rm.setErrmsg(errmsg); rm.setErrno(1); return rm; } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/repository/support/KeywordsRepository.java<|end_filename|> package org.needle.bookingdiscount.server.repository.support; import java.util.List; import org.needle.bookingdiscount.domain.support.Keywords; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; public interface KeywordsRepository extends PagingAndSortingRepository<Keywords, Long> { @Query("from Keywords t where t.isDefault=?1 ") public List<Keywords> findByIsDefault(Boolean isDefault, Pageable pageable); @Query("select distinct t.keyword, t.isHot from Keywords t ") public List<Object[]> distinctKeywordAndIsHot(Pageable pageable); @Query("select distinct t.keyword from Keywords t where t.keyword like ?1") public List<String> distinctKeywordByKeyword(String keyword, Pageable pageable); } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/repository/member/SearchHistoryRepository.java<|end_filename|> package org.needle.bookingdiscount.server.repository.member; import java.util.List; import org.needle.bookingdiscount.domain.member.SearchHistory; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; public interface SearchHistoryRepository extends PagingAndSortingRepository<SearchHistory, Long> { @Query("select distinct keyword from SearchHistory t where t.user.id=?1") public List<String> distinctKeywordByUser(Long userId, Pageable pageable); @Query("from SearchHistory t where t.user.id=?1") public List<SearchHistory> findByUser(Long userId); } <|start_filename|>booking-admin/src/test/java/org/needle/bookingdiscount/BoolTest.java<|end_filename|> package org.needle.bookingdiscount; public class BoolTest { public static void main(String[] args) { } } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/freight/Shipper.java<|end_filename|> package org.needle.bookingdiscount.domain.freight; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import org.needle.bookingdiscount.domain.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper=true) @Entity @Table(name="needle_shipper") public class Shipper extends BaseEntity { @Column(name="name", length=20) private String name; @Column(name="code", length=10) private String code; @Column(name="sort_order") private Integer sortOrder; @Column(name="monthCode") private String monthCode; @Column(name="customerName", length=100) private String customerName; @Column(name="enabled", columnDefinition="tinyint(1) default 0") private Boolean enabled; } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/utils/JsonUtils.java<|end_filename|> package org.needle.bookingdiscount.utils; import java.io.IOException; import org.hibernate.service.spi.ServiceException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; public class JsonUtils { private static Logger logger = LoggerFactory.getLogger(JsonUtils.class); private static ObjectMapper om = new ObjectMapper(); public static <T> String toJSON(T obj) { return toJSON(obj, om); } public static <T> String toJSON(T obj, ObjectMapper om) { try { return om.writeValueAsString(obj); } catch (JsonProcessingException e) { logger.error("toJSON(..) => {}的实例转换为JSON格式失败:{}。obj={}", obj.getClass().getSimpleName(), e.getMessage(), obj); throw new ServiceException(obj.getClass().getSimpleName() + "的实例转换为JSON格式失败:" + e.getMessage()); } } public static <T> T fromJSON(String json, TypeReference<?> ref) { return fromJSON(json, ref, om); } @SuppressWarnings("unchecked") public static <T> T fromJSON(String json, TypeReference<?> ref, ObjectMapper om) { try { return (T) om.readValue(json, ref); } catch (IOException e) { e.printStackTrace(); logger.error("解析{}类的JSON数据失败:{},JSON={}", ref.getType().getTypeName(), e.getMessage(), json); throw new ServiceException("解析" + ref.getType().getTypeName() + "类的JSON数据失败:" + e.getMessage()); } } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/repository/product/GoodsRepository.java<|end_filename|> package org.needle.bookingdiscount.server.repository.product; import java.util.List; import org.needle.bookingdiscount.domain.product.Goods; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; public interface GoodsRepository extends PagingAndSortingRepository<Goods, Long> { @Query("from Goods t where t.category.id=?1 and t.goodsNumber>=?2 and t.isOnSale=?3 and t.isIndex=?4 and t.isDelete=?5 order by t.sortOrder") public List<Goods> findGoods(Long categoryId, int goodsNumber, Boolean isOnSale, Boolean isIndex, Boolean isDelete); @Query("from Goods t where t.isOnSale=?1 and t.isDelete=?2 order by t.sortOrder ") public List<Goods> findByIsOnSaleAndIsDelete(Boolean isOnSale, Boolean isDelete, Pageable pageable); @Query("from Goods t where t.isOnSale=?1 and t.isDelete=?2 and t.name like ?3 order by t.sortOrder asc") public List<Goods> findByIsOnSaleAndIsDeleteAndKeyword(Boolean isOnSale, Boolean isDelete, String keyword, Pageable pageable); @Query("from Goods t where t.isOnSale=?1 and t.isDelete=?2 order by t.retailPrice asc") public List<Goods> findByIsOnSaleAndIsDeleteOrderByPriceAsc(Boolean isOnSale, Boolean isDelete, Pageable pageable); @Query("from Goods t where t.isOnSale=?1 and t.isDelete=?2 order by t.retailPrice desc") public List<Goods> findByIsOnSaleAndIsDeleteOrderByPriceDesc(Boolean isOnSale, Boolean isDelete, Pageable pageable); @Query("from Goods t where t.isOnSale=?1 and t.isDelete=?2 and t.name like ?3 order by t.retailPrice asc") public List<Goods> findByIsOnSaleAndIsDeleteAndKeywordOrderByPriceAsc(Boolean isOnSale, Boolean isDelete, String keyword, Pageable pageable); @Query("from Goods t where t.isOnSale=?1 and t.isDelete=?2 and t.name like ?3 order by t.retailPrice desc") public List<Goods> findByIsOnSaleAndIsDeleteAndKeywordOrderByPriceDesc(Boolean isOnSale, Boolean isDelete, String keyword, Pageable pageable); @Query("from Goods t where t.isOnSale=?1 and t.isDelete=?2 order by t.sellVolume asc") public List<Goods> findByIsOnSaleAndIsDeleteOrderBySaleAsc(Boolean isOnSale, Boolean isDelete, Pageable pageable); @Query("from Goods t where t.isOnSale=?1 and t.isDelete=?2 order by t.sellVolume desc") public List<Goods> findByIsOnSaleAndIsDeleteOrderBySaleDesc(Boolean isOnSale, Boolean isDelete, Pageable pageable); @Query("from Goods t where t.isOnSale=?1 and t.isDelete=?2 and t.name like ?3 order by t.sellVolume asc") public List<Goods> findByIsOnSaleAndIsDeleteAndKeywordOrderBySaleAsc(Boolean isOnSale, Boolean isDelete, String keyword, Pageable pageable); @Query("from Goods t where t.isOnSale=?1 and t.isDelete=?2 and t.name like ?3 order by t.sellVolume desc") public List<Goods> findByIsOnSaleAndIsDeleteAndKeywordOrderBySaleDesc(Boolean isOnSale, Boolean isDelete, String keyword, Pageable pageable); @Query("from Goods t where t.category.id=?1 and t.isOnSale=?2 and t.isDelete=?3 order by t.sortOrder ") public List<Goods> findByCategoryAndIsOnSaleAndIsDelete(Long categoryId, Boolean isOnSale, Boolean isDelete, Pageable pageable); @Query("select count(t) from Goods t where t.isOnSale=?1 and t.isDelete=?2") public Long countByIsOnSaleAndIsDelete(boolean isOnSale, boolean isDelete); @Modifying @Query("update Goods t set t.goodsNumber=t.goodsNumber+?1 where id=?2") public void increment(int goodsNumber, Long id); @Modifying @Query("update Goods t set t.goodsNumber=t.goodsNumber-?1 where id=?2") public void decrement(int goodsNumber, Long id); @Modifying @Query("update Goods t set t.sellVolume=t.sellVolume+?1 where id=?2") public void incrementSellVolume(int sellVolume, Long id); } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/security/SecurityContext.java<|end_filename|> package org.needle.bookingdiscount.server.security; import java.util.List; import java.util.Optional; import org.needle.bookingdiscount.domain.member.MemberUser; import org.needle.bookingdiscount.server.exception.ServiceException; import org.needle.bookingdiscount.server.repository.member.MemberUserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; @Component @Transactional public class SecurityContext { @Autowired private MemberUserRepository memberUserRepository; public void setUserToken(Long userId, String token) { Optional<MemberUser> userOpt = memberUserRepository.findById(userId); if(!userOpt.isPresent()) { throw new ServiceException("用户不存在"); } MemberUser user = userOpt.get(); user.setToken(token); memberUserRepository.save(user); } public Optional<MemberUser> getUserByToken(String token) { List<MemberUser> users = memberUserRepository.findByToken(token); return Optional.ofNullable(users.isEmpty() ? null : users.get(0)); } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/repository/product/CategoryRepository.java<|end_filename|> package org.needle.bookingdiscount.server.repository.product; import java.util.List; import org.needle.bookingdiscount.domain.product.Category; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; public interface CategoryRepository extends PagingAndSortingRepository<Category, Long> { @Query("from Category t where t.isChannel=?1 and t.parentId=?2 order by t.sortOrder") public List<Category> findByIsChannelAndParent(Boolean isChannel, Long parentId); @Query("from Category t where t.isShow=?1 and t.parentId=?2 order by t.sortOrder") public List<Category> findByIsShowAndParent(Boolean isShow, Long parentId); @Query("from Category t where t.isCategory=?1 and t.parentId=?2 order by t.sortOrder") public List<Category> findByIsCategoryAndParentId(Boolean isCategory, Long parentId, Pageable pageable); } <|start_filename|>booking-admin/src/main/java/org/needle/bookingdiscount/admin/repository/GoodsSpecificationRepository.java<|end_filename|> package org.needle.bookingdiscount.admin.repository; import java.util.List; import org.needle.bookingdiscount.domain.product.GoodsSpecification; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; public interface GoodsSpecificationRepository extends PagingAndSortingRepository<GoodsSpecification, Long> { @Query("from GoodsSpecification t where t.goods.id=?1") public List<GoodsSpecification> findByGoods(Long goodsId); @Query("from GoodsSpecification t where t.specification.id=?1") public List<GoodsSpecification> findBySpecification(Long specificationId); } <|start_filename|>booking-admin/src/test/java/org/needle/bookingdiscount/DateTest.java<|end_filename|> package org.needle.bookingdiscount; import java.util.Date; public class DateTest { public static void main(String[] args) { System.out.println(new Date(1583338927000L)); } } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/support/ShowSettings.java<|end_filename|> package org.needle.bookingdiscount.domain.support; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import org.needle.bookingdiscount.domain.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper=true) @Entity @Table(name="needle_show_settings") public class ShowSettings extends BaseEntity { @Column(name="banner", columnDefinition="tinyint(1) unsigned default 0") private Integer banner = 0; @Column(name="channel", columnDefinition="tinyint(1) default 0") private Integer channel = 0; @Column(name="index_banner_img", columnDefinition="tinyint(1) default 0") private Integer indexBannerImg = 0; @Column(name="notice", columnDefinition="tinyint(1)") private Integer notice = 0; @Data public static class JsonShowSettings { private Long id; private Integer banner; private Integer channel; private Integer index_banner_img; private Integer notice; public JsonShowSettings(ShowSettings showSettings) { this.id = showSettings.getId(); this.banner = showSettings.getBanner(); this.channel = showSettings.getBanner(); this.index_banner_img = showSettings.getIndexBannerImg(); this.notice = showSettings.getNotice(); } } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/api/CatalogController.java<|end_filename|> package org.needle.bookingdiscount.server.api; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.needle.bookingdiscount.domain.product.Goods.JsonGoods; import org.needle.bookingdiscount.server.api.handler.ResponseHandler; import org.needle.bookingdiscount.server.data.DataPage; import org.needle.bookingdiscount.server.data.ResponseMessage; import org.needle.bookingdiscount.server.service.CatalogService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/catalog") public class CatalogController { @Autowired private CatalogService catalogService; // http://localhost:8080/catalog/index @RequestMapping("/index") @ResponseBody public Object index(Long id) { return ResponseHandler.doResponse(() -> { return catalogService.getIndexData(id); }); } // http://localhost:8080/catalog/current @RequestMapping("/current") @ResponseBody public Object current(Long id) { return ResponseHandler.doResponse(() -> { return catalogService.getCurrentData(id); }); } // http://localhost:8080/catalog/currentlist?page=0&size=10 @RequestMapping("/currentlist") @ResponseBody public Object currentlist(@RequestBody Map<String,Object> data, HttpServletRequest request, HttpServletResponse response) { int page = data.get("page") == null ? 1 : (int) data.get("page"); int size = data.get("size") == null ? 20 : (int) data.get("size"); Long id = Long.valueOf(data.get("id").toString()); return ResponseHandler.doResponse(() -> { int pageIndex = page > 0 ? page - 1 : page; List<JsonGoods> list = catalogService.getCurrentListData(pageIndex, size, id); return ResponseMessage.success(new DataPage(page, list)); }); } } <|start_filename|>booking-admin/src/main/java/org/needle/bookingdiscount/admin/repository/OrderGoodsRepository.java<|end_filename|> package org.needle.bookingdiscount.admin.repository; import java.util.List; import org.needle.bookingdiscount.domain.order.OrderGoods; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; public interface OrderGoodsRepository extends PagingAndSortingRepository<OrderGoods, Long> { @Query("from OrderGoods t where t.order.id=?1 ") public List<OrderGoods> findByOrder(Long orderId); } <|start_filename|>booking-admin/src/test/java/org/needle/bookingdiscount/Base64Test.java<|end_filename|> package org.needle.bookingdiscount; import java.io.UnsupportedEncodingException; import org.apache.tomcat.util.codec.binary.Base64; import org.needleframe.utils.Base64Utils; public class Base64Test { public static void base64Test() { Base64 base64 = new Base64(); String encodedText = "6buE6YeR/5aWz"; try { System.out.println(new String(base64.decode(encodedText), "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } public static void main(String[] args) { System.out.println(Base64Utils.decode("6buE6YeR")); System.out.println(Base64Utils.encode("家有儿女")); } } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/product/GoodsGallery.java<|end_filename|> package org.needle.bookingdiscount.domain.product; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.needle.bookingdiscount.domain.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; @Data @EqualsAndHashCode(callSuper=true) @Entity @Table(name="needle_goods_gallery") public class GoodsGallery extends BaseEntity { @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="goods_id") private Goods goods; @Column(name="img_url", length=200) private String imgUrl; @Column(name="sort_order", columnDefinition="int(11) unsigned default 5") private Integer sortOrder; @Column(name="img_desc", length=200) private String imgDesc; @Column(name="is_delete", columnDefinition="tinyint default 0") private Boolean isDelete; @Getter @Setter public static class JsonGoodsGallery { private Long id; private Long goods_id; private String img_url; private String img_desc; private Integer sort_order; private Boolean is_delete; public JsonGoodsGallery(GoodsGallery goodsGallery) { this.id = goodsGallery.getId(); this.goods_id = goodsGallery.getGoods() == null ? null : goodsGallery.getGoods().getId(); this.img_url = goodsGallery.getImgUrl(); this.img_desc = goodsGallery.getImgDesc(); this.sort_order = goodsGallery.getSortOrder(); this.is_delete = goodsGallery.getIsDelete(); } } } <|start_filename|>booking-admin/src/main/java/org/needle/bookingdiscount/admin/repository/SpecificationRepository.java<|end_filename|> package org.needle.bookingdiscount.admin.repository; import org.needle.bookingdiscount.domain.product.Specification; import org.springframework.data.repository.PagingAndSortingRepository; public interface SpecificationRepository extends PagingAndSortingRepository<Specification, Long> { } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/support/Notice.java<|end_filename|> package org.needle.bookingdiscount.domain.support; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import org.needle.bookingdiscount.domain.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; @Data @EqualsAndHashCode(callSuper=true) @Entity @Table(name="needle_notice") public class Notice extends BaseEntity { @Column(name="content", length=255) private String content; @Column(name="end_time", columnDefinition="int(11)") private Integer endTime; @Column(name="is_delete", columnDefinition="tinyint(1) default 0") private Boolean isDelete; @Getter @Setter public static class JsonNotice { private Long id; private String content; private Integer end_time; private Boolean is_delete; public JsonNotice(Notice notice) { this.id = notice.getId(); this.content = notice.getContent(); this.end_time = notice.getEndTime(); this.is_delete = notice.getIsDelete(); } } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/api/GoodsController.java<|end_filename|> package org.needle.bookingdiscount.server.api; import java.util.Optional; import javax.servlet.http.HttpServletRequest; import org.needle.bookingdiscount.domain.member.MemberUser; import org.needle.bookingdiscount.server.api.handler.ResponseHandler; import org.needle.bookingdiscount.server.security.SecurityContext; import org.needle.bookingdiscount.server.service.GoodsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/goods") public class GoodsController { @Autowired private GoodsService goodsService; @Autowired private SecurityContext securityContext; // // 统计商品总数 @RequestMapping("/count") @ResponseBody public Object count() { return ResponseHandler.doResponse(() -> { return goodsService.count(); }); } // 获得商品的详情 @RequestMapping("/detail") @ResponseBody public Object detail(@RequestHeader(name="X-Nideshop-Token") String token, Long id, HttpServletRequest request) { return ResponseHandler.doResponse(() -> { Optional<MemberUser> user = securityContext.getUserByToken(token); Long userId = user.isPresent() ? user.get().getId() : null; return goodsService.detail(id, userId); }); } // 获得商品列表 @RequestMapping("/list") @ResponseBody public Object list(@RequestHeader(name="X-Nideshop-Token") String token, String keyword, String sort, String order, String sales, HttpServletRequest request) { return ResponseHandler.doResponse(() -> { Optional<MemberUser> user = securityContext.getUserByToken(token); Long userId = user.isPresent() ? user.get().getId() : null; return goodsService.list(userId, keyword, sort, order, sales); }); } // @RequestMapping("/list") // @ResponseBody // public Object list(@RequestHeader(name="X-Nideshop-Token") String token, // @RequestBody Map<String,Object> data, // HttpServletRequest request) { // String keyword = (String) data.get("keyword"); // String sort = (String) data.get("sort"); // String order = (String) data.get("order"); // String sales = (String) data.get("sales"); // return ResponseHandler.doResponse(() -> { // Optional<MemberUser> user = securityContext.getUserByToken(token); // Long userId = user.isPresent() ? user.get().getId() : null; // return goodsService.list(userId, keyword, sort, order, sales); // }); // } // 获得商品的详情 @RequestMapping("/goodsShare") @ResponseBody public Object goodsShare(Long id) { return ResponseHandler.doResponse(() -> { return goodsService.goodsShare(id); }); } // 获得商品的详情 @RequestMapping("/saveUserId") @ResponseBody public Object saveUserId() { return ResponseHandler.doResponse(() -> { goodsService.saveUserId(); return "OK"; }); } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/WebConfig.java<|end_filename|> package org.needle.bookingdiscount.server; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.SerializationFeature; @Configuration @EnableAutoConfiguration @EnableConfigurationProperties public class WebConfig implements WebMvcConfigurer { @Bean public Jackson2ObjectMapperBuilderCustomizer customJackson() { return new Jackson2ObjectMapperBuilderCustomizer() { public void customize(Jackson2ObjectMapperBuilder builder) { builder.serializationInclusion(Include.NON_NULL); // builder.serializationInclusion(Include.NON_EMPTY); builder.featuresToDisable( SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, SerializationFeature.FAIL_ON_EMPTY_BEANS, SerializationFeature.FAIL_ON_SELF_REFERENCES, SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS, SerializationFeature.FLUSH_AFTER_WRITE_VALUE, DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); builder.featuresToEnable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY); } }; } @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowCredentials(true) .allowedMethods("GET", "POST", "DELETE", "PUT", "PATCH") .maxAge(3600); } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/api/PayController.java<|end_filename|> package org.needle.bookingdiscount.server.api; import javax.servlet.http.HttpServletRequest; import org.needle.bookingdiscount.server.api.handler.ResponseHandler; import org.needle.bookingdiscount.server.service.PayService; import org.needle.bookingdiscount.utils.RequestUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import lombok.extern.slf4j.Slf4j; @Slf4j @Controller @RequestMapping("/pay") public class PayController { @Autowired private PayService payService; @RequestMapping("/preWeixinPay") @ResponseBody public Object preWeixinPay(String appid, Long orderId, HttpServletRequest request) { return ResponseHandler.doResponse(() -> { String clientIp = RequestUtils.getClientIp(request); return payService.preWeixinPay(appid, orderId, clientIp); }); } @RequestMapping("/notify") @ResponseBody public Object notify(@RequestBody String xml) { return ResponseHandler.doResponse(() -> { log.info("notify(..) => request={}", xml); String result = payService.notify(xml); log.info("notify(..) => response={}", result); return result; }); } } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/freight/FreightTemplate.java<|end_filename|> package org.needle.bookingdiscount.domain.freight; import java.math.BigDecimal; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import org.needle.bookingdiscount.domain.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper=true) @Entity @Table(name="needle_freight_template") public class FreightTemplate extends BaseEntity { @Column(name="name", length=120) private String name; @Column(name="package_price", columnDefinition="decimal(5,2) unsigned default 0.00") private BigDecimal packagePrice; // 按件0;按重1; @Column(name="freight_type", columnDefinition="tinyint(1)") private Integer freightType; @Column(name="is_delete", columnDefinition="tinyint(1)") private Boolean isDelete; } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/product/Specification.java<|end_filename|> package org.needle.bookingdiscount.domain.product; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import org.needle.bookingdiscount.domain.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper=true) @Entity @Table(name="needle_specification") public class Specification extends BaseEntity { @Column(name="name", length=60) private String name; @Column(name="sort_order", columnDefinition="tinyint(3) unsigned default 0") private Integer sortOrder; @Column(name="memo", length=200) private String memo; public Specification() {} public Specification(Long id) { this.id = id; } } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/member/Footprint.java<|end_filename|> package org.needle.bookingdiscount.domain.member; import java.text.SimpleDateFormat; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.needle.bookingdiscount.domain.BaseEntity; import org.needle.bookingdiscount.domain.product.Goods; import org.needle.bookingdiscount.domain.product.Goods.JsonGoods; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper=true) @Entity @Table(name="needle_footprint") public class Footprint extends BaseEntity { @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="user_id") private MemberUser user; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="goods_id") private Goods goods; @Column(name="add_time", columnDefinition="int(11) default 0") private Integer addTime; @Data public static class JsonFootprint { private Long id; private Long user_id; private Long goods_id; private String add_time; private JsonGoods goods; public JsonFootprint(Footprint footprint) { this.id = footprint.getId(); this.user_id = footprint.getUser().getId(); this.goods_id = footprint.getGoods().getId(); this.add_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(footprint.getAddTime() * 1000)); } } } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/order/Order.java<|end_filename|> package org.needle.bookingdiscount.domain.order; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.needle.bookingdiscount.domain.BaseEntity; import org.needle.bookingdiscount.domain.member.MemberUser; import org.needle.bookingdiscount.domain.order.OrderGoods.JsonOrderGoods; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; @Data @EqualsAndHashCode(callSuper=true) @Entity @Table(name="needle_order") public class Order extends BaseEntity { @Column(name="order_sn" ,length=20) private String orderSn; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="user_id") private MemberUser user; // 300:待发货;301:待收货;401:已收货;102:已关闭;101:待付款; @Column(name="order_status", columnDefinition="smallint(4) unsigned default 0") private Integer orderStatus; @Column(name="offline_pay", columnDefinition="tinyint(1) unsigned") private Integer offlinePay; @Column(name="shipping_status", columnDefinition="tinyint(1) unsigned") private Integer shippingStatus; @Column(name="print_status", columnDefinition="tinyint(1) unsigned") private Integer printStatus; @Column(name="pay_status", columnDefinition="tinyint(1)") private Integer payStatus; // 收货人 @Column(name="consignee", length=60) private String consignee; @Column(name="country", columnDefinition="smallint(5) unsigned") private Long country; @Column(name="province", columnDefinition="smallint(5) unsigned") private Long province; @Column(name="city", columnDefinition="smallint(5) unsigned") private Long city; @Column(name="district", columnDefinition="smallint(5) unsigned") private Long district; @Column(name="address", length=255) private String address; @Column(name="print_info", length=255) private String printInfo; @Column(name="mobile", length=60) private String mobile; // 留言 @Column(name="postscript", length=255) private String postscript; @Column(name="admin_memo", length=255) private String adminMemo; @Column(name="shipping_fee", columnDefinition="decimal(10,2)") private BigDecimal shippingFee; @Column(name="pay_name", length=120) private String payName; @Column(name="pay_id", length=255) private String payId; @Column(name="change_price", columnDefinition="decimal(10,2) unsigned") private BigDecimal changePrice; @Column(name="order_price", columnDefinition="decimal(10,2)") private BigDecimal orderPrice; @Column(name="goods_price", columnDefinition="decimal(10,2)") private BigDecimal goodsPrice; @Column(name="actual_price", columnDefinition="decimal(10,2) unsigned") private BigDecimal actualPrice; @Column(name="add_time", columnDefinition="int(11) unsigned") private Integer addTime; @Column(name="pay_time", columnDefinition="int(11) unsigned") private Integer payTime; @Column(name="shipping_time", columnDefinition="int(11) unsigned") private Integer shippingTime; @Column(name="confirm_time", columnDefinition="int(11) unsigned") private Integer confirmTime; @Column(name="dealdone_time", columnDefinition="int(11) unsigned default 0") private Integer dealdoneTime; @Column(name="freight_price", columnDefinition="int(10) unsigned default 0") private Integer freightPrice; @Column(name="express_value", columnDefinition="decimal(10,2)") private BigDecimal expressValue; @Column(name="remark", length=255) private String remark; @Column(name="order_type", columnDefinition="tinyint(2) unsigned default 0") private Integer orderType; @Column(name="is_delete", columnDefinition="tinyint(1) unsigned default 0") private Boolean isDelete; public static List<Integer> getOrderStatus(int showType) { List<Integer> status = new ArrayList<Integer>(); if (showType == 0) { status = Arrays.asList(101, 102, 103, 201, 202, 203, 300, 301, 302, 303, 401); } else if (showType == 1) { // 待付款订单 status = Arrays.asList(101, 801); } else if (showType == 2) { // 待发货订单 status = Arrays.asList(300); } else if (showType == 3) { // 待收货订单 status = Arrays.asList(301); } else if (showType == 4) { // 待评价订单 status = Arrays.asList(302, 303); } return status; } public static String getOrderStatusText(Order order) { return getOrderStatusText(order.getOrderStatus()); } public static String getOrderStatusText(int orderStatus) { String statusText = "待付款"; switch(orderStatus) { case 101: statusText = "待付款"; break; case 102: statusText = "交易关闭"; break; case 103: statusText = "交易关闭"; //到时间系统自动取消 break; case 201: statusText = "待发货"; break; case 300: statusText = "待发货"; break; case 301: statusText = "已发货"; break; case 401: statusText = "交易成功"; //到时间,未收货的系统自动收货、 break; } return statusText; } @Getter @Setter public static class JsonOrder { private Long id; private String order_sn; private Long user_id; private Integer order_status; private Integer offline_pay; private Integer shipping_status; private Integer print_status; private Integer pay_status; private String consignee; private Long country; private Long province; private Long city; private Long district; private String address; private String print_info; private String mobile; private String postscript; private String admin_memo; private BigDecimal shipping_fee; private String pay_name; private String pay_id; private BigDecimal change_price; private BigDecimal order_price; private BigDecimal goods_price; private BigDecimal actual_price; private Integer freight_price; private BigDecimal express_value; private String remark; private Integer order_type; private Boolean is_delete; private String add_time; private String pay_time; private String confirm_time; private String shipping_time; private String dealdone_time; private int confirm_remainTime; private int final_pay_time; private int goodsCount = 0; private List<JsonOrderGoods> goodsList = new ArrayList<JsonOrderGoods>(); private String order_status_text; private HandleOption handleOption; private String province_name; private String city_name; private String district_name; private String full_region; private String userNickname; private String username; private String userMobile; private String userAvatar; private List<JsonOrderGoods> orderGoods = new ArrayList<JsonOrderGoods>(); public JsonOrder(Order order) { this.id = order.getId(); this.order_sn = order.getOrderSn(); this.user_id = order.getUser().getId(); this.offline_pay = order.getOfflinePay(); this.shipping_fee = order.getShippingFee(); this.print_status = order.getPrintStatus(); this.pay_status = order.getPayStatus(); this.consignee = order.getConsignee(); this.country = order.getCountry(); this.province = order.getProvince(); this.city = order.getCity(); this.district = order.getDistrict(); this.address = order.getAddress(); this.print_info = order.getPrintInfo(); this.mobile = order.getMobile(); this.postscript = order.getPostscript(); this.admin_memo = order.getAdminMemo(); this.shipping_fee = order.getShippingFee(); this.pay_name = order.getPayName(); this.pay_id = order.getPayId(); this.change_price = order.getChangePrice(); this.order_price = order.getOrderPrice(); this.goods_price = order.getGoodsPrice(); this.actual_price = order.getActualPrice(); this.add_time = order.getAddTime() == null ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(order.getAddTime() * 1000)); this.pay_time = order.getPayTime() == null ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(order.getPayTime() * 1000)); this.shipping_time = order.getShippingTime() == null ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(order.getShippingTime() * 1000)); this.confirm_time = order.getConfirmTime() == null ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(order.getConfirmTime() * 1000)); this.dealdone_time = order.getDealdoneTime() == null ? null : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(order.getDealdoneTime() * 1000)); this.freight_price = order.getFreightPrice(); this.express_value = order.getExpressValue(); this.remark = order.getRemark(); this.order_type = order.getOrderType(); this.is_delete = order.getIsDelete(); this.userNickname = order.getUser().getNickname(); this.username = order.getUser().getUsername(); this.userMobile = order.getUser().getMobile(); this.userAvatar = order.getUser().getAvatar(); } } public static class HandleOption { public boolean cancel = false; // 取消操作 public boolean delete = false; // 删除操作 public boolean pay = false; // 支付操作 public boolean confirm = false; // 确认收货完成订单操作 public boolean cancel_refund = false; } public static class TextCode { public boolean pay = false; public boolean close = false; public boolean delivery = false; public boolean receive = false; public boolean success = false; public boolean countdown = false; } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/service/AuthService.java<|end_filename|> package org.needle.bookingdiscount.server.service; import java.util.Date; import java.util.HashMap; import java.util.List; import org.needle.bookingdiscount.domain.member.MemberUser; import org.needle.bookingdiscount.domain.member.MemberUser.JsonMemberUser; import org.needle.bookingdiscount.server.exception.ServiceException; import org.needle.bookingdiscount.server.repository.member.MemberUserRepository; import org.needle.bookingdiscount.utils.Base64Utils; import org.needle.bookingdiscount.wechat.WxMaConfiguration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.ModelMap; import cn.binarywang.wx.miniapp.api.WxMaService; import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult; import cn.binarywang.wx.miniapp.bean.WxMaUserInfo; import lombok.Data; import lombok.extern.slf4j.Slf4j; import me.chanjar.weixin.common.error.WxErrorException; @Slf4j @Service @Transactional public class AuthService { @Autowired private MemberUserRepository userRepository; public ModelMap login(WxUserInfo fullUserInfo, String appid, String code, String clientIp) { int currentTime = (int) (new Date().getTime() / 1000); final WxMaService wxService = WxMaConfiguration.getMaService(appid); WxMaJscode2SessionResult sessionData = null; try { sessionData = wxService.getUserService().getSessionInfo(code); log.info("sessionKey={}, openid={}", sessionData.getSessionKey(), sessionData.getOpenid()); } catch(WxErrorException e) { throw new ServiceException("登录失败"); } String sessionKey = sessionData.getSessionKey(); // String openid = sessionData.getOpenid(); // 用户信息校验 if(!wxService.getUserService().checkUserInfo(sessionKey, fullUserInfo.rawData, fullUserInfo.signature)) { throw new ServiceException("用户身份识别失败"); } WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(sessionKey, fullUserInfo.encryptedData, fullUserInfo.iv); String nickName = Base64Utils.encode(userInfo.getNickName()); // 根据openid查找用户是否已经注册 List<MemberUser> userList = userRepository.findByWeixinOpenid(sessionData.getOpenid()); int is_new = 0; MemberUser user = new MemberUser(); if(userList.isEmpty()) { user.setUsername("微信用户"); user.setPassword(userInfo.getOpenId()); user.setRegisterTime(currentTime); user.setRegisterIp(clientIp); user.setLastLoginTime(currentTime); user.setLastLoginIp(clientIp); user.setMobile(""); user.setWeixinOpenid(userInfo.getOpenId()); user.setAvatar(userInfo.getAvatarUrl()); user.setGender(Integer.valueOf(userInfo.getGender())); // 性别 0:未知、1:男、2:女 user.setNickname(nickName); user.setCountry(userInfo.getCountry()); user.setProvince(userInfo.getProvince()); user.setCity(userInfo.getCity()); user.setBirthday(0); user.setName("微信用户"); user.setNameMobile(0); userRepository.save(user); is_new = 1; } else { user = userList.get(0); user.setLastLoginTime(currentTime); user.setLastLoginIp(clientIp); user.setAvatar(userInfo.getAvatarUrl()); user.setNickname(nickName); user.setCountry(userInfo.getCountry()); user.setProvince(userInfo.getProvince()); user.setCity(userInfo.getCity()); userRepository.save(user); } JsonMemberUser memberUser = new JsonMemberUser(user); memberUser.setNickname(Base64Utils.decode(memberUser.getNickname())); ModelMap model = new ModelMap(); model.addAttribute("token", sessionKey); model.addAttribute("userInfo", memberUser); model.addAttribute("is_new", is_new); return model; } @Data public static class WxUserInfo { String errMsg; HashMap<String,String> clientInfo = new HashMap<String,String>(); HashMap<String,String> userInfo = new HashMap<String,String>(); // {"nickName":"zhao","gender":1,"language":"zh_CN","city":"","province":"Shanghai","country":"China","avatarUrl":"https://thirdwx.qlogo.cn/mmopen/vi_32/FQqRPpJ6x9MT6VnzCOIciaJibjzxL5eQz8tXPPqgct8zOM49icMrxToaN6qUgu6VdgwkUbA0zCv3EntoaKbiacMOHA/132"} String rawData; String signature; String encryptedData; String iv; } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/api/handler/ResponseHandler.java<|end_filename|> package org.needle.bookingdiscount.server.api.handler; import org.needle.bookingdiscount.server.data.ResponseMessage; import org.needle.bookingdiscount.server.exception.ServiceException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonIgnore; public class ResponseHandler { @JsonIgnore private final static Logger logger = LoggerFactory.getLogger(ResponseHandler.class); public static ResponseMessage doResponse(RequestHandler executor) { try { Object data = executor.doRequest(); if(data instanceof ResponseMessage) { return (ResponseMessage) data; } return ResponseMessage.success(data); } catch(ServiceException e) { logger.error("doResponse(..) => 执行页面请求失败:msg={}", e.getMessage(), e); return ResponseMessage.failed(e.getCode(), e.getMessage()); } catch (Exception e) { logger.error("doResponse(..) => 执行页面请求失败:{}", e); return ResponseMessage.failed(e.getMessage()); } } } <|start_filename|>booking-admin/src/main/java/org/needle/bookingdiscount/admin/repository/GoodsRepository.java<|end_filename|> package org.needle.bookingdiscount.admin.repository; import org.needle.bookingdiscount.domain.product.Goods; import org.springframework.data.repository.PagingAndSortingRepository; public interface GoodsRepository extends PagingAndSortingRepository<Goods, Long> { } <|start_filename|>booking-admin/src/main/java/org/needle/bookingdiscount/admin/web/GoodsController.java<|end_filename|> package org.needle.bookingdiscount.admin.web; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.needle.bookingdiscount.admin.service.GoodsService; import org.needle.bookingdiscount.domain.product.Goods; import org.needle.bookingdiscount.domain.product.Goods.JsonGoods; import org.needle.bookingdiscount.domain.product.Product; import org.needle.bookingdiscount.domain.product.Specification; import org.needle.bookingdiscount.utils.JsonUtils; import org.needleframe.core.exception.ServiceException; import org.needleframe.core.model.ActionData; import org.needleframe.core.model.Module; import org.needleframe.core.model.ViewProp; import org.needleframe.core.web.AbstractDataController; import org.needleframe.core.web.handler.DataHandler; import org.needleframe.core.web.handler.ResponseHandler; import org.needleframe.core.web.response.DataModule; import org.needleframe.core.web.response.DataModuleBuilder; import org.needleframe.core.web.response.ResponseMessage; import org.needleframe.core.web.response.ResponseModule; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.ServletRequestUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.fasterxml.jackson.core.type.TypeReference; @Controller @RequestMapping("/data") public class GoodsController extends AbstractDataController { @Autowired private GoodsService goodsService; @Override protected Module getModule(String moduleName) { return appContextService.getModuleContext().getModule(Goods.class); } @RequestMapping("/goods/get") @ResponseBody public ResponseMessage getData(String id, HttpServletRequest request, HttpServletResponse response) { return ResponseHandler.doResponse(() -> { Module module = getModule("goods"); DataHandler dataHandler = new DataHandler(module, om); List<ViewProp> viewProps = dataHandler.getDefaultViewProps(); Map<String,Object> data = dataService.get(module, viewProps, id); DataModule dataModule = new DataModuleBuilder(module).build(viewProps); dataFormatter.format(dataModule, data); return ResponseModule.success(dataModule, data); }); } @RequestMapping("/goods/create") @ResponseBody public ResponseMessage create(String _data, HttpServletRequest request, HttpServletResponse response) { return ResponseHandler.doResponse(() -> { Long specificationId = ServletRequestUtils.getRequiredLongParameter(request, "specificationId1"); String galleryImgs = request.getParameter("galleryImgs"); List<String> gimgs = new ArrayList<String>(); if(StringUtils.hasText(galleryImgs)) { String[] imgs = galleryImgs.split(","); gimgs = Arrays.asList(imgs); } String jsonProductList = request.getParameter("productList"); List<Product> productList = new ArrayList<Product>(); if(StringUtils.hasText(jsonProductList)) { productList = JsonUtils.fromJSON(jsonProductList, new TypeReference<List<Product>>() {}); } Module module = getModule("goods"); DataHandler dataHandler = new DataHandler(module, om); List<ActionData> _dataList = dataHandler.getCreateData(_data, request); if(_dataList.isEmpty() || _dataList.get(0).getData().isEmpty()) { throw new ServiceException("请提交要保存的数据"); } Map<String,Object> data = _dataList.get(0).getData().get(0); Goods goods = module.fromData(data); Specification specification = new Specification(specificationId); JsonGoods jsonGoods = goodsService.save(goods, gimgs, specification, productList); return ResponseModule.success(jsonGoods); }); } // http://localhost:8080/data/goods/update?data=%5B%7B%22saleId%22%3A1%2C%22id%22%3A1%2C%22user%22%3A1%7D%5D @RequestMapping("/goods/update") @ResponseBody public ResponseMessage update(String _data, HttpServletRequest request, HttpServletResponse response) { return ResponseHandler.doResponse(() -> { Long specificationId = ServletRequestUtils.getRequiredLongParameter(request, "specificationId1"); String galleryImgs = request.getParameter("galleryImgs"); List<String> gimgs = new ArrayList<String>(); if(StringUtils.hasText(galleryImgs)) { String[] imgs = galleryImgs.split(","); gimgs = Arrays.asList(imgs); } String jsonProductList = request.getParameter("productList"); List<Product> productList = new ArrayList<Product>(); if(StringUtils.hasText(jsonProductList)) { productList = JsonUtils.fromJSON(jsonProductList, new TypeReference<List<Product>>() {}); } Module module = getModule("goods"); DataHandler dataHandler = new DataHandler(module, om); List<Map<String,Object>> _dataList = dataHandler.getUpdateData(_data, request); if(_dataList.isEmpty()) { throw new ServiceException("请提交要更新的数据"); } Map<String,Object> data = _dataList.get(0); Goods goods = module.fromData(data); Specification specification = new Specification(specificationId); JsonGoods jsonGoods = goodsService.save(goods, gimgs, specification, productList); return ResponseModule.success(jsonGoods); }); } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/repository/member/AddressRepository.java<|end_filename|> package org.needle.bookingdiscount.server.repository.member; import java.util.List; import org.needle.bookingdiscount.domain.member.Address; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; public interface AddressRepository extends PagingAndSortingRepository<Address, Long> { @Query("from Address t where t.user.id=?1 and t.isDefault=?2 and t.isDelete=?3 order by id desc") public List<Address> findByUserAndIsDefaultAndIsDelete(Long userId, boolean isDefault, boolean isDelete); @Query("from Address t where t.user.id=?1 and t.isDelete=?2 order by id desc") public List<Address> findByUserAndIsDelete(Long userId, boolean isDelete); } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/cart/Cart.java<|end_filename|> package org.needle.bookingdiscount.domain.cart; import java.math.BigDecimal; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Transient; import org.needle.bookingdiscount.domain.BaseEntity; import org.needle.bookingdiscount.domain.member.MemberUser; import org.needle.bookingdiscount.domain.product.Goods; import org.needle.bookingdiscount.domain.product.Product; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.Setter; import lombok.Getter; @Data @EqualsAndHashCode(callSuper=true) @Entity @Table(name="needle_cart") public class Cart extends BaseEntity { @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="user_id") private MemberUser user; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="goods_id") private Goods goods; @Column(name="goods_sn", length=60) private String goodsSn; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="product_id") private Product product; @Column(name="goods_name", length=120) private String goodsName; @Column(name="goods_aka", length=120) private String goodsAka; @Column(name="goods_weight") private Double goodsWeight; @Column(name="add_price", columnDefinition="decimal(10,2)") private BigDecimal addPrice; @Column(name="retail_price", columnDefinition="decimal(10,2)") private BigDecimal retailPrice; @Column(name="number", columnDefinition="smallint(5) unsigned default 0") private Integer number; @Column(name="goods_specifition_name_value", columnDefinition="TEXT") private String goodsSpecificationNameValue; @Column(name="goods_specifition_ids", length=60) private String goodsSpecificationIds; @Column(name="checked", columnDefinition="tinyint(1) unsigned") private Integer checked; @Column(name="list_pic_url", length=255) private String listPicUrl; @Column(name="freight_template_id") private Long freightTemplateId; @Column(name="is_on_sale", columnDefinition="tinyint(1) default 1") private Boolean isOnSale = Boolean.TRUE; @Column(name="add_time", columnDefinition="int(11) default 0") private Integer addTime; @Column(name="is_fast", columnDefinition="tinyint(1) default 0") private Boolean isFast = Boolean.FALSE; @Column(name="is_delete", columnDefinition="tinyint(2) unsigned") private Boolean isDelete = Boolean.FALSE; @Transient private Double weightCount; @Transient private int goodsNumber; @Getter @Setter public static class JsonCart { private Long id; private Long user_id; private Long goods_id; private String goods_sn; private Long product_id; private String goods_name; private String goods_aka; private Double goods_weight; private BigDecimal add_price; private BigDecimal retail_price; private Integer number; private String goods_specifition_name_value; private String goods_specifition_ids; private Integer checked; private String list_pic_url; private Long freight_template_id; private Boolean is_on_sale; private Integer add_time; private Boolean is_fast; private Boolean is_delete; private Double weight_count; private int goods_number; public JsonCart(Cart cart) { this.id = cart.getId(); this.user_id = cart.getUser() == null ? null : cart.getUser().getId(); this.goods_id = cart.getGoods() == null ? null :cart.getGoods().getId(); this.goods_sn = cart.getGoodsSn(); this.product_id = cart.getProduct() == null ? null : cart.getProduct().getId(); this.goods_name = cart.getGoodsName(); this.goods_aka = cart.getGoodsAka(); this.goods_weight = cart.getGoodsWeight(); this.add_price = cart.getAddPrice(); this.retail_price = cart.getRetailPrice(); this.number = cart.getNumber(); this.goods_specifition_name_value = cart.getGoodsSpecificationNameValue(); this.goods_specifition_ids = cart.getGoodsSpecificationIds(); this.checked = cart.getChecked(); this.list_pic_url = cart.getListPicUrl(); this.freight_template_id = cart.getFreightTemplateId(); this.is_on_sale = cart.getIsOnSale(); this.add_time = cart.getAddTime(); this.is_fast = cart.getIsFast(); this.is_delete = cart.getIsDelete(); this.weight_count = cart.getWeightCount(); this.goods_number = cart.getGoodsNumber(); } } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/service/RegionService.java<|end_filename|> package org.needle.bookingdiscount.server.service; import java.util.List; import java.util.stream.Collectors; import org.needle.bookingdiscount.domain.support.Region; import org.needle.bookingdiscount.domain.support.Region.JsonRegion; import org.needle.bookingdiscount.server.repository.support.RegionRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; @Service @Transactional public class RegionService { @Autowired private RegionRepository regionRepository; public List<JsonRegion> list(String parentId) { Long pid = 0L; if(StringUtils.hasText(parentId)) { pid = Long.valueOf(parentId); } List<Region> regionList = regionRepository.findByParent(pid); return regionList.stream().map(r -> new JsonRegion(r)).collect(Collectors.toList()); } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/api/CartController.java<|end_filename|> package org.needle.bookingdiscount.server.api; import java.util.HashMap; import java.util.Map; import java.util.Optional; import javax.servlet.http.HttpServletRequest; import org.needle.bookingdiscount.domain.member.MemberUser; import org.needle.bookingdiscount.server.api.handler.ResponseHandler; import org.needle.bookingdiscount.server.exception.ServiceException; import org.needle.bookingdiscount.server.security.SecurityContext; import org.needle.bookingdiscount.server.service.CartService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/cart") public class CartController { // public static Long userId = 1098L; @Autowired private CartService cartService; @Autowired private SecurityContext securityContext; // http://localhost:8080/cart/index //获取购物车的数据 @RequestMapping("/index") @ResponseBody public Object index(@RequestHeader(name="X-Nideshop-Token") String token, HttpServletRequest request) { return ResponseHandler.doResponse(() -> { Optional<MemberUser> userOpt = securityContext.getUserByToken(token); return userOpt.isPresent() ? cartService.getIndexData(userOpt.get().getId()) : new ModelMap(); }); } // 添加商品到购物车 @RequestMapping("/add") @ResponseBody public Object add(@RequestHeader(name="X-Nideshop-Token") String token, @RequestBody Map<String,Object> data, HttpServletRequest request) { Long goodsId = Long.valueOf(data.get("goodsId").toString()); Long productId = Long.valueOf(data.get("productId").toString()); int number = (int) data.get("number"); // 0:正常加入购物车,1:立即购买,2:再来一单 int addType = (int) data.get("addType"); return ResponseHandler.doResponse(() -> { MemberUser user = securityContext.getUserByToken(token) .orElseThrow(() -> new ServiceException(401, "用户未登录")); return cartService.add(user.getId(), goodsId, productId, number, addType); }); } // 更新购物车的商品 @RequestMapping("/update") @ResponseBody public Object update(@RequestHeader(name="X-Nideshop-Token") String token, @RequestBody Map<String,Object> data, HttpServletRequest request) { Long productId = Long.valueOf(data.get("productId").toString()); Long id = Long.valueOf(data.get("id").toString()); Integer number = (Integer) data.get("number"); return ResponseHandler.doResponse(() -> { MemberUser user = securityContext.getUserByToken(token) .orElseThrow(() -> new ServiceException(401, "用户未登录")); return cartService.update(user.getId(), productId, id, number); }); } // 删除购物车的商品 @RequestMapping("/delete") @ResponseBody public Object delete(@RequestHeader(name="X-Nideshop-Token") String token, @RequestBody Map<String,Object> data, HttpServletRequest request) { Long productIds = Long.valueOf(data.get("productIds").toString()); return ResponseHandler.doResponse(() -> { MemberUser user = securityContext.getUserByToken(token) .orElseThrow(() -> new ServiceException(401, "用户未登录")); return cartService.delete(user.getId(), productIds); }); } // 选择或取消选择商品 @RequestMapping("/checked") @ResponseBody public Object checked(@RequestHeader(name="X-Nideshop-Token") String token, @RequestBody Map<String,Object> data, HttpServletRequest request) { String productIds = data.get("productIds").toString(); int checked = (int) data.get("isChecked"); return ResponseHandler.doResponse(() -> { MemberUser user = securityContext.getUserByToken(token) .orElseThrow(() -> new ServiceException(401, "用户未登录")); return cartService.check(user.getId(), productIds, checked == 1 ? true : false); }); } // 获取购物车商品件数 @RequestMapping("/goodsCount") @ResponseBody public Object goodsCount(@RequestHeader(name="X-Nideshop-Token") String token, HttpServletRequest request) { return ResponseHandler.doResponse(() -> { Optional<MemberUser> userOpt = securityContext.getUserByToken(token); if(userOpt.isPresent()) { return cartService.goodsCount(userOpt.get().getId()); } ModelMap model = new ModelMap(); Map<String,Object> dataMap = new HashMap<String,Object>(); dataMap.put("goodsCount", 0); model.addAttribute("cartTotal", dataMap); return model; }); } // 下单前信息确认 @RequestMapping("/checkout") @ResponseBody public Object checkout(@RequestHeader(name="X-Nideshop-Token") String token, String orderFrom, int type, String addressId, int addType, HttpServletRequest request) { return ResponseHandler.doResponse(() -> { MemberUser user = securityContext.getUserByToken(token) .orElseThrow(() -> new ServiceException(401, "用户未登录")); return cartService.checkout(user.getId(), orderFrom, type, addressId, addType); }); } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/service/SearchService.java<|end_filename|> package org.needle.bookingdiscount.server.service; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.needle.bookingdiscount.domain.support.Keywords; import org.needle.bookingdiscount.domain.support.Keywords.JsonKeywords; import org.needle.bookingdiscount.server.repository.member.SearchHistoryRepository; import org.needle.bookingdiscount.server.repository.support.KeywordsRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.ModelMap; @Service @Transactional public class SearchService { @Autowired private KeywordsRepository keywordsRepository; @Autowired private SearchHistoryRepository searchHistoryRepository; // 搜索页面数据 public ModelMap index(String keywords, Long userId) { Pageable pageable = PageRequest.of(0, 1); // 取出输入框默认的关键词 List<Keywords> defaultKeyword = keywordsRepository.findByIsDefault(true, pageable); // 取出热闹关键词 List<Object[]> hotKeywordList = keywordsRepository.distinctKeywordAndIsHot(PageRequest.of(0, 10)); List<String> historyKeywordList = userId == null ? new ArrayList<String>() : searchHistoryRepository.distinctKeywordByUser(userId, PageRequest.of(0, 10)); ModelMap model = new ModelMap(); model.addAttribute("defaultKeyword", defaultKeyword.stream().map(k -> new JsonKeywords(k)).collect(Collectors.toList())); model.addAttribute("hotKeywordList", hotKeywordList); model.addAttribute("historyKeywordList", historyKeywordList); return model; } //搜索帮助 public List<String> helper(String keyword) { List<String> keywords = keywordsRepository.distinctKeywordByKeyword(keyword + "%", PageRequest.of(0, 10)); return keywords; } public void clearHistory(Long userId) { if(userId != null) { searchHistoryRepository.findByUser(userId).forEach(searchHistory -> { searchHistoryRepository.delete(searchHistory); }); } } } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/member/SearchHistory.java<|end_filename|> package org.needle.bookingdiscount.domain.member; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.needle.bookingdiscount.domain.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper=true) @Entity @Table(name="needle_search_history") public class SearchHistory extends BaseEntity { @Column(name="keyword", columnDefinition="char(50)") private String keyword; @Column(name="`from`", columnDefinition="varchar(45)") private String from; @Column(name="add_time", columnDefinition="int(11)") private Integer addTime; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="user_id") private MemberUser user; } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/api/OrderController.java<|end_filename|> package org.needle.bookingdiscount.server.api; import java.math.BigDecimal; import java.util.List; import java.util.Map; import java.util.Optional; import javax.servlet.http.HttpServletRequest; import org.needle.bookingdiscount.domain.member.MemberUser; import org.needle.bookingdiscount.domain.order.Order.JsonOrder; import org.needle.bookingdiscount.domain.order.OrderExpress.JsonOrderExpress; import org.needle.bookingdiscount.server.api.handler.ResponseHandler; import org.needle.bookingdiscount.server.data.DataPage; import org.needle.bookingdiscount.server.data.ResponseMessage; import org.needle.bookingdiscount.server.exception.ServiceException; import org.needle.bookingdiscount.server.security.SecurityContext; import org.needle.bookingdiscount.server.service.OrderService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import lombok.extern.slf4j.Slf4j; @Slf4j @Controller @RequestMapping("/order") public class OrderController { @Autowired private OrderService orderService; @Autowired private SecurityContext securityContext; // 提交订单 @RequestMapping("/submit") @ResponseBody public Object submit(@RequestHeader(name="X-Nideshop-Token") String token, @RequestBody Map<String,Object> data, HttpServletRequest request) { Long addressId = Long.valueOf(data.get("addressId").toString()); BigDecimal freightPrice = new BigDecimal(data.get("freightPrice").toString()); int offlinePay = (int) data.get("offlinePay"); String postscript = (String) data.get("postscript"); return ResponseHandler.doResponse(() -> { MemberUser user = securityContext.getUserByToken(token) .orElseThrow(() -> new ServiceException(401, "未登录")); return orderService.submit(user.getId(), addressId, freightPrice, offlinePay, postscript); }); } //订单列表 @RequestMapping("/list") @ResponseBody public Object list(@RequestHeader(name="X-Nideshop-Token") String token, int showType, @RequestParam(defaultValue="1") int page, @RequestParam(defaultValue="10") int size, HttpServletRequest request) { return ResponseHandler.doResponse(() -> { int pageIndex = page > 0 ? page - 1 : page; MemberUser user = securityContext.getUserByToken(token) .orElseThrow(() -> new ServiceException(401, "未登录")); List<JsonOrder> dataList = orderService.list(user.getId(), showType, pageIndex, size); return new DataPage(pageIndex, dataList); }); } //订单详情 @RequestMapping("/detail") @ResponseBody public Object detail(@RequestHeader(name="X-Nideshop-Token") String token, Long orderId, HttpServletRequest request) { return ResponseHandler.doResponse(() -> { MemberUser user = securityContext.getUserByToken(token) .orElseThrow(() -> new ServiceException(401, "未登录")); return orderService.detail(orderId, user.getId()); }); } //订单删除 @RequestMapping("/delete") @ResponseBody public Object delete(@RequestHeader(name="X-Nideshop-Token") String token, @RequestBody Map<String,Object> data, HttpServletRequest request) { Long orderId = Long.valueOf(data.get("orderId").toString()); return ResponseHandler.doResponse(() -> { MemberUser user = securityContext.getUserByToken(token) .orElseThrow(() -> new ServiceException(401, "未登录")); return orderService.delete(orderId, user.getId()); }); } //取消订单 @RequestMapping("/cancel") @ResponseBody public Object cancel(@RequestHeader(name="X-Nideshop-Token") String token, @RequestBody Map<String,Object> data, HttpServletRequest request) { Long orderId = Long.valueOf(data.get("orderId").toString()); return ResponseHandler.doResponse(() -> { MemberUser user = securityContext.getUserByToken(token) .orElseThrow(() -> new ServiceException(401, "未登录")); return orderService.cancel(orderId, user.getId()); }); } //物流详情 @RequestMapping("/confirm") @ResponseBody public Object confirm(@RequestHeader(name="X-Nideshop-Token") String token, @RequestBody Map<String,Object> data, HttpServletRequest request) { Long orderId = Long.valueOf(data.get("orderId").toString()); return ResponseHandler.doResponse(() -> { MemberUser user = securityContext.getUserByToken(token) .orElseThrow(() -> new ServiceException(401, "未登录")); return orderService.confirm(orderId, user.getId()); }); } // 获取订单数 @RequestMapping("/count") @ResponseBody public Object count(@RequestHeader(name="X-Nideshop-Token") String token, @RequestBody Map<String,Object> data, HttpServletRequest request) { int showType = (int) data.get("showType"); return ResponseHandler.doResponse(() -> { MemberUser user = securityContext.getUserByToken(token) .orElseThrow(() -> new ServiceException(401, "未登录")); return orderService.count(showType, user.getId()); }); } // 我的页面获取订单数状态 @RequestMapping("/orderCount") @ResponseBody public Object orderCount(@RequestHeader(name="X-Nideshop-Token") String token, HttpServletRequest request) { return ResponseHandler.doResponse(() -> { Optional<MemberUser> userOpt = securityContext.getUserByToken(token); if(userOpt.isPresent()) { return orderService.orderCount(userOpt.get().getId()); } ModelMap model = new ModelMap(); model.addAttribute("toPay", 0); model.addAttribute("toDelivery", 0); model.addAttribute("toReceive", 0); return model; }); } // 物流信息 @RequestMapping("/express") @ResponseBody public Object express(Long orderId) { return ResponseHandler.doResponse(() -> { JsonOrderExpress orderExpress = null; try { orderExpress = orderService.express(orderId); } catch(ServiceException e) { log.error("express(..) => 查询物流信息失败:msg={}", e.getMessage()); return ResponseMessage.failed(e.getCode(), e.getMessage()); } return orderExpress; }); } // 获取checkout页面的商品列表 @RequestMapping("/orderGoods") @ResponseBody public Object orderGoods(@RequestHeader(name="X-Nideshop-Token") String token, Long orderId, HttpServletRequest request) { return ResponseHandler.doResponse(() -> { MemberUser user = securityContext.getUserByToken(token) .orElseThrow(() -> new ServiceException(401, "未登录")); return orderService.orderGoods(orderId, user.getId()); }); } } <|start_filename|>booking-admin/src/main/java/org/needle/bookingdiscount/admin/repository/ProductRepository.java<|end_filename|> package org.needle.bookingdiscount.admin.repository; import java.util.List; import org.needle.bookingdiscount.domain.product.Product; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; public interface ProductRepository extends PagingAndSortingRepository<Product, Long> { @Query("from Product t where t.goods.id=?1 ") public List<Product> findByGoods(Long goodsId); @Query("from Product t where t.goods.id=?1 and t.isOnSale=?2 and t.isDelete=?3") public List<Product> findByGoodsAndIsOnSaleAndIsDelete(Long goodsId, boolean isOnSale, boolean isDelete); @Query("from Product t where t.goodsSn=?1 ") public List<Product> findByGoodsSn(String goodsSn); } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/api/RegionController.java<|end_filename|> package org.needle.bookingdiscount.server.api; import javax.servlet.http.HttpServletRequest; import org.needle.bookingdiscount.server.api.handler.ResponseHandler; import org.needle.bookingdiscount.server.service.RegionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/region") public class RegionController { @Autowired private RegionService regionService; @RequestMapping("/list") @ResponseBody public Object list(String parentId, HttpServletRequest request) { return ResponseHandler.doResponse(() -> { return regionService.list(parentId); }); } } <|start_filename|>booking-admin/src/main/java/org/needle/bookingdiscount/admin/cart/CartRepository.java<|end_filename|> package org.needle.bookingdiscount.admin.cart; import java.math.BigDecimal; import java.util.List; import org.needle.bookingdiscount.domain.cart.Cart; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; public interface CartRepository extends PagingAndSortingRepository<Cart, Long> { @Query("from Cart t where t.goods.id=?1 order by t.addTime") public List<Cart> findByGoodsId(Long goodsId, Pageable pageable); @Query("from Cart t where t.product.id=?1 order by t.addTime") public List<Cart> findByProductId(Long productId, Pageable pageable); @Modifying @Query("update Cart t set t.checked=?1, t.isOnSale=?2, t.listPicUrl=?3, t.freightTemplateId=?4 where t.goods.id=?5") public void updateByGoods(int checked, boolean isOnSale, String listPicUrl, Long freightTemplateId, Long goodsId); @Modifying @Query("update Cart t set t.retailPrice=?1, goodsSpecificationNameValue=?2, goods_sn=?3 where t.product.id=?4") public void updateByProduct(BigDecimal retailPrice, String goodsSpecificationNameValue, String goodsSn, Long productId); } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/support/Ad.java<|end_filename|> package org.needle.bookingdiscount.domain.support; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.needle.bookingdiscount.domain.BaseEntity; import org.needle.bookingdiscount.domain.product.Goods; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; @Data @EqualsAndHashCode(callSuper=true) @Entity @Table(name="needle_ad") public class Ad extends BaseEntity { @Column(name="link_type", columnDefinition="tinyint(1) default 0") private Integer linkType; @Column(name="link", length=255) private String link; @Column(name="image_url", length=500) private String imageUrl; @JsonIgnore @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="goods_id") private Goods goods; @Column(name="end_time") private Integer endTime; @Column(name="sort_order", columnDefinition="tinyint(2) default 0") private Integer sortOrder; @Column(name="enabled", columnDefinition="tinyint(1) unsigned default 0") private Boolean enabled; @Column(name="is_delete", columnDefinition="tinyint(1) default 0") private Boolean isDelete; public Long getGoods_id() { return goods == null ? null : goods.getId(); } @Getter @Setter public static class JsonAd { private Long id; private Integer link_type; private String link; private String image_url; private Long goods_id; private Integer end_time; private Integer sort_order; private Boolean enabled; private Boolean is_delete; public JsonAd(Ad ad) { this.id = ad.getId(); this.link_type = ad.getLinkType(); this.link = ad.getLink(); this.image_url = ad.getImageUrl(); this.goods_id = ad.getGoods_id(); this.end_time = ad.getEndTime(); this.sort_order = ad.getSortOrder(); this.enabled = ad.getEnabled(); this.is_delete = ad.getIsDelete(); } } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/repository/support/RegionRepository.java<|end_filename|> package org.needle.bookingdiscount.server.repository.support; import java.util.List; import org.needle.bookingdiscount.domain.support.Region; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; public interface RegionRepository extends PagingAndSortingRepository<Region, Long> { @Query("from Region t where t.parent.id=?1 and t.isDelete=false") public List<Region> findByParent(Long parentId); } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/api/HomeController.java<|end_filename|> package org.needle.bookingdiscount.server.api; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.needle.bookingdiscount.server.api.handler.ResponseHandler; import org.needle.bookingdiscount.server.data.ResponseMessage; import org.needle.bookingdiscount.server.service.HomeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import lombok.extern.slf4j.Slf4j; @Slf4j @Controller @RequestMapping("/index") public class HomeController { @Autowired private HomeService homeService; // http://localhost:8080/index/appInfo @RequestMapping("/appInfo") @ResponseBody public Object appInfo(HttpServletRequest request, HttpServletResponse response) { log.debug("appInfo(..) => JSESSIONID={}", request.getSession().getId()); return ResponseHandler.doResponse(() -> { ModelMap model = homeService.getHomeData(); return ResponseMessage.success(model); }); } } <|start_filename|>booking-admin/src/main/java/org/needle/bookingdiscount/admin/service/GoodsService.java<|end_filename|> package org.needle.bookingdiscount.admin.service; import java.math.BigDecimal; import java.util.List; import java.util.Map; import java.util.Optional; import org.needle.bookingdiscount.admin.cart.CartRepository; import org.needle.bookingdiscount.admin.repository.GoodsGalleryRepository; import org.needle.bookingdiscount.admin.repository.GoodsRepository; import org.needle.bookingdiscount.admin.repository.GoodsSpecificationRepository; import org.needle.bookingdiscount.admin.repository.ProductRepository; import org.needle.bookingdiscount.domain.product.Goods; import org.needle.bookingdiscount.domain.product.Goods.JsonGoods; import org.needle.bookingdiscount.domain.product.GoodsGallery; import org.needle.bookingdiscount.domain.product.GoodsSpecification; import org.needle.bookingdiscount.domain.product.Product; import org.needle.bookingdiscount.domain.product.Specification; import org.needleframe.core.exception.ServiceException; import org.needleframe.core.model.ActionData; import org.needleframe.core.model.Module; import org.needleframe.core.service.AbstractDataService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; @Service @Transactional public class GoodsService extends AbstractDataService { @Autowired private GoodsRepository goodsRepository; @Autowired private GoodsGalleryRepository goodsGalleryRepository; @Autowired private GoodsSpecificationRepository goodsSpecificationRepository; @Autowired private CartRepository cartRepository; @Autowired private ProductRepository productRepository; @Override protected Class<?> getModelClass() { return Goods.class; } public JsonGoods save(Goods goods, List<String> galleryImgs, Specification specification, List<Product> products) { Long id = goods.getId(); goods.setHttpsPicUrl(goods.getListPicUrl()); goods.setKeywords(""); goods.setIsDelete(false); if(goods.getIsOnSale() == null) { goods.setIsOnSale(false); } if(id != null && id > 0) { goodsRepository.save(goods); saveGalleryImages(goods, galleryImgs); int check = Boolean.TRUE.equals(goods.getIsOnSale()) ? 1 : 0; cartRepository.updateByGoods(check, goods.getIsOnSale(), goods.getListPicUrl(), goods.getFreightTemplateId(), goods.getId()); productRepository.findByGoods(goods.getId()).forEach(p -> { p.setIsDelete(true); productRepository.save(p); }); goodsSpecificationRepository.findByGoods(goods.getId()).forEach(gs -> { gs.setIsDelete(true); goodsSpecificationRepository.save(gs); }); for(Product item : products) { String goodsSpecificationNameValue = item.getValue(); String goodsSn = item.getGoodsSn(); if(item.getId() != null && item.getId() > 0) { cartRepository.updateByProduct(item.getRetailPrice(), goodsSpecificationNameValue, goodsSn, item.getId()); item.setGoods(goods); item.setIsDelete(false); List<Product> exists = productRepository.findByGoodsSn(goodsSn); if(item.getId() != null && !exists.isEmpty() && exists.get(0).getId().intValue() != item.getId().intValue()) { throw new ServiceException("商品SKU已存在"); } productRepository.save(item); Optional<GoodsSpecification> goodsSpecificationOpt = goodsSpecificationRepository.findById(Long.valueOf(item.getGoodsSpecificationIds())); if(goodsSpecificationOpt.isPresent()) { GoodsSpecification gs = goodsSpecificationOpt.get(); gs.setGoods(goods); gs.setValue(goodsSpecificationNameValue); gs.setSpecification(specification); gs.setIsDelete(false); goodsSpecificationRepository.save(gs); } } else { List<Product> exists = productRepository.findByGoodsSn(goodsSn); if(!exists.isEmpty()) { throw new ServiceException("商品SKU已存在"); } GoodsSpecification gs = new GoodsSpecification(); gs.setGoods(goods); gs.setValue(goodsSpecificationNameValue); gs.setSpecification(specification); gs.setIsDelete(false); gs.setPicUrl(""); goodsSpecificationRepository.save(gs); item.setGoodsSpecificationIds(gs.getId().toString()); item.setGoods(goods); item.setIsDelete(false); productRepository.save(item); } } } else { goods.setCostPrice("0"); goods.setGoodsNumber(0); goods.setRetailPrice("0"); goodsRepository.save(goods); saveGalleryImages(goods, galleryImgs); for(Product item : products) { GoodsSpecification gs = new GoodsSpecification(); gs.setGoods(goods); gs.setSpecification(specification); gs.setValue(item.getValue()); gs.setPicUrl(""); gs.setIsDelete(false); goodsSpecificationRepository.save(gs); item.setGoodsSpecificationIds(gs.getId().toString()); item.setGoods(goods); item.setIsOnSale(true); gs.setIsDelete(false); productRepository.save(item); } } List<Product> productList = productRepository.findByGoodsAndIsOnSaleAndIsDelete(goods.getId(), true, false); int goodsNum = 0; BigDecimal maxRetailPrice = new BigDecimal(0); BigDecimal minRetailPrice = productList.isEmpty() ? new BigDecimal(0) : new BigDecimal(Integer.MAX_VALUE); BigDecimal maxCost = new BigDecimal(0); BigDecimal minCost = new BigDecimal(0); for(Product p : productList) { goodsNum += p.getGoodsNumber(); if(maxRetailPrice.doubleValue() < p.getRetailPrice().doubleValue()) { maxRetailPrice = p.getRetailPrice(); } if(minRetailPrice.doubleValue() > p.getRetailPrice().doubleValue()) { minRetailPrice = p.getRetailPrice(); } if(maxCost.doubleValue() < p.getCost().doubleValue()) { maxCost = p.getCost(); } if(minCost.doubleValue() > p.getCost().doubleValue()) { minCost = p.getCost(); } } String goodsPrice = minRetailPrice.toString(); if(maxRetailPrice.subtract(minRetailPrice).doubleValue() > 0.01) { goodsPrice = minRetailPrice.toString() + '~' + maxRetailPrice.toString(); } String costPrice = minCost.toString() + '~' + maxCost.toString(); goods.setGoodsNumber(goodsNum); goods.setRetailPrice(goodsPrice); goods.setCostPrice(costPrice); goods.setMinRetailPrice(minRetailPrice); goods.setMinCostPrice(minCost); goodsRepository.save(goods); return new JsonGoods(goods); } // public JsonGoods save(Goods goods, Specification specification, List<Product> products) { // Long id = goods.getId(); // // if(id != null && id > 0) { // goodsRepository.save(goods); // int check = Boolean.TRUE.equals(goods.getIsOnSale()) ? 1 : 0; // cartRepository.updateByGoods(check, goods.getIsOnSale(), goods.getListPicUrl(), goods.getFreightTemplateId(), goods.getId()); // // productRepository.findByGoods(goods.getId()).forEach(p -> { // p.setIsDelete(true); // productRepository.save(p); // }); // // goodsSpecificationRepository.findByGoods(goods.getId()).forEach(gs -> { // gs.setIsDelete(true); // goodsSpecificationRepository.save(gs); // }); // // for(Product item : products) { // String goodsSpecificationNameValue = item.getValue(); // String goodsSn = item.getGoodsSn(); // if(item.getId() != null && item.getId() > 0) { // cartRepository.updateByProduct(item.getRetailPrice(), goodsSpecificationNameValue, goodsSn, item.getId()); // item.setIsDelete(false); // productRepository.save(item); // // Optional<GoodsSpecification> goodsSpecificationOpt = // goodsSpecificationRepository.findById(Long.valueOf(item.getGoodsSpecificationIds())); // // if(goodsSpecificationOpt.isPresent()) { // GoodsSpecification gs = goodsSpecificationOpt.get(); // gs.setValue(goodsSpecificationNameValue); // gs.setSpecification(specification); // gs.setIsDelete(false); // goodsSpecificationRepository.save(gs); // } // } // else { // GoodsSpecification gs = new GoodsSpecification(); // gs.setValue(goodsSpecificationNameValue); // gs.setGoods(goods); // gs.setSpecification(specification); // gs.setIsDelete(false); // goodsSpecificationRepository.save(gs); // // item.setGoodsSpecificationIds(gs.getId().toString()); // item.setGoods(goods); // productRepository.save(item); // } // } // } // else { // goodsRepository.save(goods); // // for(Product item : products) { // GoodsSpecification gs = new GoodsSpecification(); // gs.setGoods(goods); // gs.setSpecification(specification); // gs.setValue(item.getValue()); // goodsSpecificationRepository.save(gs); // // item.setGoodsSpecificationIds(gs.getId().toString()); // item.setGoods(goods); // item.setIsOnSale(true); // productRepository.save(item); // } // } // // List<Product> productList = productRepository.findByGoodsAndIsOnSaleAndIsDelete(goods.getId(), true, false); // int goodsNum = 0; // BigDecimal maxRetailPrice = new BigDecimal(0); // BigDecimal minRetailPrice = new BigDecimal(Integer.MAX_VALUE); // BigDecimal maxCost = new BigDecimal(0); // BigDecimal minCost = new BigDecimal(0); // for(Product p : productList) { // goodsNum += p.getGoodsNumber(); // if(maxRetailPrice.doubleValue() < p.getRetailPrice().doubleValue()) { // maxRetailPrice = p.getRetailPrice(); // } // if(minRetailPrice.doubleValue() > p.getRetailPrice().doubleValue()) { // minRetailPrice = p.getRetailPrice(); // } // // if(maxCost.doubleValue() < p.getCost().doubleValue()) { // maxCost = p.getCost(); // } // if(minCost.doubleValue() > p.getCost().doubleValue()) { // minCost = p.getCost(); // } // } // // String goodsPrice = minRetailPrice.toString(); // if(maxRetailPrice.subtract(minRetailPrice).doubleValue() > 0.01) { // goodsPrice = minRetailPrice.toString() + '~' + maxRetailPrice.toString(); // } // String costPrice = minCost.toString() + '~' + maxCost.toString(); // // goods.setGoodsNumber(goodsNum); // goods.setRetailPrice(goodsPrice); // goods.setCostPrice(costPrice); // goods.setMinRetailPrice(minRetailPrice); // goods.setMinCostPrice(minCost); // goodsRepository.save(goods); // // return new JsonGoods(goods); // } private void saveGalleryImages(Goods goods, List<String> galleryImgs) { if(goods.getId() != null) { List<GoodsGallery> persistList = goodsGalleryRepository.findByGoods(goods); persistList.forEach(gg -> { gg.setIsDelete(true); goodsGalleryRepository.save(gg); }); } for(int i = 0; i < galleryImgs.size(); i++) { String img = galleryImgs.get(i); GoodsGallery gg = new GoodsGallery(); gg.setGoods(goods); gg.setImgUrl(img); gg.setIsDelete(false); gg.setImgDesc(""); gg.setSortOrder(i + 1); goodsGalleryRepository.save(gg); } } @Override protected void afterCreate(Module module, List<ActionData> dataList) { super.afterCreate(module, dataList); dataList.forEach(actionData -> { actionData.getData().forEach(data -> { Goods goods = module.fromData(data); List<GoodsGallery> persistList = goodsGalleryRepository.findByGoods(goods); persistList.forEach(gg -> { goodsGalleryRepository.delete(gg); }); String galleryImgs = (String) data.get("galleryImgs"); if(StringUtils.hasText(galleryImgs)) { String[] array = galleryImgs.split(","); for(int i = 0; i < array.length; i++) { if(StringUtils.hasText(array[i])) { GoodsGallery gg = new GoodsGallery(); gg.setGoods(goods); gg.setImgUrl(array[i]); gg.setIsDelete(false); gg.setSortOrder(i + 1); goodsGalleryRepository.save(gg); } } } }); }); } @Override protected void afterUpdate(Module module, List<Map<String, Object>> dataList) { super.afterUpdate(module, dataList); dataList.forEach(data -> { Goods goods = module.fromData(data); List<GoodsGallery> persistList = goodsGalleryRepository.findByGoods(goods); persistList.forEach(gg -> { goodsGalleryRepository.delete(gg); }); String galleryImgs = (String) data.get("galleryImgs"); if(StringUtils.hasText(galleryImgs)) { String[] array = galleryImgs.split(","); for(int i = 0; i < array.length; i++) { if(StringUtils.hasText(array[i])) { GoodsGallery gg = new GoodsGallery(); gg.setGoods(goods); gg.setImgUrl(array[i]); gg.setIsDelete(false); gg.setImgDesc(""); gg.setSortOrder(i + 1); goodsGalleryRepository.save(gg); } } } }); } } <|start_filename|>booking-admin/src/main/java/org/needle/bookingdiscount/admin/service/SettingsService.java<|end_filename|> package org.needle.bookingdiscount.admin.service; import java.util.List; import java.util.Map; import org.needle.bookingdiscount.admin.repository.RegionRepository; import org.needle.bookingdiscount.domain.freight.Settings; import org.needle.bookingdiscount.domain.support.Region; import org.needleframe.core.model.ActionData; import org.needleframe.core.model.Module; import org.needleframe.core.service.AbstractDataService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class SettingsService extends AbstractDataService { @Autowired private RegionRepository regionRepository; @Override protected Class<?> getModelClass() { return Settings.class; } @Override protected void beforeCreate(Module module, List<ActionData> dataList) { dataList.forEach(actionData -> { actionData.getData().forEach(data -> { Settings settings = module.fromData(data); Region province = regionRepository.findById(settings.getProvince().getId()).get(); Region city = regionRepository.findById(settings.getCity().getId()).get(); Region district = regionRepository.findById(settings.getDistrict().getId()).get(); data.put("provinceName", province.getName()); data.put("cityName", city.getName()); data.put("expAreaName", district.getName()); }); }); } @Override protected void beforeUpdate(Module module, List<Map<String, Object>> dataList) { dataList.forEach(data -> { Settings settings = module.fromData(data); Region province = regionRepository.findById(settings.getProvince().getId()).get(); Region city = regionRepository.findById(settings.getCity().getId()).get(); Region district = regionRepository.findById(settings.getDistrict().getId()).get(); data.put("provinceName", province.getName()); data.put("cityName", city.getName()); data.put("expAreaName", district.getName()); }); } } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/support/Keywords.java<|end_filename|> package org.needle.bookingdiscount.domain.support; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import org.needle.bookingdiscount.domain.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper=true) @Entity @Table(name="needle_keywords") public class Keywords extends BaseEntity { @Column(name="keyword", length=90) private String keyword; @Column(name="is_hot", columnDefinition="tinyint(1) unsigned default 0") private Boolean isHot; @Column(name="is_default", columnDefinition="tinyint(1) unsigned default 0") private Boolean isDefault; @Column(name="is_show", columnDefinition="tinyint(1) unsigned default 1") private Boolean isShow; @Column(name="sort_order") private Integer sortOrder; @Column(name="scheme_url", length=255) private String scheme_url; @Column(name="type", columnDefinition="int(11) unsigned default 0") private Integer type; @Data public static class JsonKeywords { private Long id; private String keyword; private Boolean is_hot; private Boolean is_default; private Boolean is_show; private Integer sort_order; private String scheme_url; private Integer type; public JsonKeywords(Keywords keywords) { this.id = keywords.getId(); this.keyword = keywords.getKeyword(); this.is_hot = keywords.getIsHot(); this.is_default = keywords.getIsDefault(); this.is_show = keywords.getIsShow(); this.sort_order = keywords.getSortOrder(); this.scheme_url = keywords.getScheme_url(); this.type = keywords.getType(); } } } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/support/ExceptAreaDetail.java<|end_filename|> package org.needle.bookingdiscount.domain.support; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.needle.bookingdiscount.domain.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper=true) @Entity @Table(name="needle_except_area_detail") public class ExceptAreaDetail extends BaseEntity { @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="except_area_id") private ExceptArea exceptArea; @Column(name="area", columnDefinition="int(5) default 0") private Integer area; @Column(name="is_delete", columnDefinition="tinyint(1) default 0") private Boolean isDelete; } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/order/OrderExpress.java<|end_filename|> package org.needle.bookingdiscount.domain.order; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.needle.bookingdiscount.domain.BaseEntity; import org.needle.bookingdiscount.domain.freight.Shipper; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper=true) @Entity @Table(name="needle_order_express") public class OrderExpress extends BaseEntity { @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="order_id") private Order order; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="shipper_id") private Shipper shipper; @Column(name="shipper_name", length=120) private String shipperName; @Column(name="shipper_code", length=60) private String shipperCode; @Column(name="logistic_code", length=40) private String logisticCode; @Column(name="traces", length=2000) private String traces; @Column(name="is_finish", columnDefinition="tinyint(1) default 0") private Boolean isFinish; @Column(name="request_count", columnDefinition="int(11)") private Integer requestCount; @Column(name="request_time", columnDefinition="int(11)") private Integer requestTime; @Column(name="add_time", columnDefinition="int(11)") private Integer addTime; @Column(name="update_time", columnDefinition="int(11)") private Integer updateTime; @Column(name="express_type", columnDefinition="tinyint(1)") private Integer expressType; @Column(name="region_code", length=10) private String regionCode; @Column(name="express_status", length=200) private String expressStatus; @Data public static class JsonOrderExpress { private Long id; private Long order_id; private Long shipper_id; private String shipper_name; private String shipper_code; private String logistic_code; private String traces; private Boolean is_finish; private Integer request_count; private Integer request_time; private Integer add_time; private Integer update_time; private Integer express_type; private String region_code; private String express_status; public JsonOrderExpress(OrderExpress orderExpress) { this.id = orderExpress.getId(); this.order_id = orderExpress.getOrder().getId(); this.shipper_id = orderExpress.getShipper().getId(); this.shipper_name = orderExpress.getShipperName(); this.shipper_code = orderExpress.getShipperCode(); this.logistic_code = orderExpress.getLogisticCode(); this.traces = orderExpress.getTraces(); this.is_finish = orderExpress.getIsFinish(); this.request_count = orderExpress.getRequestCount(); this.request_time = orderExpress.getRequestTime(); this.add_time = orderExpress.getAddTime(); this.update_time = orderExpress.getUpdateTime(); this.express_type = orderExpress.getExpressType(); this.region_code = orderExpress.getRegionCode(); this.express_status = orderExpress.getExpressStatus(); } } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/service/CartService.java<|end_filename|> package org.needle.bookingdiscount.server.service; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import org.needle.bookingdiscount.domain.cart.Cart; import org.needle.bookingdiscount.domain.cart.Cart.JsonCart; import org.needle.bookingdiscount.domain.freight.FreightTemplate; import org.needle.bookingdiscount.domain.freight.FreightTemplateDetail; import org.needle.bookingdiscount.domain.freight.FreightTemplateGroup; import org.needle.bookingdiscount.domain.member.Address; import org.needle.bookingdiscount.domain.member.Address.JsonAddress; import org.needle.bookingdiscount.domain.member.MemberUser; import org.needle.bookingdiscount.domain.order.OrderGoods; import org.needle.bookingdiscount.domain.product.Goods; import org.needle.bookingdiscount.domain.product.GoodsSpecification; import org.needle.bookingdiscount.domain.product.Product; import org.needle.bookingdiscount.server.exception.ServiceException; import org.needle.bookingdiscount.server.repository.cart.CartRepository; import org.needle.bookingdiscount.server.repository.freight.FreightTemplateDetailRepository; import org.needle.bookingdiscount.server.repository.freight.FreightTemplateGroupRepository; import org.needle.bookingdiscount.server.repository.freight.FreightTemplateRepository; import org.needle.bookingdiscount.server.repository.member.AddressRepository; import org.needle.bookingdiscount.server.repository.order.OrderGoodsRepository; import org.needle.bookingdiscount.server.repository.product.GoodsRepository; import org.needle.bookingdiscount.server.repository.product.GoodsSpecificationRepository; import org.needle.bookingdiscount.server.repository.product.ProductRepository; import org.needle.bookingdiscount.server.repository.support.RegionRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.ModelMap; import org.springframework.util.StringUtils; @Service @Transactional public class CartService { @Autowired private CartRepository cartRepository; @Autowired private GoodsRepository goodsRepository; @Autowired private ProductRepository productRepository; @Autowired private GoodsSpecificationRepository goodsSpecificationRepository; @Autowired private OrderGoodsRepository orderGoodsRepository; @Autowired private AddressRepository addressRepository; @Autowired private FreightTemplateRepository freightTemplateRepository; @Autowired private FreightTemplateDetailRepository freightTemplateDetailRepository; @Autowired private RegionRepository regionRepository; @Autowired private FreightTemplateGroupRepository freightTemplateGroupRepository; private ModelMap getCart(Long userId, int type) { List<Cart> cartList = new ArrayList<Cart>(); if(type == 0) { cartList = cartRepository.findUserCarts(userId, false, false); } else { cartList = cartRepository.findUserCarts(userId, true, false); } // 获取购物车统计信息 int goodsCount = 0; BigDecimal goodsAmount = new BigDecimal(0); int checkedGoodsCount = 0; BigDecimal checkedGoodsAmount = new BigDecimal(0); int numberChange = 0; for(Cart cartItem : cartList) { Product product = cartItem.getProduct(); cartItem.setGoodsNumber(product.getGoodsNumber()); // 设置产品库存 if(Boolean.TRUE.equals(product.getIsDelete())) { Cart cart = cartRepository.getByUserAndProduct(userId, product.getId()); cart.setIsDelete(true); cartRepository.save(cart); } else { BigDecimal retailPrice = product.getRetailPrice(); int productNum = product.getGoodsNumber(); if(productNum <= 0 || Boolean.FALSE.equals(product.getIsOnSale())) { Cart cart = cartRepository.getByUserAndProductAndChecked(userId, product.getId(), 1); if(cart != null) { cart.setChecked(0); cartRepository.save(cart); } cartItem.setNumber(0); } else if(productNum > 0 && productNum < cartItem.getNumber()) { cartItem.setNumber(productNum); numberChange = 1; } else if(productNum > 0 && cartItem.getNumber() == 0) { cartItem.setNumber(1); numberChange = 1; } goodsCount += cartItem.getNumber(); goodsAmount = goodsAmount.add(retailPrice.multiply(new BigDecimal(cartItem.getNumber()))); cartItem.setRetailPrice(retailPrice); if(cartItem.getChecked() > 0 && productNum > 0) { checkedGoodsCount += cartItem.getNumber(); checkedGoodsAmount = checkedGoodsAmount.add(retailPrice.multiply(new BigDecimal(cartItem.getNumber()))); } Goods goods = cartItem.getGoods(); cartItem.setListPicUrl(goods.getListPicUrl()); cartItem.setWeightCount(cartItem.getNumber() * cartItem.getGoodsWeight()); cartItem.setAddPrice(retailPrice); cartRepository.save(cartItem); // Cart cart = cartRepository.getByUserAndProduct(userId, cartItem.getProduct().getId()); // if(cart != null) { // cart.setNumber(cartItem.getNumber()); // cart.setAddPrice(retailPrice); // cartRepository.save(cart); // } } } Map<String,Object> cartTotalMap = new HashMap<String,Object>(); cartTotalMap.put("goodsCount", goodsCount); cartTotalMap.put("goodsAmount", goodsAmount.setScale(2, BigDecimal.ROUND_HALF_UP)); cartTotalMap.put("checkedGoodsCount", checkedGoodsCount); cartTotalMap.put("checkedGoodsAmount", checkedGoodsAmount.setScale(2, BigDecimal.ROUND_HALF_UP)); cartTotalMap.put("user_id", userId); cartTotalMap.put("numberChange", numberChange); ModelMap model = new ModelMap(); model.addAttribute("cartList", cartList.stream().map(c -> new JsonCart(c)).collect(Collectors.toList())); model.addAttribute("cartTotal", cartTotalMap); return model; } public ModelMap getIndexData(Long userId) { return getCart(userId, 0); } // 0:正常加入购物车,1:立即购买,2:再来一单 public ModelMap add(Long userId, Long goodsId, Long productId, int number, int addType) { int currentTime = new Long(new Date().getTime() / 1000).intValue(); Optional<Goods> goodsInfoOpt = goodsRepository.findById(goodsId); if(!goodsInfoOpt.isPresent() || Boolean.FALSE.equals(goodsInfoOpt.get().getIsOnSale())) { throw new ServiceException("400", "商品已下架"); } Goods goodsInfo = goodsInfoOpt.get(); // 取得规格的信息,判断规格库存 Optional<Product> productInfoOpt = productRepository.findById(productId); if(!productInfoOpt.isPresent() || productInfoOpt.get().getGoodsNumber() < number) { throw new ServiceException("400", "库存不足"); } MemberUser user = new MemberUser(userId); Product productInfo = productInfoOpt.get(); // 判断购物车中是否存在此规格商品 BigDecimal retailPrice = productInfo.getRetailPrice(); if (addType == 1) { cartRepository.findByUserAndIsDelete(userId, false).forEach(cart -> { cart.setChecked(0); cartRepository.save(cart); }); List<String> goodsSepcifitionValue = new ArrayList<String>(); String goodsSpecificationIds = productInfo.getGoodsSpecificationIds(); if(StringUtils.hasText(goodsSpecificationIds)) { List<Long> ids = new ArrayList<Long>(); String[] stringIds = goodsSpecificationIds.split("_"); for(int i = 0; i < stringIds.length; i++) { String stringId = stringIds[i]; if(StringUtils.hasText(stringId)) { ids.add(Long.valueOf(stringId)); } } List<GoodsSpecification> gsList = goodsSpecificationRepository.findByGoodsAndIsDeleteAndIdIn(productInfo.getGoods().getId(), false, ids); goodsSepcifitionValue = gsList.stream().map(gs -> gs.getValue()).collect(Collectors.toList()); } // 添加到购物车 Cart cart = new Cart(); cart.setGoods(productInfo.getGoods()); cart.setProduct(productInfo); cart.setGoodsSn(productInfo.getGoodsSn()); cart.setGoodsName(goodsInfo.getName()); cart.setGoodsAka(productInfo.getGoodsName()); cart.setGoodsWeight(productInfo.getGoodsWeight()); cart.setFreightTemplateId(goodsInfo.getFreightTemplateId()); cart.setListPicUrl(goodsInfo.getListPicUrl()); cart.setNumber(number); cart.setUser(user); cart.setRetailPrice(retailPrice); cart.setAddPrice(retailPrice); cart.setGoodsSpecificationNameValue(goodsSepcifitionValue.stream().collect(Collectors.joining(";"))); cart.setGoodsSpecificationIds(productInfo.getGoodsSpecificationIds()); cart.setChecked(1); cart.setAddTime(currentTime); cart.setIsFast(true); cartRepository.save(cart); return this.getCart(userId, 1); } else { Cart cartInfo = cartRepository.getByUserAndProduct(userId, productId); if(cartInfo == null || Boolean.TRUE.equals(cartInfo.getIsDelete())) { // 添加操作 // 添加规格名和值 List<String> goodsSepcifitionValue = new ArrayList<String>(); String goodsSpecificationIds = productInfo.getGoodsSpecificationIds(); if(StringUtils.hasText(goodsSpecificationIds)) { List<Long> ids = new ArrayList<Long>(); String[] stringIds = goodsSpecificationIds.split("_"); for(int i = 0; i < stringIds.length; i++) { String stringId = stringIds[i]; if(StringUtils.hasText(stringId)) { ids.add(Long.valueOf(stringId)); } } List<GoodsSpecification> gsList = goodsSpecificationRepository.findByGoodsAndIsDeleteAndIdIn(productInfo.getGoods().getId(), false, ids); goodsSepcifitionValue = gsList.stream().map(gs -> gs.getValue()).collect(Collectors.toList()); } // 添加到购物车 Cart cart = new Cart(); cart.setGoods(productInfo.getGoods()); cart.setProduct(productInfo); cart.setGoodsSn(productInfo.getGoodsSn()); cart.setGoodsName(goodsInfo.getName()); cart.setGoodsAka(productInfo.getGoodsName()); cart.setGoodsWeight(productInfo.getGoodsWeight()); cart.setFreightTemplateId(goodsInfo.getFreightTemplateId()); cart.setListPicUrl(goodsInfo.getListPicUrl()); cart.setNumber(number); cart.setUser(user); cart.setRetailPrice(retailPrice); cart.setAddPrice(retailPrice); cart.setGoodsSpecificationNameValue(goodsSepcifitionValue.stream().collect(Collectors.joining(";"))); cart.setGoodsSpecificationIds(productInfo.getGoodsSpecificationIds()); cart.setChecked(1); cart.setAddTime(currentTime); cart.setIsDelete(false); cartRepository.save(cart); } else { // 如果已经存在购物车中,则数量增加 if(productInfo.getGoodsNumber() < (number + cartInfo.getNumber())) { throw new ServiceException("400", "库存不足"); } cartInfo.setRetailPrice(retailPrice); cartInfo.setNumber(cartInfo.getNumber() + 1); cartRepository.save(cartInfo); } return this.getCart(userId, 0); } } public ModelMap update(Long userId, Long productId, Long id, int number) { // 取得规格的信息,判断规格库存 Optional<Product> productInfoOpt = productRepository.findById(productId); if(!productInfoOpt.isPresent() || Boolean.TRUE.equals(productInfoOpt.get().getIsDelete()) || productInfoOpt.get().getGoodsNumber() < number) { throw new ServiceException("400", "库存不足"); } Cart cartInfo = cartRepository.findById(id).get(); if(cartInfo.getProduct().getId() == productId) { cartInfo.setNumber(number); cartRepository.save(cartInfo); } return getCart(userId, 0); } public ModelMap delete(Long userId, Long productIds) { Long productId = productIds; if(productId == null) { throw new ServiceException("删除出错"); } Cart cart = cartRepository.getByUserAndProduct(userId, productId); if(cart != null) { cart.setIsDelete(true); cartRepository.save(cart); } return this.getCart(userId, 0); } public ModelMap check(Long userId, String productIds, Boolean isChecked) { if(!StringUtils.hasText(productIds)) { throw new ServiceException("删除出错"); } String productId = productIds.toString(); String[] productIdArray = productId.split(","); List<Long> ids = new ArrayList<Long>(); for(int i = 0; i < productIdArray.length; i++) { if(StringUtils.hasText(productIdArray[i])) { ids.add(Long.valueOf(productIdArray[i])); } } cartRepository.findByUserAndProductIn(userId, ids).forEach(cart -> { cart.setChecked(Boolean.TRUE.equals(isChecked) ? 1 : 0); cartRepository.save(cart); }); return this.getCart(userId, 0); } @SuppressWarnings("unchecked") public ModelMap goodsCount(Long userId) { ModelMap cartData = this.getCart(userId, 0); List<Cart> cartList = cartRepository.findByUserAndIsDeleteAndIsFast(userId, false, true); cartList.forEach(cart -> { cart.setIsDelete(true); cartRepository.save(cart); }); Map<String,Object> cartTotal = (Map<String, Object>) cartData.get("cartTotal"); ModelMap model = new ModelMap(); Map<String,Object> dataMap = new HashMap<String,Object>(); dataMap.put("goodsCount", cartTotal.get("goodsCount")); model.addAttribute("cartTotal", dataMap); return model; } public void addAgain(Long userId, Long goodsId, Long productId, int number) { int currentTime = new Long(new Date().getTime() / 1000).intValue(); Optional<Goods> goodsInfoOpt = goodsRepository.findById(goodsId); if(!goodsInfoOpt.isPresent() || Boolean.FALSE.equals(goodsInfoOpt.get().getIsOnSale())) { throw new ServiceException("400", "商品已下架"); } // 取得规格的信息,判断规格库存 Optional<Product> productInfoOpt = productRepository.findById(productId); if (!productInfoOpt.isPresent() || productInfoOpt.get().getGoodsNumber() < number) { throw new ServiceException("400", "库存不足"); } MemberUser user = new MemberUser(); user.setId(userId); Product productInfo = productInfoOpt.get(); // 判断购物车中是否存在此规格商品 Cart cartInfo = cartRepository.getByUserAndProduct(userId, productId); BigDecimal retailPrice = productInfo.getRetailPrice(); if(cartInfo == null) { // 添加操作 // 添加规格名和值 List<String> goodsSepcifitionValue = new ArrayList<String>(); String goodsSpecificationIds = productInfo.getGoodsSpecificationIds(); if(StringUtils.hasText(goodsSpecificationIds)) { List<Long> ids = new ArrayList<Long>(); String[] sids = goodsSpecificationIds.split("_"); for(int i = 0; i < sids.length; i++) { if(StringUtils.hasText(sids[i])) { ids.add(Long.valueOf(sids[i])); } } List<GoodsSpecification> gsList = goodsSpecificationRepository.findByGoodsAndIsDeleteAndIdIn(productInfo.getGoods().getId(), false, ids); goodsSepcifitionValue = gsList.stream().map(gs -> gs.getValue()).collect(Collectors.toList()); } Goods goodsInfo = productInfo.getGoods(); // 添加到购物车 Cart cart = new Cart(); cart.setGoods(productInfo.getGoods()); cart.setProduct(productInfo); cart.setGoodsSn(productInfo.getGoodsSn()); cart.setGoodsName(goodsInfo.getName()); cart.setGoodsAka(productInfo.getGoodsName()); cart.setGoodsWeight(productInfo.getGoodsWeight()); cart.setFreightTemplateId(goodsInfo.getFreightTemplateId()); cart.setListPicUrl(goodsInfo.getListPicUrl()); cart.setNumber(number); cart.setUser(user); cart.setRetailPrice(retailPrice); cart.setAddPrice(retailPrice); cart.setGoodsSpecificationNameValue(goodsSepcifitionValue.stream().collect(Collectors.joining(";"))); cart.setGoodsSpecificationIds(productInfo.getGoodsSpecificationIds()); cart.setChecked(1); cart.setAddTime(currentTime); cart.setIsDelete(false); cartRepository.save(cart); } else { // 如果已经存在购物车中,则数量增加 if(productInfo.getGoodsNumber() < (number + cartInfo.getNumber())) { throw new ServiceException("400", "库存不足"); } cartInfo.setRetailPrice(retailPrice); cartInfo.setChecked(1); cartInfo.setNumber(number); cartRepository.save(cartInfo); } } private ModelMap getAgainCart(Long userId, String orderFrom) { cartRepository.findByUserAndIsDelete(userId, false).forEach(cart -> { cart.setChecked(0); cartRepository.save(cart); }); List<OrderGoods> againGoods = orderGoodsRepository.findByOrder(Long.valueOf(orderFrom)); againGoods.forEach(item -> { this.addAgain(userId, item.getGoods().getId(), item.getProduct().getId(), item.getNumber()); }); // 获取购物车统计信息 int goodsCount = 0; BigDecimal goodsAmount = new BigDecimal(0); int checkedGoodsCount = 0; BigDecimal checkedGoodsAmount = new BigDecimal(0); List<Cart> cartList = cartRepository.findByUserAndIsDeleteAndIsFast(userId, false, false); for(Cart cartItem : cartList) { goodsCount += cartItem.getNumber(); goodsAmount = goodsAmount.add(new BigDecimal(cartItem.getNumber()).multiply(cartItem.getRetailPrice())); if(cartItem.getChecked() > 0) { checkedGoodsCount += cartItem.getNumber(); checkedGoodsAmount = checkedGoodsAmount.add(cartItem.getRetailPrice().multiply(new BigDecimal(cartItem.getNumber()))); } // 查找商品的图片 Goods goodsInfo = cartItem.getGoods(); int num = goodsInfo.getGoodsNumber(); if (num <= 0) { Cart cart = cartRepository.getByUserAndProductAndChecked(userId, cartItem.getProduct().getId(), 1); if(cart != null) { cart.setChecked(0); cartRepository.save(cart); } } cartItem.setListPicUrl(goodsInfo.getListPicUrl()); cartItem.setGoodsNumber(goodsInfo.getGoodsNumber()); cartItem.setWeightCount(cartItem.getNumber() * cartItem.getGoodsWeight()); } Map<String,Object> cartTotal = new LinkedHashMap<String,Object>(); cartTotal.put("goodsCount", goodsCount); cartTotal.put("goodsAmount", goodsAmount.setScale(2, BigDecimal.ROUND_HALF_UP)); cartTotal.put("checkedGoodsCount", checkedGoodsCount); cartTotal.put("checkedGoodsAmount", checkedGoodsAmount.setScale(2, BigDecimal.ROUND_HALF_UP)); cartTotal.put("user_id", userId); ModelMap model = new ModelMap(); model.addAttribute("cartList", cartList); model.addAttribute("cartTotal", cartTotal); return model; } @SuppressWarnings("unchecked") public ModelMap checkout(Long userId, String orderFrom, int type, String addressId, int addType) { int goodsCount = 0; // 购物车的数量 BigDecimal goodsMoney = new BigDecimal(0); // 购物车的总价 BigDecimal freightPrice = new BigDecimal(0); int outStock = 0; ModelMap cartData = new ModelMap(); // 获取要购买的商品 if(type == 0) { if (addType == 0) { cartData = this.getCart(userId, 0); } else if (addType == 1) { cartData = this.getCart(userId, 1); } else if (addType == 2) { cartData = this.getAgainCart(userId, orderFrom); } } List<JsonCart> cartList = (List<JsonCart>) cartData.get("cartList"); List<JsonCart> checkedGoodsList = cartList.stream().filter(cart -> cart.getChecked() == 1).collect(Collectors.toList()); for(JsonCart item : checkedGoodsList) { goodsCount = goodsCount + item.getNumber(); goodsMoney = goodsMoney.add(new BigDecimal(item.getNumber()).multiply(item.getRetail_price())); if(item.getGoods_number() <= 0 || Boolean.FALSE.equals(item.getIs_on_sale())) { outStock = outStock + 1; } } if(addType == 2) { List<OrderGoods> againGoods = orderGoodsRepository.findByOrder(Long.valueOf(orderFrom)); int againGoodsCount = 0; for(OrderGoods item : againGoods) { againGoodsCount = againGoodsCount + item.getNumber(); } if(goodsCount != againGoodsCount) { outStock = 1; } } // 选择的收货地址 List<Address> checkedAddressList = new ArrayList<Address>(); if(!StringUtils.hasText(addressId) || "0".equals(addressId)) { checkedAddressList = addressRepository.findByUserAndIsDefaultAndIsDelete(userId, true, false); } else { Optional<Address> addressOpt = addressRepository.findById(Long.valueOf(addressId)); if(addressOpt.isPresent() && Boolean.FALSE.equals(addressOpt.get().getIsDelete())) { checkedAddressList.add(addressOpt.get()); } } Address checkedAddress = null; if(checkedAddressList.size() > 0) { checkedAddress = checkedAddressList.get(0); // 运费开始 // 先将促销规则中符合满件包邮或者满金额包邮的规则找到; // 先看看是不是属于偏远地区。 Long provinceId = checkedAddress.getProvinceId(); // 得到数组了,然后去判断这两个商品符不符合要求 // 先用这个goods数组去遍历 List<JsonCart> cartGoods = checkedGoodsList; List<FreightTemplate> freightTempArray = freightTemplateRepository.findByIsDelete(false); List<Map<String,Object>> freightData = new ArrayList<Map<String,Object>>(); for(FreightTemplate item : freightTempArray) { Map<String,Object> dataMap = new LinkedHashMap<String,Object>(); dataMap.put("id", item.getId()); dataMap.put("number", 0); dataMap.put("money", new BigDecimal(0)); dataMap.put("goods_weight", 0); dataMap.put("freight_type", item.getFreightType()); freightData.add(dataMap); } // 按件计算和按重量计算的区别是:按件,只要算goods_number就可以了,按重量要goods_number*goods_weight for(Map<String,Object> item : freightData) { for(JsonCart cartItem : cartGoods) { if(item.get("id") == cartItem.getFreight_template_id()) { // 这个在判断,购物车中的商品是否属于这个运费模版,如果是,则加一,但是,这里要先判断下,这个商品是否符合满件包邮或满金额包邮,如果是包邮的,那么要去掉 item.put("number", cartItem.getNumber() + (int) item.get("number")); item.put("money", cartItem.getRetail_price().multiply(new BigDecimal(cartItem.getNumber()))); double goodsWeight = Double.valueOf(item.get("goods_weight").toString()); item.put("goods_weight", goodsWeight + cartItem.getNumber() * cartItem.getGoods_weight()); } } } checkedAddress.setProvinceName(regionRepository.findById(checkedAddress.getProvinceId()).get().getName()); checkedAddress.setCityName(regionRepository.findById(checkedAddress.getCityId()).get().getName()); checkedAddress.setDistrictName(regionRepository.findById(checkedAddress.getDistrictId()).get().getName()); checkedAddress.setFullRegion(checkedAddress.getProvinceName() + checkedAddress.getCityName() + checkedAddress.getDistrictName()); for(Map<String,Object> item : freightData) { int number = (int) item.get("number"); double goods_weight = Double.valueOf(item.containsKey("goods_weight") ? item.get("goods_weight").toString() : "0"); BigDecimal money = (BigDecimal) item.get("money"); if(number == 0) { continue; } List<FreightTemplateDetail> exList = freightTemplateDetailRepository.findByTemplateAndArea(new Long(item.get("id").toString()), provinceId.intValue()); BigDecimal freight_price = new BigDecimal(0); if(!exList.isEmpty()) { // console.log('第一层:非默认邮费算法'); FreightTemplateDetail ex = exList.get(0); FreightTemplateGroup groupData = ex.getGroup(); // 不为空,说明有模板,那么应用模板,先去判断是否符合指定的包邮条件,不满足,那么根据type 是按件还是按重量 int free_by_number = groupData.getFreeByNumber(); BigDecimal free_by_money = groupData.getFreeByMoney(); // 4种情况,1、free_by_number > 0 2,free_by_money > 0 3,free_by_number free_by_money > 0,4都等于0 FreightTemplate templateInfo = freightTemplateRepository.findById(new Long(item.get("id").toString())).get(); int freight_type = templateInfo.getFreightType(); if (freight_type == 0) { if (number > groupData.getStart()) { // 说明大于首件了 freight_price = new BigDecimal(groupData.getStart()).multiply(groupData.getStartFee()) .add(new BigDecimal(number - 1).multiply(groupData.getAddFee())); // todo 如果续件是2怎么办??? } else { freight_price = new BigDecimal(groupData.getStart()).multiply(groupData.getStartFee()); } } else if (freight_type == 1) { if (goods_weight > groupData.getStart()) { // 说明大于首件了 freight_price = new BigDecimal(groupData.getStart()).multiply(groupData.getStartFee()) .add(new BigDecimal(goods_weight - 1).multiply(groupData.getAddFee())); // todo 如果续件是2怎么办??? } else { freight_price = new BigDecimal(groupData.getStart()).multiply(groupData.getStartFee()); } } if(free_by_number > 0) { if (number >= free_by_number) { freight_price = new BigDecimal(0); } } if(free_by_money.doubleValue() > 0.01) { if(money.doubleValue() >= free_by_money.doubleValue()) { freight_price = new BigDecimal(0); } } } else { Long templateId = (Long) item.get("id"); // console.log('第二层:使用默认的邮费算法'); List<FreightTemplateGroup> groupDataList = freightTemplateGroupRepository.findByTemplateAndArea(templateId, "0"); FreightTemplateGroup groupData = groupDataList.get(0); int free_by_number = groupData.getFreeByNumber(); BigDecimal free_by_money = groupData.getFreeByMoney(); FreightTemplate templateInfo = freightTemplateRepository.findById(templateId).get(); int freight_type = templateInfo.getFreightType(); if (freight_type == 0) { if (number > groupData.getStart()) { // 说明大于首件了 freight_price = new BigDecimal(groupData.getStart()).multiply(groupData.getStartFee()) .add(new BigDecimal(number - 1).multiply(groupData.getAddFee())); // todo 如果续件是2怎么办??? } else { freight_price = new BigDecimal(groupData.getStart()).multiply(groupData.getStartFee()); } } else if(freight_type == 1) { if (goods_weight > groupData.getStart()) { // 说明大于首件了 freight_price = new BigDecimal(groupData.getStart()).multiply(groupData.getStartFee()) .add(new BigDecimal(goods_weight - 1).multiply(groupData.getAddFee())); // todo 如果续件是2怎么办??? } else { freight_price = new BigDecimal(groupData.getStart()).multiply(groupData.getStartFee()); } } if(free_by_number > 0) { if (number >= free_by_number) { freight_price = new BigDecimal(0); } } if(free_by_money.doubleValue() > 0.01) { if (money.doubleValue() >= free_by_money.doubleValue()) { freight_price = new BigDecimal(0); } } } freightPrice = freightPrice.doubleValue() > freight_price.doubleValue() ? freightPrice : freight_price; // 会得到 几个数组,然后用省id去遍历在哪个数组 } } else { checkedAddress = null; } Map<String,Object> cartTotal = (Map<String, Object>) cartData.get("cartTotal"); // 计算订单的费用 BigDecimal goodsTotalPrice = (BigDecimal) cartTotal.get("checkedGoodsAmount"); // 获取是否有可用红包 BigDecimal money = (BigDecimal) cartTotal.get("checkedGoodsAmount"); BigDecimal orderTotalPrice = new BigDecimal(0.0); orderTotalPrice = money.add(freightPrice); // 订单的总价 BigDecimal actualPrice = orderTotalPrice; // 减去其它支付的金额后,要实际支付的金额 int numberChange = (int) cartTotal.get("numberChange"); ModelMap model = new ModelMap(); model.addAttribute("checkedAddress", checkedAddress == null ? 0 : new JsonAddress(checkedAddress)); model.addAttribute("freightPrice", freightPrice); model.addAttribute("checkedGoodsList", checkedGoodsList); model.addAttribute("goodsTotalPrice", goodsTotalPrice); model.addAttribute("orderTotalPrice", orderTotalPrice.setScale(2, BigDecimal.ROUND_HALF_UP)); model.addAttribute("actualPrice", actualPrice.setScale(2, BigDecimal.ROUND_HALF_UP)); model.addAttribute("goodsCount", goodsCount); model.addAttribute("outStock", outStock); model.addAttribute("numberChange", numberChange); return model; } } <|start_filename|>booking-server/src/test/java/org/needle/booking_server/PayTest.java<|end_filename|> package org.needle.booking_server; import org.needle.bookingdiscount.utils.DateUtils; public class PayTest { // <xml><appid><![CDATA[wx4e9b74e0999d1764]]></appid> // <bank_type><![CDATA[OTHERS]]></bank_type> // <cash_fee><![CDATA[1500]]></cash_fee> // <fee_type><![CDATA[CNY]]></fee_type> // <is_subscribe><![CDATA[N]]></is_subscribe> // <mch_id><![CDATA[1605111309]]></mch_id> // <nonce_str><![CDATA[1613121377575]]></nonce_str> // <openid><![CDATA[oDV-d5eoxj38EoG7zRtCsZfo5ifE]]></openid> // <out_trade_no><![CDATA[12200212000001353]]></out_trade_no> // <result_code><![CDATA[SUCCESS]]></result_code> // <return_code><![CDATA[SUCCESS]]></return_code> // <sign><![CDATA[0AD78B7BEFC08EF61124993F0CD8ACB7]]></sign> // <time_end><![CDATA[20210212171623]]></time_end> // <total_fee>1500</total_fee> // <trade_type><![CDATA[JSAPI]]></trade_type> // <transaction_id><![CDATA[4200000944202102121924625499]]></transaction_id> // </xml> public static void main(String[] args) { // 20210212171623 System.out.println(DateUtils.parseDate("20210212171623", "yyyyMMddHHmmss")); System.out.println((int) (DateUtils.parseDate("20210212171623", "yyyyMMddHHmmss").getTime()/1000)); } } <|start_filename|>booking-admin/src/main/java/org/needle/bookingdiscount/admin/repository/RegionRepository.java<|end_filename|> package org.needle.bookingdiscount.admin.repository; import org.needle.bookingdiscount.domain.support.Region; import org.springframework.data.repository.PagingAndSortingRepository; public interface RegionRepository extends PagingAndSortingRepository<Region, Long> { } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/repository/freight/SettingsRepository.java<|end_filename|> package org.needle.bookingdiscount.server.repository.freight; import org.needle.bookingdiscount.domain.freight.Settings; import org.springframework.data.repository.PagingAndSortingRepository; public interface SettingsRepository extends PagingAndSortingRepository<Settings, Long> { } <|start_filename|>booking-admin/src/main/java/org/needle/bookingdiscount/admin/repository/OrderRepository.java<|end_filename|> package org.needle.bookingdiscount.admin.repository; import org.needle.bookingdiscount.domain.order.Order; import org.springframework.data.repository.PagingAndSortingRepository; public interface OrderRepository extends PagingAndSortingRepository<Order, Long> { } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/utils/DateUtils.java<|end_filename|> package org.needle.bookingdiscount.utils; import java.math.BigDecimal; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.temporal.ChronoField; import java.util.Calendar; import java.util.Date; import java.util.Locale; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.Assert; public class DateUtils { static Logger logger = LoggerFactory.getLogger(DateUtils.class); public static String format(Date date, Locale locale) { String formatDate = null; try { formatDate = formatDateTime(date, locale); } catch(Exception e) { formatDate = formatDate(date, locale); } return formatDate; } public static Date parse(String date, Locale locale) { Date parsedDate = null; try { parsedDate = parseDateTime(date, locale); } catch(Exception e) { parsedDate = parseDate(date, locale); } return parsedDate; } public static String formatDateTime(Date date, Locale locale) { String pattern = getPattern(locale); DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); return localDateTime.format(formatter); } public static Date parseDateTime(String datetime, Locale locale) { datetime = datetime.replace("T", " "); DateTimeFormatter formatter = getDateTimeFormatter(locale); LocalDateTime localDateTime = LocalDateTime.parse(datetime, formatter); Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant(); return Date.from(instant); } public static String formatDate(Date date, Locale locale) { DateTimeFormatter formatter = getDateFormatter(locale); LocalDate localDate = LocalDate.from(date.toInstant()); return localDate.format(formatter); } public static Date parseDate(String date, Locale locale) { DateTimeFormatter formatter = getDateFormatter(locale); LocalDate localDate = LocalDate.parse(date, formatter); ZonedDateTime zdt = localDate.atStartOfDay(ZoneId.systemDefault()); return Date.from(zdt.toInstant()); } public static String formatDate(Date date, String pattern) { return new SimpleDateFormat(pattern).format(date); } public static Date parseDate(String date, String pattern) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); try { return simpleDateFormat.parse(date); } catch (ParseException e) { throw new RuntimeException("parseDate [" + date + ", " + pattern + "] exception:" + e.getMessage()); } } public static DateTimeFormatter getDateTimeFormatter(Locale locale) { DateTimeFormatter formatter = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd[[ HH][:mm][:ss]]") .toFormatter(locale); return formatter; } public static DateTimeFormatter getDateFormatter(Locale locale) { DateTimeFormatter formatter = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd[['T'HH][:mm][:ss]]") .parseDefaulting(ChronoField.HOUR_OF_DAY, 0) .parseDefaulting(ChronoField.MINUTE_OF_DAY, 0) .parseDefaulting(ChronoField.SECOND_OF_DAY, 0) .parseDefaulting(ChronoField.MILLI_OF_SECOND, 0) .toFormatter(locale); return formatter; } public static String getPattern(Locale locale) { return getPattern(locale, DateFormat.MEDIUM); } public static String getPattern(Locale locale, int dateStyle) { DateFormat dateFormat = DateFormat.getDateInstance(dateStyle, locale); SimpleDateFormat simpleDateFormat = (SimpleDateFormat) dateFormat; String pattern = simpleDateFormat.toPattern(); return pattern; } public static Date getDateNext(int days) { return getDateNext(new Date(), days); } public static Date getDateNext(Date date, int days) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.DAY_OF_MONTH, days); return calendar.getTime(); } public static Date getDateNextYear(Date date, int years) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.YEAR, years); return calendar.getTime(); } public static Date getDate(Date date, int hour, int minute, int second) { Assert.notNull(date, "日期不正确"); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, minute); calendar.set(Calendar.SECOND, second); calendar.set(Calendar.MILLISECOND, 0); return calendar.getTime(); } public static boolean dateEquals(Date date1, Date date2) { date1 = getDate(date1, 0, 0, 0); date2 = getDate(date2, 0, 0, 0); return date1.equals(date2); } public static String getYear(Date date) { return formatDate(date, "yyyy"); } public static String getMonth(Date date) { return formatDate(date, "MM"); } public static String getDay(Date date) { return formatDate(date, "dd"); } public static double getHours(Date date) { Calendar c = Calendar.getInstance(); c.setTime(date); int hour = c.get(Calendar.HOUR_OF_DAY); int minute = c.get(Calendar.MINUTE); double hours = hour + ((minute) / 60.0); return new BigDecimal(hours).setScale(1, BigDecimal.ROUND_HALF_DOWN).doubleValue(); } public static long getMinuteMillis(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar.getTime().getTime(); } public static Date getLastWeekMonday() { Calendar c = Calendar.getInstance(); c.add(Calendar.DATE, -1); while(c.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) { c.add(Calendar.DATE, -1); } return c.getTime(); } public static void main(String[] args) throws Exception { String date = format(new Date(), Locale.getDefault()); System.out.println(parse(date, Locale.getDefault())); System.out.println(parseDate("2020-10-28", Locale.getDefault())); System.out.println(parseDate("2020-10-28T00:00:00", Locale.getDefault())); System.out.println(parseDateTime("2020-10-28T10:32:40", Locale.getDefault())); System.out.println(parseDateTime("2020-10-28 10:32:40", Locale.getDefault())); System.out.println(parse("2020-10-28T10:32:40", Locale.getDefault())); } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/repository/freight/FreightTemplateRepository.java<|end_filename|> package org.needle.bookingdiscount.server.repository.freight; import java.util.List; import org.needle.bookingdiscount.domain.freight.FreightTemplate; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; public interface FreightTemplateRepository extends PagingAndSortingRepository<FreightTemplate, Long> { @Query("from FreightTemplate t where t.isDelete=?1") public List<FreightTemplate> findByIsDelete(boolean isDelete); } <|start_filename|>booking-domain/src/main/java/org/needle/bookingdiscount/domain/product/GoodsSpecification.java<|end_filename|> package org.needle.bookingdiscount.domain.product; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Transient; import org.needle.bookingdiscount.domain.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper=true) @Entity @Table(name="needle_goods_specification") public class GoodsSpecification extends BaseEntity { @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="goods_id") private Goods goods; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="specification_id") private Specification specification; @Column(name="value", length=50) private String value; @Column(name="pic_url", length=200) private String picUrl; @Column(name="is_delete", columnDefinition="tinyint(1) default 0") private Boolean isDelete; @Transient private int goodsNumber; @Data public static class JsonGoodsSpecification { private Long id; private Long goods_id; private Long specification_id; private String value; private String pic_url; private Boolean is_delete; private int goods_number; public JsonGoodsSpecification(GoodsSpecification goodsSpecification) { this.id = goodsSpecification.getId(); this.goods_id = goodsSpecification.getGoods() == null ? null : goodsSpecification.getGoods().getId(); try { Specification specification = goodsSpecification.getSpecification(); if(specification != null) { this.specification_id = specification.getId(); } } catch(Exception e) {} this.value = goodsSpecification.getValue(); this.pic_url = goodsSpecification.getPicUrl(); this.is_delete = goodsSpecification.getIsDelete(); this.goods_number = goodsSpecification.getGoodsNumber(); } } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/service/PayService.java<|end_filename|> package org.needle.bookingdiscount.server.service; import java.util.List; import java.util.Optional; import org.needle.bookingdiscount.domain.member.MemberUser; import org.needle.bookingdiscount.domain.order.Order; import org.needle.bookingdiscount.domain.order.OrderGoods; import org.needle.bookingdiscount.domain.product.Goods; import org.needle.bookingdiscount.domain.product.Product; import org.needle.bookingdiscount.server.exception.ServiceException; import org.needle.bookingdiscount.server.repository.order.OrderGoodsRepository; import org.needle.bookingdiscount.server.repository.order.OrderRepository; import org.needle.bookingdiscount.server.repository.product.GoodsRepository; import org.needle.bookingdiscount.server.repository.product.ProductRepository; import org.needle.bookingdiscount.utils.DateUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult; import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest; import com.github.binarywang.wxpay.exception.WxPayException; import com.github.binarywang.wxpay.service.WxPayService; import lombok.extern.slf4j.Slf4j; @Slf4j @Service @Transactional public class PayService { @Autowired private OrderRepository orderRepository; @Autowired private OrderGoodsRepository orderGoodsRepository; @Autowired private GoodsRepository goodsRepository; @Autowired private ProductRepository productRepository; @Autowired private WxPayService wxService; public Object preWeixinPay(String appid, Long orderId, String clientIp) { Optional<Order> orderInfoOpt = orderRepository.findById(orderId); if(!orderInfoOpt.isPresent()) { throw new ServiceException(400, "订单已取消"); } Order orderInfo = orderInfoOpt.get(); List<OrderGoods> orderGoods = orderGoodsRepository.findByOrder(orderId); // 再次确认库存和价格 int checkPrice = 0; int checkStock = 0; for(OrderGoods item : orderGoods) { Product product = item.getProduct(); if(item.getNumber() > product.getGoodsNumber()) { checkStock++; } if(Math.abs(item.getRetailPrice().doubleValue() - product.getRetailPrice().doubleValue()) > 0.01) { checkPrice++; } } if(checkStock > 0) { throw new ServiceException(400, "库存不足,请重新下单"); } if (checkPrice > 0) { throw new ServiceException(400, "价格发生变化,请重新下单"); } if(orderInfo.getPayStatus() != 0) { throw new ServiceException(400, "订单已支付,请不要重复操作"); } MemberUser user = orderInfo.getUser(); String openid = user.getWeixinOpenid(); if(!StringUtils.hasText(openid)) { throw new ServiceException(400, "微信支付失败"); } WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest(); request.setAppid(appid); request.setOpenid(openid); request.setBody("【订单号】" + orderInfo.getOrderSn()); request.setOutTradeNo(orderInfo.getOrderSn()); request.setTotalFee((int) (orderInfo.getActualPrice().doubleValue() * 100)); request.setSpbillCreateIp(clientIp); request.setTradeType("JSAPI"); request.setNotifyUrl(wxService.getConfig().getNotifyUrl()); try { return wxService.createOrder(request); } catch (WxPayException e) { log.error("订单{}微信支付失败:{}", orderInfo.getOrderSn(), e.getMessage(), e); throw new ServiceException(400, "微信支付失败", e); } } public String notify(String xml) { log.info("notify(..) => weixin_pay_notify_xml={}", xml); WxPayOrderNotifyResult notifyResult; try { notifyResult = this.wxService.parseOrderNotifyResult(xml); } catch (WxPayException e) { log.error("notify(..) => 解析支付回调报文失败", e); return "FAIL"; } if(notifyResult == null) { return "FAIL"; } String orderSn = notifyResult.getOutTradeNo(); Order orderInfo = orderRepository.getByOrderSn(orderSn); if(orderInfo == null) { return "FAIL"; } log.debug("notify(..) => notify order: orderSn={}, payStatus={}, actualPrice={}", orderSn, orderInfo.getPayStatus(), orderInfo.getActualPrice()); boolean bool = orderInfo.getPayStatus() == 2 ? false : true; if(bool == true) { if(orderInfo.getOrderType() == 0) { //普通订单和秒杀订单 orderInfo.setPayStatus(2); orderInfo.setOrderStatus(300); orderInfo.setPayId(notifyResult.getTransactionId()); orderInfo.setPayTime((int) (DateUtils.parseDate(notifyResult.getTimeEnd(), "yyyyMMddHHmmss").getTime()/1000)); orderRepository.save(orderInfo); afterPay(orderInfo); } } else { return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[订单已支付]]></return_msg></xml>"; } return "<xml><return_code>SUCCESS</return_code><return_msg>OK</return_msg></xml>"; // return "SUCCESS"; } private void afterPay(Order orderInfo) { if(orderInfo.getOrderType() == 0) { List<OrderGoods> orderGoodsList = orderGoodsRepository.findByOrder(orderInfo.getId()); for(OrderGoods cartItem : orderGoodsList) { Goods goods = cartItem.getGoods(); Product product = cartItem.getProduct(); int number = cartItem.getNumber(); goodsRepository.decrement(number, goods.getId()); goodsRepository.incrementSellVolume(number, goods.getId()); productRepository.decrement(number, product.getId()); } } } } <|start_filename|>booking-admin/src/main/java/org/needle/bookingdiscount/admin/repository/GoodsGalleryRepository.java<|end_filename|> package org.needle.bookingdiscount.admin.repository; import java.util.List; import org.needle.bookingdiscount.domain.product.Goods; import org.needle.bookingdiscount.domain.product.GoodsGallery; import org.springframework.data.repository.PagingAndSortingRepository; public interface GoodsGalleryRepository extends PagingAndSortingRepository<GoodsGallery, Long> { public List<GoodsGallery> findByGoods(Goods goods); } <|start_filename|>booking-admin/src/main/java/org/needle/bookingdiscount/admin/service/MemberUserService.java<|end_filename|> package org.needle.bookingdiscount.admin.service; import org.needle.bookingdiscount.admin.repository.MemberUserRepository; import org.needle.bookingdiscount.domain.member.MemberUser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class MemberUserService { @Autowired private MemberUserRepository memberUserRepository; public MemberUser getById(Long id) { return memberUserRepository.findById(id).get(); } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/repository/cart/CartRepository.java<|end_filename|> package org.needle.bookingdiscount.server.repository.cart; import java.util.List; import org.needle.bookingdiscount.domain.cart.Cart; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; public interface CartRepository extends PagingAndSortingRepository<Cart, Long> { @Query("from Cart t where t.user.id=?1 and t.isFast=?2 and t.isDelete=?3 order by t.id desc") public List<Cart> findUserCarts(Long userId, Boolean isFast, Boolean isDelete); @Query("from Cart t where t.user.id=?1 and t.isDelete=?2 ") public List<Cart> findByUserAndIsDelete(Long userId, Boolean isDelete); @Query("from Cart t where t.user.id=?1 and t.isDelete=?2 and t.isFast=?3 ") public List<Cart> findByUserAndIsDeleteAndIsFast(Long userId, Boolean isDelete, Boolean isFast); @Query("from Cart t where t.user.id=?1 and t.product.id in (?2) and t.isDelete=false") public List<Cart> findByUserAndProductIn(Long userId, List<Long> productIds); @Query("from Cart t where t.user.id=?1 and t.checked=?2 and t.isDelete=?3 ") public List<Cart> findByUserAndCheckedAndIsDelete(Long userId, int checked, Boolean isDelete); @Query("from Cart t where t.user.id=?1 and t.checked=?2 and t.isFast=?3 and t.isDelete=?4 ") public List<Cart> findByUserAndCheckedAndIsFastAndIsDelete(Long userId, int checked, Boolean isFast, Boolean isDelete); @Query("from Cart t where t.user.id=?1 and t.product.id=?2 and t.isDelete=false") public Cart getByUserAndProduct(Long userId, Long productId); @Query("from Cart t where t.user.id=?1 and t.product.id=?2 and t.checked=?3 and t.isDelete=false") public Cart getByUserAndProductAndChecked(Long userId, Long productId, int checked); } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/data/DataPage.java<|end_filename|> package org.needle.bookingdiscount.server.data; import java.util.ArrayList; import java.util.List; import lombok.Data; @Data public class DataPage { private int count = 0; private int currentPage; private List<?> data = new ArrayList<Object>(); public DataPage(int currentPage, List<?> data) { this.count = data.size(); this.currentPage = currentPage; this.data = data; } } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/repository/product/ProductRepository.java<|end_filename|> package org.needle.bookingdiscount.server.repository.product; import java.util.List; import org.needle.bookingdiscount.domain.product.Product; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; public interface ProductRepository extends PagingAndSortingRepository<Product, Long> { @Query("from Product t where t.goods.id=?1 ") public List<Product> findByGoods(Long goodsId); @Query("from Product t where t.goodsSpecificationIds=?1 and t.isDelete=false") public List<Product> findByGoodsSpecificationIds(String goodsSpecificationIds); @Modifying @Query("update Product t set t.goodsNumber=t.goodsNumber+?1 where id=?2") public void increment(int goodsNumber, Long id); @Modifying @Query("update Product t set t.goodsNumber=t.goodsNumber-?1 where id=?2") public void decrement(int goodsNumber, Long id); } <|start_filename|>booking-server/src/main/java/org/needle/bookingdiscount/server/service/FootprintService.java<|end_filename|> package org.needle.bookingdiscount.server.service; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.needle.bookingdiscount.domain.member.Footprint; import org.needle.bookingdiscount.domain.member.Footprint.JsonFootprint; import org.needle.bookingdiscount.domain.product.Goods; import org.needle.bookingdiscount.domain.product.Goods.JsonGoods; import org.needle.bookingdiscount.server.repository.member.FootprintRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class FootprintService { @Autowired private FootprintRepository footprintRepository; public List<JsonFootprint> list(Long userId, int page, int size) { Pageable pageable = PageRequest.of(page, size); List<Footprint> footprintList = footprintRepository.findByUser(userId, pageable); List<JsonFootprint> list = new ArrayList<JsonFootprint>(); for(Footprint footprint : footprintList) { JsonFootprint item = new JsonFootprint(footprint); Goods goods = footprint.getGoods(); item.setAdd_time(new SimpleDateFormat("yyyy-MM-dd").format(new Date(footprint.getAddTime() * 1000))); item.setGoods(new JsonGoods(goods)); list.add(item); } return list; } public String delete(Long userId, Long footprintId) { footprintRepository.deleteById(footprintId); return "删除成功"; } } <|start_filename|>booking-admin/src/main/java/org/needle/bookingdiscount/BookingAdminApp.java<|end_filename|> package org.needle.bookingdiscount; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.transaction.annotation.EnableTransactionManagement; @SpringBootApplication @EnableJpaRepositories @EnableTransactionManagement @EnableAutoConfiguration public class BookingAdminApp extends SpringBootServletInitializer { protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(BookingAdminApp.class); } public static void main(String[] args) { SpringApplication.run(BookingAdminApp.class, args); } }
502627670/needle-store
<|start_filename|>fonts.css<|end_filename|> @font-face { font-family: 'Favorit-Mono'; font-weight: normal; src: url('//partners.rebelmouse.com/IEEE/FavoritMono/ABCFavoritMono-Regular.woff2') format('woff2'), url('//partners.rebelmouse.com/IEEE/FavoritMono/ABCFavoritMono-Regular.woff') format('woff'); font-display:swap; } @font-face { font-family: 'Favorit-Mono'; font-weight: 100; src: url('//partners.rebelmouse.com/IEEE/FavoritMono/ABCFavoritMono-Light.woff2') format('woff2'), url('//partners.rebelmouse.com/IEEE/FavoritMono/ABCFavoritMono-Light.woff') format('woff'); font-display:swap; } <|start_filename|>serviceworker.js<|end_filename|> 'use strict'; var CACHE_NAME = 'DirtyLittleSQL'; var urlsToCache = [ 'sql-wasm.wasm', 'separators-pre.js', 'worker.sql-wasm.js', 'serviceworker.js', 'tips.js', '3rdparty/json2csv.js', '3rdparty/chart.min.js', '3rdparty/localforage.min.js', '3rdparty/hotkeys.min.js', '3rdparty/xlsx.full.min.js', '3rdparty/codemirror/show-hint.js', '3rdparty/codemirror/sql-hint.js', '3rdparty/codemirror/sql.min.js', '3rdparty/codemirror/codemirror.js', 'gui.js', 'separators.js', 'index.html', '3rdparty/codemirror/3024-night.css', '3rdparty/codemirror/3024-day.css', '3rdparty/codemirror/show-hint.css', '3rdparty/codemirror/codemirror.css', 'fonts.css', 'demo.css', 'ABCFavoritMono-Regular.woff', 'ABCFavoritMono-Light.woff2', 'ABCFavoritMono-Light.woff', 'ABCFavoritMono-Regular.woff2', ]; self.addEventListener('install', function(event) { // Perform install steps event.waitUntil( caches.open(CACHE_NAME) .then(function(cache) { console.log('Opened cache'); return cache.addAll(urlsToCache); }) ); }); self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request) .then(function(response) { // Cache hit - return response if (response) { return response; } return fetch(event.request); } ) ); }); <|start_filename|>separators-pre.js<|end_filename|> // To compile run: // npm install browserify // npm install json2csv // browserify separators-pre.js > separators.js // This will create a bundle that includes cvs2json. // const suffixToSep = new Map([ ["csv", ","], ["tsv", "\t"], ["psv", "|"], ["ssv", ";"], ]); var enc = new TextEncoder(); // always utf-8 var dec = new TextDecoder(); // always utf-8 let toHex = x => x.toString(16).padStart(2,'0') function getPossibleSeps(seps) { // Guess the separator as the char that occurs a consistent number of times // in each line. let s = []; for (const [k, v] of seps) { let max = Math.max(...v); if (!max) continue let min = Math.min(...v); if (min == max) { s.push(k); } } return s; } // Returns the guessed separator as a decimal integer, e.g. '\t' as 9. // Returns -1 if we can't figure out the separator used in the file. function guessSeparatorFromData(d) { // Number of lines to use for guessing is the number of newlines, to a max of 10 let ltc = Math.min(d.filter(x => x === 0x0a).length, 10); let seps = new Map(); suffixToSep.forEach((x,y,z) => seps.set(enc.encode(x)[0], new Array(ltc).fill(0))); let cl = 0; // line count let skip = false; // Count the appearances of each separator in each line. for (let i = 0; i < d.byteLength; i++) { // Ignore anything inside double quotes if (d[i] == 0x22) { skip = !skip; } if (skip) { continue; } // Check for newline (\n) if (d[i] == 0x0a) { cl++; if (cl == ltc) break; continue; } if (seps.has(d[i])) { let cv = seps.get(d[i]); cv[cl]++ seps.set(d[i], cv); } } let s = getPossibleSeps(seps); if (s.length != 1) return -1; return s[0]; } // Take all the sheets in a workbook and return them as an // array of [csvdata, tablename] function convertExcelToCSV(d, filename) { var data = new Uint8Array(d); var wb = XLSX.read(data,{type:'array'}); let sheets = []; for (let i = 0, l = wb.SheetNames.length; i < l; i += 1) { let s = wb.Sheets[wb.SheetNames[i]]; var csv = XLSX.utils.sheet_to_csv(s, { type:'array', header: 1 }); sheets.push([enc.encode(csv), filename + wb.SheetNames[i]]); } return sheets; } // Take all the sheets in a workbook and return them as an // array of [csvdata, tablename] function convertJSONToCSV(d) { const { Parser } = require('json2csv'); const opts = { flatten: true, flattenSeparator: '__' }; const parser = new Parser(opts); const csv = parser.parse(JSON.parse(dec.decode(d))); return csv; } function guessSeparator(filename, data) { let suff = filename.slice(-3); if (suffixToSep.has(suff)) { return [toHex(enc.encode(suffixToSep.get(suff))[0]), suffixToSep.get(suff)]; } // Use the first 10,000 bytes for guessing. let d = new Uint8Array(data.slice(0,10000)); let s = guessSeparatorFromData(d); // Special case decoding tab to '\t'. let h = toHex(s); if (s == 9) { s = '\t'; } else { s = dec.decode(new Uint8Array([s])); } return [h, s]; } global.getDataAndSeparator = function (d, filename) { // Handle spreadsheets. if ([".xls", ".xlsx", ".ods"].some(e => filename.endsWith(e))) { let dt = convertExcelToCSV(d, filename); let header = hasHeader(dt, ','); return [convertExcelToCSV(d, filename), '2c', header]; } // Handle JSON if ([".json", ".js"].some(e => filename.endsWith(e))) { let dt = convertJSONToCSV(d); let header = hasHeader(dt, ','); let r = enc.encode(dt); return [[[r, filename]], '2c', header]; } let [sep, sepAsText] = guessSeparator(filename, d); let i = indexToFirstLine(d, sepAsText); d = d.slice(i); let header = hasHeader(d, sepAsText); return [[[d, filename]], sep, header]; } function indexToFirstLine(data, sep) { let d = new Uint8Array(data.slice(0,10000)); let indexOfFirstSep = d.indexOf(enc.encode(sep)[0]); let lineBreak = d.indexOf(0x0a); // Line break occurs after the first instance of the separator, so there // are no leading lines. if (lineBreak > indexOfFirstSep) { return 0; } // Search for the first line break before the first occurence // of our separator. let prevLineBreak = 0; while (lineBreak < indexOfFirstSep) { prevLineBreak = lineBreak + 1; lineBreak = d.indexOf(0x0a, lineBreak + 1); // Just in case there's no line break at all. if (lineBreak < 0) { return 0; } } return prevLineBreak; } function hasHeader(data, s) { let d = new Uint8Array(data.slice(0,10000)); d = new Uint8Array(d.slice(0,d.indexOf(0x0a))); let st = dec.decode(d); let a = st.split(s); let u = [...new Set(a)]; // Duplicate values in the header line suggest it is not a header. if (u.length != a.length) { return false; } // More than one non-alphanumeric field suggests not a header. var an = new RegExp("[^0-9\-\.]\+"); let nums = a.filter(x => an.test(x) == false).length; if (nums > 1) { return false; } return true; } function testGuessSeparatorFromData() { let d = enc.encode("a,b,c\n1,2,3\n4,5,6"); let result = toHex(guessSeparatorFromData(d)); console.log((result == '2c' ? 'Pass. ' : 'FAIL. ') + 'Detect CSV ' + '. Actual result:', result); d = enc.encode("a\tb\tc\n1\t2\t3\n4\t5\t6"); result = toHex(guessSeparatorFromData(d)); console.log((result == '09' ? 'Pass. ' : 'FAIL. ') + 'Detect TSV ' + '. Actual result:', result); d = enc.encode("a|b|c\n1|2|3\n2|3|4"); result = toHex(guessSeparatorFromData(d)); console.log((result == '7c' ? 'Pass. ' : 'FAIL. ') + 'Detect pipe ' + '. Actual result:', result); d = enc.encode("a,\"b,e\",c\n1,2,3\n4,5,6"); result = toHex(guessSeparatorFromData(d)); console.log((result == '2c' ? 'Pass. ' : 'FAIL. ') + 'Detect CSV with double quotes in header ' + '. Actual result:', result); } function testHeaderDetection() { let d = enc.encode("a,b,c\n1,2,3\n4,5,6"); let result = hasHeader(d,','); console.log((result == true ? 'Pass. ' : 'FAIL. ') + 'Detect header ' + '. Actual result:', result); d = enc.encode("a,b,b\n1,2,3\n4,5,6"); result = hasHeader(d,','); console.log((result == false ? 'Pass. ' : 'FAIL. ') + 'Detect duplicate items in header ' + '. Actual result:', result); d = enc.encode("a,1,2\n1,2,3\n4,5,6"); result = hasHeader(d,','); console.log((result == false ? 'Pass. ' : 'FAIL. ') + 'Detect numbers header ' + '. Actual result:', result); d = enc.encode("a,b,c\n1,2,3\n4,5,6"); result = hasHeader(d,','); console.log((result == true ? 'Pass. ' : 'FAIL. ') + 'Detect numbers header ' + '. Actual result:', result); d = enc.encode("a,b1,c2\n1,2,3\n4,5,6"); result = hasHeader(d,','); console.log((result == true ? 'Pass. ' : 'FAIL. ') + 'Detect numbers header ' + '. Actual result:', result); d = enc.encode("2021-02-01,2021-02-01,c\n1,2,3\n4,5,6"); result = hasHeader(d,','); console.log((result == fail ? 'Pass. ' : 'FAIL. ') + 'Detect numbers header ' + '. Actual result:', result); }
mwenge/dls
<|start_filename|>src/Web/WebDrapo/Model/KeyValueVO.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebDrapo.Model { public class KeyValueVO { public string Key { set; get; } public string Value { set; get; } public List<KeyValueVO> Children { set; get; } public bool Visible { set; get; } public string Selection { set; get; } public KeyValueVO() { this.Visible = true; this.Children = new List<KeyValueVO>(); } } } <|start_filename|>src/Middleware/Drapo/DrapoDynamic.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; namespace Sysphera.Middleware.Drapo { public class DrapoDynamic { private string _eTag; private string _lastModified; private string _contentType; private string _contentData; private int _status; public string ETag { get => _eTag; set => _eTag = value; } public string LastModified { get => _lastModified; set => _lastModified = value; } public string ContentType { get => _contentType; set => _contentType = value; } public string ContentData { get => _contentData; set => _contentData = value; } public int Status { get => _status; set => _status = value; } public Dictionary<string, string> Headers { set; get; } public DrapoDynamic() { this._status = 200; } } } <|start_filename|>src/Web/WebDrapo/Dockerfile.json<|end_filename|> FROM microsoft/aspnetcore:2.0.0 ARG source=. WORKDIR /app EXPOSE 9901 COPY ${source:-obj/Docker/publish} . ENTRYPOINT ["dotnet", "PowerPlanning.Gateway.Web.WebGateway.dll"] <|start_filename|>src/Middleware/Drapo/Request/DrapoRequestReader.cs<|end_filename|> using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; namespace Sysphera.Middleware.Drapo.Request { public class DrapoRequestReader : IDrapoRequestReader { private DrapoMiddlewareOptions _options; private IHttpContextAccessor _context; private string _connectionId = null; private string _domain = null; public DrapoRequestReader(DrapoMiddlewareOptions options, IHttpContextAccessor context) { this._options = options; this._context = context; } public string Get(string key) { if(!this._context.HttpContext.Request.Headers.TryGetValue(key, out StringValues values)) return (null); return (values.ToString()); } public string GetPipeHeaderConnectionId() { if (this._connectionId == null) this._connectionId = this.Get(this._options.Config.PipeHeaderConnectionId); return (this._connectionId); } public void SetPipeHeaderConnectionId(string connectionId) { this._connectionId = connectionId; } public string GetDomain() { if (this._domain != null) return (this._domain); string domainRegex = this._options.Config.DomainRegex; if (string.IsNullOrEmpty(domainRegex)) return (string.Empty); string host = this._context.HttpContext.Request.Host.Host; if (string.IsNullOrEmpty(host)) return (string.Empty); Match match = Regex.Match(host, domainRegex); if (match == null) return (string.Empty); string domain = match.Groups[this._options.Config.DomainGroup].Value; if (string.IsNullOrEmpty(domain)) return (string.Empty); return (domain); } public void SetDomain(string domain) { this._domain = domain; } } } <|start_filename|>src/Middleware/Drapo/Pipe/DrapoConnectionManagerRedis.cs<|end_filename|> using Newtonsoft.Json; using StackExchange.Redis; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Sysphera.Middleware.Drapo.Pipe { public class DrapoConnectionManagerRedis : IDrapoConnectionManager { private readonly ConnectionMultiplexer _connection = null; public DrapoConnectionManagerRedis(DrapoMiddlewareOptions options) { _connection = ConnectionMultiplexer.Connect(options.BackplaneRedis); Check(); } private string CreateDomainKey(string domain) { return ($"drapo_connection_{domain}"); } private string CreateConnectionKey(string domain, string connectionId) { return ($"drapo_connection_{domain}_{connectionId}"); } public void Create(string domain, string connectionId, string containerId) { IDatabase database = _connection.GetDatabase(); DrapoConnection connection = new DrapoConnection(connectionId, domain, containerId); database.StringSet(this.CreateConnectionKey(domain, connectionId), Serialize(connection)); } public bool Remove(string domain, string connectionId) { IDatabase database = _connection.GetDatabase(); return (database.KeyDelete(this.CreateConnectionKey(domain, connectionId))); } public long Count(string domain) { return (this.GetAll(domain).Count); } public DrapoConnection Get(string domain, string connectionId) { IDatabase database = _connection.GetDatabase(); return (Get<DrapoConnection>(database, this.CreateConnectionKey(domain, connectionId))); } public bool Identify(string domain, string connectionId, long identity) { IDatabase database = _connection.GetDatabase(); DrapoConnection connection = Get<DrapoConnection>(database, this.CreateConnectionKey(domain, connectionId)); if (connection == null) return (false); connection.Identity = identity; database.StringSet(this.CreateConnectionKey(domain, connectionId), Serialize(connection)); return (true); } public List<DrapoConnection> GetAll(string domain) { List<DrapoConnection> connections = new List<DrapoConnection>(); IDatabase database = _connection.GetDatabase(); foreach (string key in GetKeysByPattern(this.CreateDomainKey(domain) + "*")) { DrapoConnection connection = Get<DrapoConnection>(database, key); if (connection != null) connections.Add(connection); } return (connections); } public bool Check() { bool updated = false; Dictionary<string, bool> containers = new Dictionary<string, bool>(); IDatabase database = _connection.GetDatabase(); foreach (string key in GetKeysByPattern(this.CreateDomainKey(string.Empty) + "*")) { DrapoConnection connection = Get<DrapoConnection>(database, key); if (connection == null) continue; if (string.IsNullOrEmpty(connection.ContainerId)) continue; if (!containers.ContainsKey(connection.ContainerId)) containers.Add(connection.ContainerId, IsContainerConnected(database, connection.ContainerId)); if (containers[connection.ContainerId]) continue; if (database.KeyDelete(key)) updated = true; } return (updated); } private bool IsContainerConnected(IDatabase database, string containerId) { List<string> keys = new List<string>(); foreach (System.Net.EndPoint endPoint in _connection.GetEndPoints()) { IServer server = _connection.GetServer(endPoint); RedisChannel[] channels = server.SubscriptionChannels("*" + containerId + "*"); if ((channels != null) && (channels.Length > 0)) return (true); } return (false); } private List<string> GetKeysByPattern(string pattern) { List<string> keys = new List<string>(); IDatabase database = _connection.GetDatabase(); foreach (System.Net.EndPoint endPoint in _connection.GetEndPoints()) { IServer server = _connection.GetServer(endPoint); foreach (RedisKey redisKey in server.Keys(database.Database, pattern)) { keys.Add(redisKey); } } return (keys); } private T Get<T>(IDatabase database, string key) { string data = database.StringGet(key); if (data is null) return (default(T)); return (Deserialize<T>(data)); } private string Serialize(object data) { return (JsonConvert.SerializeObject(data)); } private T Deserialize<T>(string data) { return (JsonConvert.DeserializeObject<T>(data)); } } } <|start_filename|>src/Middleware/Drapo/js/DrapoLinkedCubeNode.js<|end_filename|> "use strict"; var DrapoLinkedCubeNode = (function () { function DrapoLinkedCubeNode() { this.Value = null; this.Context = null; this.Next = null; } return DrapoLinkedCubeNode; }()); <|start_filename|>src/Middleware/Drapo/DrapoWindow.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; namespace Sysphera.Middleware.Drapo { public class DrapoWindow { public string Name { set; get; } public string Path { set; get; } public string Did { set; get; } public Dictionary<string,string> Parameters { set; get; } public DrapoWindow() { this.Parameters = new Dictionary<string, string>(); } } } <|start_filename|>src/Web/WebDrapo/wwwroot/DrapoPages/ControlFlowForDataField.html<|end_filename|> <!DOCTYPE html> <html> <head> <script src="/drapo.js"></script> <title>Control Flow - Data Field</title> </head> <body> <span>Control Flow - Data Field</span> <div d-dataKey="user" d-dataUrlGet="/Object/GetChildProperties"></div> <div d-for="property in user.Child.Properties"> <br> <span>Key: {{property.Key}}</span><br> <span>Value: {{property.Value}}</span><br> </div> </body> </html> <|start_filename|>src/Middleware/Drapo/Pipe/DrapoPipeMessageType.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; namespace Sysphera.Middleware.Drapo.Pipe { public enum DrapoPipeMessageType { Register = 0, Storage = 1, Execute = 2 } } <|start_filename|>src/Test/WebDrapo.Test/Pages/ControlFlowForRecursiveIndex.Test.html<|end_filename|> <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> <script src="/drapo.js"></script> <title>Control Flow - For - Index</title> </head> <body> <span>Control Flow - For - Index</span> <div d-datakey="users" d-dataurlget="/Data/GetLevels?Levels=3&amp;Children=2"></div> <div d-for="user in users" style="display: none;"> <br /> <span>Key: {{user.Key}}</span><br /> <span>Value: {{user.Value}}</span><br /> <span>Index: {{user._Index}}</span><br /> <span>Children</span> <br /> <div d-for="user in user.Children"></div> </div><div> <br /> <span>Key: L3K0</span><br /> <span>Value: L3V0</span><br /> <span>Index: 0</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L2K0</span><br /> <span>Value: L2V0</span><br /> <span>Index: 1</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L1K0</span><br /> <span>Value: L1V0</span><br /> <span>Index: 2</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index: 3</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index: 4</span><br /> <span>Children</span> <br /> </div> </div><div> <br /> <span>Key: L1K1</span><br /> <span>Value: L1V1</span><br /> <span>Index: 5</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index: 6</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index: 7</span><br /> <span>Children</span> <br /> </div> </div> </div><div> <br /> <span>Key: L2K1</span><br /> <span>Value: L2V1</span><br /> <span>Index: 8</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L1K0</span><br /> <span>Value: L1V0</span><br /> <span>Index: 9</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index: 10</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index: 11</span><br /> <span>Children</span> <br /> </div> </div><div> <br /> <span>Key: L1K1</span><br /> <span>Value: L1V1</span><br /> <span>Index: 12</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index: 13</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index: 14</span><br /> <span>Children</span> <br /> </div> </div> </div> </div><div> <br /> <span>Key: L3K1</span><br /> <span>Value: L3V1</span><br /> <span>Index: 15</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L2K0</span><br /> <span>Value: L2V0</span><br /> <span>Index: 16</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L1K0</span><br /> <span>Value: L1V0</span><br /> <span>Index: 17</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index: 18</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index: 19</span><br /> <span>Children</span> <br /> </div> </div><div> <br /> <span>Key: L1K1</span><br /> <span>Value: L1V1</span><br /> <span>Index: 20</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index: 21</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index: 22</span><br /> <span>Children</span> <br /> </div> </div> </div><div> <br /> <span>Key: L2K1</span><br /> <span>Value: L2V1</span><br /> <span>Index: 23</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L1K0</span><br /> <span>Value: L1V0</span><br /> <span>Index: 24</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index: 25</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index: 26</span><br /> <span>Children</span> <br /> </div> </div><div> <br /> <span>Key: L1K1</span><br /> <span>Value: L1V1</span><br /> <span>Index: 27</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index: 28</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index: 29</span><br /> <span>Children</span> <br /> </div> </div> </div> </div> </body></html> <|start_filename|>src/Middleware/Drapo/DrapoDynamicRequest.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; namespace Sysphera.Middleware.Drapo { public class DrapoDynamicRequest { public string Code { set; get; } public string Context { set; get; } public string Path { set; get; } public string PathBase { set; get; } } } <|start_filename|>src/Web/WebDrapo/Controllers/AuthenticationController.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using WebDrapo.Model; using System.Security.Claims; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication; // For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace WebDrapo.Controllers { [AllowAnonymous] public class AuthenticationController : Controller { [HttpPost] public async Task<ActionResult> Login([FromBody] KeyValueVO identity) { if ((identity.Key != "admin") || (identity.Value != "password")) return (Ok("Error")); List<Claim> claims = new List<Claim>(); claims.Add(new Claim("userLogin", identity.Key)); claims.Add(new Claim("domain", "domain")); ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, "local", "userlogin", "domain"); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity)); return (Ok("Ok")); } [HttpPost] public async Task<ActionResult> Logout([FromBody] string token) { if (token != "Ok") return (Ok("Error")); await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return (Ok("Ok")); } } } <|start_filename|>src/Test/WebDrapo.Test/Pages/ObjectList.Test.html<|end_filename|> <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> <script src="/drapo.js"></script> <title>Drapo Object List</title> </head> <body> <h1><span>Drapo Object List</span></h1> <div d-datakey="objects" d-dataurlget="~/Object/GetReports"></div> <ul> <li d-for="object in objects" style="display: none;">{{object.Code}} - {{object.Name}}</li><li> - </li><li>1 - Report1</li><li>2 - Report2</li><li>3 - Report3</li> </ul> </body></html> <|start_filename|>src/Test/WebDrapo.Test/Pages/ComponentContent.Test.html<|end_filename|> <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> <script src="/drapo.js"></script> <title>Component Content</title> <link href="" rel="stylesheet" /><script src=""></script></head> <body> <div> <span>Component Content</span> <div class="code"> <pre> &lt;div d-datakey="source" d-datatype="object" d-dataproperty-levels="2" d-dataproperty-children="5"&gt;&lt;/div&gt; &lt;div class="state" dc-levels="{{source.levels}}" dc-children="{{source.children}}"&gt; &lt;div d-datakey="internal" d-datatype="parent" d-dataloadtype="reference" d-datavalue="dc-"&gt;&lt;/div&gt; &lt;div d-datakey="data" d-dataurlget="/Data/GetLevels?levels={{internal.levels}}&amp;amp;children={{internal.children}}"&gt;&lt;/div&gt; &lt;div d-for="item in data"&gt; &lt;br&gt; &lt;span&gt;Key: {{item.Key}}&lt;/span&gt;&lt;br&gt; &lt;span&gt;Value: {{item.Value}}&lt;/span&gt;&lt;br&gt; &lt;/div&gt; &lt;/div&gt; </pre> </div> </div> </body></html> <|start_filename|>src/Middleware/Drapo/js/DrapoLinkedList.js<|end_filename|> "use strict"; var DrapoLinkedList = (function () { function DrapoLinkedList() { this._head = null; } DrapoLinkedList.prototype.AddOrUpdate = function (index, value) { if (this._head === null) { this._head = new DrapoLinkedListNode(); this._head.Index = index; } var node = this._head; var isEnd = false; while (node.Index !== index) { if ((isEnd = (node.Next === null)) || (node.Next.Index > index)) { var nodeNew = new DrapoLinkedListNode(); nodeNew.Index = index; if ((isEnd) && (node.Index < index)) { node.Next = nodeNew; } else if (node === this._head) { nodeNew.Next = node; this._head = nodeNew; } else { nodeNew.Next = node.Next; node.Next = nodeNew; } node = nodeNew; } else { node = node.Next; } } node.Value = value; }; DrapoLinkedList.prototype.Get = function (index) { var node = this._head; while (node !== null) { if (node.Index < index) node = node.Next; else if (node.Index === index) return (node.Value); } return (null); }; DrapoLinkedList.prototype.GetHead = function () { return (this._head); }; return DrapoLinkedList; }()); <|start_filename|>src/Web/WebDrapo/wwwroot/components/linkedcube/linkedcube.css<|end_filename|> .linkedCube { } .linkedCube > div { position: relative; } .linkedCube > div > span { position:relative; } <|start_filename|>src/Web/WebDrapo/Controllers/MixedController.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; namespace WebDrapo.Controllers { [AllowAnonymous] public class MixedController : Controller { public IActionResult Index() { return PartialView(); } } } <|start_filename|>src/Middleware/Drapo/DrapoResourceType.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; namespace Sysphera.Middleware.Drapo { public enum DrapoResourceType { Embedded, Url } } <|start_filename|>src/Web/WebDrapo/Model/DataVM.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebDrapo.Model { public class DataVM { public int? Code { set; get; } public string Name { set; get; } } } <|start_filename|>src/Middleware/Drapo/DrapoComponentFile.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; namespace Sysphera.Middleware.Drapo { public class DrapoComponentFile { public string Name { set; get; } public DrapoResourceType ResourceType { set; get; } public DrapoFileType Type { set; get; } public string Path { set; get; } } } <|start_filename|>src/Test/WebDrapo.Test/Pages/FormatTimespan.Test.html<|end_filename|> <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> <script src="/drapo.js"></script> <title>Format TimeSpan</title> </head> <body> <br /> <span>Format TimeSpan</span> <div d-datakey="dates" d-dataurlget="~/Data/GetDatesCompare"></div> <div d-for="date in dates" style="display: none;"> <br /> <span d-model="{{date.start}}" d-format="G"></span> <span d-model="{{date.end}}" d-format="G"></span> <span d-model="Cast({{date.end}} - {{date.start}},number)" d-format="t"></span> </div><div> <br /> <span>06/03/1980 00:00:00</span> <span>06/03/1980 00:00:00</span> <span>50ms</span> </div><div> <br /> <span>06/03/1980 00:00:00</span> <span>06/03/1980 00:00:25</span> <span>25s</span> </div><div> <br /> <span>06/03/1980 00:00:00</span> <span>06/03/1980 00:03:00</span> <span>3m</span> </div><div> <br /> <span>06/03/1980 00:00:00</span> <span>06/03/1980 02:00:00</span> <span>2h</span> </div><div> <br /> <span>06/03/1980 00:00:00</span> <span>06/04/1980 00:00:00</span> <span>24h</span> </div><div> <br /> <span>06/03/1980 00:00:00</span> <span></span> <span></span> </div><div> <br /> <span>06/03/1980 00:00:00</span> <span>06/03/1980 00:02:30</span> <span>2m30s</span> </div><div> <br /> <span>06/03/1980 00:00:00</span> <span>06/03/1980 04:01:22</span> <span>4h1m22s</span> </div> </body></html> <|start_filename|>src/Middleware/Drapo/DrapoConverter.cs<|end_filename|> using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace Sysphera.Middleware.Drapo { public class DrapoConverter { public static T DeserializeObject<T>(string value) { if (IsUnicodeHexadecimal(value)) value = ConvertUnicodeHexadecimalToUnicode(value); return (JsonConvert.DeserializeObject<T>(value)); } private static bool IsUnicodeHexadecimal(string value) { if (string.IsNullOrEmpty(value)) return (false); return(value.StartsWith("\\u")); } private static string ConvertUnicodeHexadecimalToUnicode(string value) { StringBuilder builder = new StringBuilder(); string[] values = value.Split("\\u"); foreach (string valueConvert in values) { if (string.IsNullOrEmpty(valueConvert)) continue; builder.Append((char)Convert.ToInt64(valueConvert, valueConvert.Length == 2 ? 16 : 32)); } return (builder.ToString()); } } } <|start_filename|>src/Web/WebDrapo/Model/ObjectVM.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebDrapo.Model { public class ObjectVM { public int Code { set; get; } public int? Previous { set; get; } public int? Next { set; get; } public string Name { set; get; } public string Description { set; get; } public decimal Value { set; get; } public DateTime Date { set; get; } } } <|start_filename|>src/Web/WebDrapo/wwwroot/components/labelinputsubscribemustache/labelInputsubscribemustache.js<|end_filename|> function labelinputsubscribemustacheConstructor(el, app) { let elj = $(el); let input = elj.children().last()[0]; let dataKey = elj.attr("d-dataKeySource"); app._observer.SubscribeComponent(dataKey, el, labelinputsubscribeNotify, input); input.addEventListener('change', function (evt) { labelinputsubscribeChange(evt, el, app); }, false); return(labelinputsubscribeNotify(el, app)); } function labelinputsubscribeNotify(el, app) { let elj = $(el); let sector = app._document.GetSector(el); let data = elj.attr("d-dataKeySource"); var mustachePartes = app._parser.ParseMustache(data); var dataKey = mustachePartes[0]; var dataField = mustachePartes[1]; let caption = elj.attr("d-caption"); let label = $(el).children().first(); let input = $(el).children().last(); label.html(caption); let promise = app._storage.RetrieveData(dataKey, sector).then(function (dataItem) { let value = (dataItem !== null) ? dataItem[dataField] : ''; input.html(value); }); return (promise); } function labelinputsubscribeChange(evt, el, app) { let elj = $(el); var target = evt.target; let sector = app._document.GetSector(elj); let data = elj.attr("d-dataKeySource"); var dataPath = app._parser.ParseMustache(data); app._storage.UpdateDataPath(sector, null, dataPath, target.value); } <|start_filename|>src/Test/WebDrapo.Test/Pages/ControlFlowForDataField.Test.html<|end_filename|> <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> <script src="/drapo.js"></script> <title>Control Flow - Data Field</title> </head> <body> <span>Control Flow - Data Field</span> <div d-datakey="user" d-dataurlget="/Object/GetChildProperties"></div> <div d-for="property in user.Child.Properties" style="display: none;"> <br /> <span>Key: {{property.Key}}</span><br /> <span>Value: {{property.Value}}</span><br /> </div><div> <br /> <span>Key: k1</span><br /> <span>Value: v1</span><br /> </div><div> <br /> <span>Key: k2</span><br /> <span>Value: v2</span><br /> </div><div> <br /> <span>Key: k3</span><br /> <span>Value: v3</span><br /> </div> </body></html> <|start_filename|>src/Web/WebDrapo/Controllers/MenuController.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using WebDrapo.Model; using Microsoft.AspNetCore.Authorization; // For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace WebDrapo.Controllers { [AllowAnonymous] public class MenuController : Controller { [HttpGet] public List<MenuItemVM> GetItems() { List<MenuItemVM> items = new List<MenuItemVM>(); items.Add(new MenuItemVM() { Name = "Home", Type = "Home", TypeImageClass= "glyphicon glyphicon-home", Action= "UncheckItemField({{menuState.visibleMenu}});UncheckItemField({{menuState.visibleSubMenu}});UpdateSector(sector,/DrapoPages/PageSimple.html)" }); items.Add(new MenuItemVM() { Name = "New", Type = "New", TypeImageClass= "glyphicon glyphicon-file", Action = "UncheckItemField({{menuState.visibleSubMenu}});UpdateDataUrl(d-menuSubItems, /Menu/GetSubItemsNew);ClearSector(sectorSubMenu);CheckItemField({{menuState.visibleSubMenu}});UpdateSector(sectorSubMenu,/DrapoPages/SectorSubMenuIcons.html)" }); items.Add(new MenuItemVM() { Name = "Explorer", Type = "Explorer", TypeImageClass= "glyphicon glyphicon-search", Action = "UncheckItemField({{menuState.visibleSubMenu}});UpdateDataUrl(d-menuSubItems, /Menu/GetSubItemsExplorer);ClearSector(sectorSubMenu);CheckItemField({{menuState.visibleSubMenu}});UpdateSector(sectorSubMenu,/DrapoPages/SectorSubMenuList.html)" }); return (items); } [HttpGet] public List<MenuItemVM> GetSubItemsNew() { List<MenuItemVM> subItems = new List<MenuItemVM>(); subItems.Add(new MenuItemVM() { Name = "Home", TypeImageClass = "glyphicon glyphicon-home", Action = "UncheckItemField({{menuState.visibleMenu}});UncheckItemField({{menuState.visibleSubMenu}});UncheckDataField(d-menuTabs,Selected,false);CheckItemField({{subMenuItem.Selected}},false);AddDataItem(d-menuTabs,subMenuItem);UpdateSector(sector,{{subMenuItem.Url}})", Url= "/DrapoPages/ControlFlowForUl.html" , Activated= "UncheckDataField(d-menuTabs,Selected,false);CheckItemField({{tab.Selected}});UpdateSector(sector,{{tab.Url}})" }); return (subItems); } [HttpGet] public List<MenuItemVM> GetSubItemsExplorer() { List<MenuItemVM> subItems = new List<MenuItemVM>(); subItems.Add(new MenuItemVM() { Name = "Explorer", TypeImageClass = "glyphicon glyphicon-search", Action = "UncheckItemField({{menuState.visibleMenu}});UncheckItemField({{menuState.visibleSubMenu}});UncheckDataField(d-menuTabs,Selected,false);CheckItemField({{subMenuItem.Selected}},false);AddDataItem(d-menuTabs,subMenuItem);UpdateSector(sector,{{subMenuItem.Url}})", Url = "/DrapoPages/ControlFlowForSelect.html", Activated = "UncheckDataField(d-menuTabs,Selected,false);CheckItemField({{tab.Selected}});UpdateSector(sector,{{tab.Url}})" }); return (subItems); } } } <|start_filename|>src/Web/WebDrapo/Views/Shared/Layout.cshtml<|end_filename|> <!DOCTYPE html> <html> <head> <script src="/drapo.js"></script> <link href="/css/bootstrap.min.css" rel="stylesheet" /> <title>@ViewBag.Title</title> </head> <body> @RenderBody() <script src="/js/bootstrap.min.js"></script> </body> </html> <|start_filename|>src/Web/WebDrapo/Controllers/AuthorizationController.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using System.Security.Claims; using WebDrapo.Model; // For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace WebDrapo.Controllers { public class AuthorizationController : Controller { [HttpGet] public Dictionary<string, string> GetUserName() { Dictionary<string, string> values = new Dictionary<string, string>(); List<Claim> claims = new List<Claim>(HttpContext.User.Claims); foreach (Claim claim in claims) if (!values.ContainsKey(claim.Type)) values.Add(claim.Type, claim.Value); return (values); } } } <|start_filename|>src/Web/WebDrapo/wwwroot/DrapoPages/ControlFlowForNested.html<|end_filename|> <!DOCTYPE html> <html> <head> <script src="/drapo.js"></script> <title>Control Flow - For</title> </head> <body> <span>Control Flow - For</span> <div d-dataKey="users" d-dataUrlGet="/Data/GetLevels?Levels=1"></div> <div d-for="user in users"> <br> <span>Key: {{user.Key}}</span><br> <span>Value: {{user.Value}}</span><br> <span>Children</span> <br> <div d-for="child in user.Children"> <span>Child Key: {{child.Key}}</span><br> <span>Child Value: {{child.Value}}</span><br> </div> </div> </body> </html> <|start_filename|>src/Middleware/Drapo/js/DrapoRenderContext.js<|end_filename|> "use strict"; var DrapoRenderContext = (function () { function DrapoRenderContext() { this._sectorExpressionContexts = {}; this._dataKeyElements = {}; } DrapoRenderContext.prototype.GetKey = function (sector, expression) { return (sector + '_' + expression); }; DrapoRenderContext.prototype.HasExpressionContext = function (sector, expression) { var key = this.GetKey(sector, expression); var value = this._sectorExpressionContexts[key]; if (value == null) return (null); return value; }; DrapoRenderContext.prototype.AddExpressionContext = function (sector, expression, hasContext) { var key = this.GetKey(sector, expression); this._sectorExpressionContexts[key] = hasContext; }; DrapoRenderContext.prototype.HasDataKeyElement = function (dataKey) { var value = this._dataKeyElements[dataKey]; if (value == null) return (null); return value; }; DrapoRenderContext.prototype.AddDataKeyElement = function (dataKey, hasElement) { this._dataKeyElements[dataKey] = hasElement; }; return DrapoRenderContext; }()); <|start_filename|>src/Web/WebDrapo/Controllers/DataUpdateController.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using WebDrapo.Model; using Microsoft.AspNetCore.Authorization; namespace WebDrapo.Controllers { [AllowAnonymous] public class DataUpdateController : Controller { private static List<DataVM> _data = CreateData(); public IActionResult Index() { return View(); } private static List<DataVM> CreateData() { List<DataVM> data = new List<DataVM>(); data.Add(new DataVM() { Code = 1, Name = "Dev1" }); data.Add(new DataVM() { Code = 2, Name = "Dev2" }); data.Add(new DataVM() { Code = 3, Name = "Dev3" }); return (data); } [HttpGet] public List<DataVM> Get() { return (_data); } [HttpPost] public List<DataVM> Set([FromBody] List<DataVM> inserted, [FromBody] List<DataVM> updated, [FromBody] List<DataVM> deleted) { return (_data); } } } <|start_filename|>src/Test/WebDrapo.Test/Pages/ControlFlowForNested.Test.html<|end_filename|> <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> <script src="/drapo.js"></script> <title>Control Flow - For</title> </head> <body> <span>Control Flow - For</span> <div d-datakey="users" d-dataurlget="/Data/GetLevels?Levels=1"></div> <div d-for="user in users" style="display: none;"> <br /> <span>Key: {{user.Key}}</span><br /> <span>Value: {{user.Value}}</span><br /> <span>Children</span> <br /> <div d-for="child in user.Children"> <span>Child Key: {{child.Key}}</span><br /> <span>Child Value: {{child.Value}}</span><br /> </div> </div><div> <br /> <span>Key: L1K0</span><br /> <span>Value: L1V0</span><br /> <span>Children</span> <br /> <div> <span>Child Key: L0K0</span><br /> <span>Child Value: L0V0</span><br /> </div><div> <span>Child Key: L0K1</span><br /> <span>Child Value: L0V1</span><br /> </div><div> <span>Child Key: L0K2</span><br /> <span>Child Value: L0V2</span><br /> </div><div> <span>Child Key: L0K3</span><br /> <span>Child Value: L0V3</span><br /> </div><div> <span>Child Key: L0K4</span><br /> <span>Child Value: L0V4</span><br /> </div> </div><div> <br /> <span>Key: L1K1</span><br /> <span>Value: L1V1</span><br /> <span>Children</span> <br /> <div> <span>Child Key: L0K0</span><br /> <span>Child Value: L0V0</span><br /> </div><div> <span>Child Key: L0K1</span><br /> <span>Child Value: L0V1</span><br /> </div><div> <span>Child Key: L0K2</span><br /> <span>Child Value: L0V2</span><br /> </div><div> <span>Child Key: L0K3</span><br /> <span>Child Value: L0V3</span><br /> </div><div> <span>Child Key: L0K4</span><br /> <span>Child Value: L0V4</span><br /> </div> </div><div> <br /> <span>Key: L1K2</span><br /> <span>Value: L1V2</span><br /> <span>Children</span> <br /> <div> <span>Child Key: L0K0</span><br /> <span>Child Value: L0V0</span><br /> </div><div> <span>Child Key: L0K1</span><br /> <span>Child Value: L0V1</span><br /> </div><div> <span>Child Key: L0K2</span><br /> <span>Child Value: L0V2</span><br /> </div><div> <span>Child Key: L0K3</span><br /> <span>Child Value: L0V3</span><br /> </div><div> <span>Child Key: L0K4</span><br /> <span>Child Value: L0V4</span><br /> </div> </div><div> <br /> <span>Key: L1K3</span><br /> <span>Value: L1V3</span><br /> <span>Children</span> <br /> <div> <span>Child Key: L0K0</span><br /> <span>Child Value: L0V0</span><br /> </div><div> <span>Child Key: L0K1</span><br /> <span>Child Value: L0V1</span><br /> </div><div> <span>Child Key: L0K2</span><br /> <span>Child Value: L0V2</span><br /> </div><div> <span>Child Key: L0K3</span><br /> <span>Child Value: L0V3</span><br /> </div><div> <span>Child Key: L0K4</span><br /> <span>Child Value: L0V4</span><br /> </div> </div><div> <br /> <span>Key: L1K4</span><br /> <span>Value: L1V4</span><br /> <span>Children</span> <br /> <div> <span>Child Key: L0K0</span><br /> <span>Child Value: L0V0</span><br /> </div><div> <span>Child Key: L0K1</span><br /> <span>Child Value: L0V1</span><br /> </div><div> <span>Child Key: L0K2</span><br /> <span>Child Value: L0V2</span><br /> </div><div> <span>Child Key: L0K3</span><br /> <span>Child Value: L0V3</span><br /> </div><div> <span>Child Key: L0K4</span><br /> <span>Child Value: L0V4</span><br /> </div> </div> </body></html> <|start_filename|>src/Web/WebDrapo/Controllers/ObjectController.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Sysphera.Middleware.Drapo; using WebDrapo.Model; // For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace WebDrapo.Controllers { [AllowAnonymous] public class ObjectController : Controller { private static List<ObjectVM> _persons = Create(); private static int _counter = 1; private static List<ObjectVM> Create() { List<ObjectVM> persons = new List<ObjectVM>(); persons.Add(new ObjectVM() { Code = 1, Previous = null, Next = 2, Name = "<NAME>", Description = "Father", Date = new DateTime(1980, 6, 3), Value = 37 }); persons.Add(new ObjectVM() { Code = 2, Previous = 1, Next = 3, Name = "Catarina", Description = "Daughter", Date = new DateTime(2011, 7, 21), Value = 6 }); persons.Add(new ObjectVM() { Code = 3, Previous = 2, Next = null, Name = "Augusto", Description = "Tornado", Date = new DateTime(2014, 10, 18), Value = 3 }); return (persons); } [HttpGet] public async Task<DrapoObject> Get([FromQuery]int? code = null) { int index = _persons.FindIndex(p => p.Code == (code ?? 1)); DrapoObject obj = new DrapoObject(_persons[index]); obj.Properties.Add("Index", index); return (await Task.FromResult<DrapoObject>(obj)); } [HttpPost] public async Task Set([FromBody] DrapoObject obj) { int index = obj.GetProperty<int>("Index"); ObjectVM person = obj.Cast<ObjectVM>(); _persons[index] = person; await Task.CompletedTask; } [HttpGet] public async Task<List<ObjectComplexVM>> GetListComplexObjects() { List<ObjectComplexVM> list = new List<ObjectComplexVM>(); for (int i = 0; i < 10; i++) { ObjectComplexVM complex = new ObjectComplexVM(); complex.Name = "Thiago - [" + i + "]"; if (i % 2 == 0) { complex.Child = new ObjectComplexVM(); complex.Child.Name = "Catarina - [" + i + "]"; } list.Add(complex); } return (await Task.FromResult<List<ObjectComplexVM>>(list)); } [HttpGet] public async Task<ObjectComplexVM> GetComplex() { ObjectComplexVM complex = new ObjectComplexVM(); complex.Name = "Thiago"; complex.Child = new ObjectComplexVM(); complex.Child.Name = "Catarina"; return (await Task.FromResult<ObjectComplexVM>(complex)); } [HttpPost] public async Task SetComplex([FromBody] ObjectComplexVM complex) { await Task.CompletedTask; } [HttpPost] public async Task<string> Join([FromQuery] string text1, [FromQuery] string text2) { return (await Task.FromResult(text1 + text2)); } [HttpGet] public async Task<string> GetJoin([FromQuery] string text1, [FromQuery] string text2) { return (await Task.FromResult(text1 + text2)); } [HttpGet] public async Task<ObjectComplexVM> GetChildProperties() { ObjectComplexVM complex = new ObjectComplexVM(); complex.Name = "Thiago"; complex.Child = new ObjectComplexVM(); complex.Child.Name = "Catarina"; complex.Child.Properties.Add("k1", "v1"); complex.Child.Properties.Add("k2", "v2"); complex.Child.Properties.Add("k3", "v3"); return (await Task.FromResult<ObjectComplexVM>(complex)); } [HttpGet] public async Task<ActionResult> GetReports() { List<DrapoObject> reports = new List<DrapoObject>(); reports.Add(CreateReport(null, string.Empty)); reports.Add(CreateReport(1, "Report1")); reports.Add(CreateReport(2, "Report2")); reports.Add(CreateReport(3, "Report3")); return (Ok(await Task.FromResult<List<DrapoObject>>(reports))); } private DrapoObject CreateReport(long? code, string name) { DrapoObject report = new DrapoObject(); report.Properties.Add("Code", code); report.Properties.Add("Name", name); return (report); } [HttpGet] public int GetCounter() { return (_counter++); } } } <|start_filename|>src/Web/WebDrapo/Model/TodoVM.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebDrapo.Model { public class TodoVM { public Guid? Code { set; get; } public string Task { set; get; } public bool Completed { set; get; } public bool Edit { set; get; } } } <|start_filename|>src/Web/WebDrapo/wwwroot/components/labelInput/labelinput.js<|end_filename|> function labelinputConstructor(el, app) { let elj = $(el); let model = elj.attr("d-model"); let caption = elj.attr("d-caption"); let label = $(el).children().first(); let input = $(el).children().last(); label.html(caption); input.attr('d-model', model); } <|start_filename|>src/Web/WebDrapo/Views/Mixed/Index.cshtml<|end_filename|> @{ Layout = null; } <!DOCTYPE html> <script src="/drapo.js"></script> <div d-sector-parent-url="/DrapoPages/PageMasterMaster.html" d-sector-parent="child"> <span>Page Master Child Mixed</span> </div> <|start_filename|>src/Test/WebDrapo.Test/Pages/ControlFlowForDictionary.Test.html<|end_filename|> <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> <script src="/drapo.js"></script> <title>Control Flow - Dictionary</title> </head> <body> <span>Control Flow - Dictionary</span> <div d-datakey="dictionary" d-dataurlget="/Data/GetDictionary"></div> <div d-for="entry in dictionary" style="display: none;"> <br /> <span>Key: {{entry.Key}}</span><br /> <div d-for="value in entry.Value"> <span>Value.Key: {{value.Key}}</span><br /> <span>Value.Value: {{value.Value}}</span><br /> </div> </div><div> <br /> <span>Key: Thiago</span><br /> <div> <span>Value.Key: KT</span><br /> <span>Value.Value: VT</span><br /> </div><div> <span>Value.Key: Kh</span><br /> <span>Value.Value: Vh</span><br /> </div><div> <span>Value.Key: Ki</span><br /> <span>Value.Value: Vi</span><br /> </div><div> <span>Value.Key: Ka</span><br /> <span>Value.Value: Va</span><br /> </div><div> <span>Value.Key: Kg</span><br /> <span>Value.Value: Vg</span><br /> </div><div> <span>Value.Key: Ko</span><br /> <span>Value.Value: Vo</span><br /> </div> </div><div> <br /> <span>Key: Henrique</span><br /> <div> <span>Value.Key: KH</span><br /> <span>Value.Value: VH</span><br /> </div><div> <span>Value.Key: Ke</span><br /> <span>Value.Value: Ve</span><br /> </div><div> <span>Value.Key: Kn</span><br /> <span>Value.Value: Vn</span><br /> </div><div> <span>Value.Key: Kr</span><br /> <span>Value.Value: Vr</span><br /> </div><div> <span>Value.Key: Ki</span><br /> <span>Value.Value: Vi</span><br /> </div><div> <span>Value.Key: Kq</span><br /> <span>Value.Value: Vq</span><br /> </div><div> <span>Value.Key: Ku</span><br /> <span>Value.Value: Vu</span><br /> </div><div> <span>Value.Key: Ke</span><br /> <span>Value.Value: Ve</span><br /> </div> </div><div> <br /> <span>Key: da</span><br /> <div> <span>Value.Key: Kd</span><br /> <span>Value.Value: Vd</span><br /> </div><div> <span>Value.Key: Ka</span><br /> <span>Value.Value: Va</span><br /> </div> </div><div> <br /> <span>Key: Silva</span><br /> <div> <span>Value.Key: KS</span><br /> <span>Value.Value: VS</span><br /> </div><div> <span>Value.Key: Ki</span><br /> <span>Value.Value: Vi</span><br /> </div><div> <span>Value.Key: Kl</span><br /> <span>Value.Value: Vl</span><br /> </div><div> <span>Value.Key: Kv</span><br /> <span>Value.Value: Vv</span><br /> </div><div> <span>Value.Key: Ka</span><br /> <span>Value.Value: Va</span><br /> </div> </div> </body></html> <|start_filename|>src/Web/WebDrapo/Controllers/UserConfigurationController.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Sysphera.Middleware.Drapo.User; namespace WebDrapo.Controllers { [AllowAnonymous] public class UserConfigurationController : Controller { private IDrapoUserConfig _userConfig; public UserConfigurationController(IDrapoUserConfig userConfig) { _userConfig = userConfig; } [HttpGet] public async Task<string> ChangeTheme([FromQuery] string theme) { Dictionary<string, string> values = new Dictionary<string, string>(); values.Add("theme", theme); await this._userConfig.Ensure(values); return (theme); } } } <|start_filename|>src/Middleware/Drapo/DrapoFileType.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; namespace Sysphera.Middleware.Drapo { public enum DrapoFileType { View, Style, Script } } <|start_filename|>src/Middleware/Drapo/components/debugger/debugger.css<|end_filename|> .dbgDebugger { color: black; font-size: 12px; line-height:1.5; padding:2px; margin:2px; border:2px; } .dbgDebugger fieldset { border: 1px solid #003B00; padding: 2px; margin: 2px; } .dbgDebugger legend { font-size: 12px; width:auto; border: 0px } .dbgLayout { position: fixed; border: 3px solid #003B00; overflow-y: auto; } .dbgLayoutLeft { top: 0px; left: 0px; width: 600px; height: 100vh; } .dbgLayoutRight { top: 0px; right: 0px; width: 600px; height: 100vh; } .dbgLayoutNoErrors { background-color: #008F11; } .dbgLayoutErrors { background-color: red; } .dbgDrapo:hover { cursor: pointer; } .dbgBlock { display: block; } .dbgSelector { position: absolute; left: 100px; width: 300px; } .dbgObject { padding: 5px; white-space: nowrap; } .dbgObject div span { padding-left: 15px; } .dbgObject:hover { color: #333; background-color: #EFEFEF; cursor: pointer; } .dbgData { padding: 5px; white-space: nowrap; } .dbgData div span { padding-left: 15px; } .dbgData:hover { color: #333; background-color: #EFEFEF; cursor: pointer; } .dbgObjectSector::before { content: "s"; } .dbgObjectData::before { content: "d"; } .dbgObjectExpanded::before { content: "-"; } .dbgObjectCollapsed::before { content: "+"; } .dbgObjectNoExpandable::before { content: "*"; } .dbgDebuggerCloak { display:none; } .dbgDebuggerClickable:hover { cursor: pointer; } .dbgDebuggerHighlight { border: 1px solid red; } .dbgRequestLast { color: blue; } .dbgRequestNotLast { color: darkred; } <|start_filename|>src/Middleware/Drapo/User/IDrapoUserConfig.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Sysphera.Middleware.Drapo.User { public interface IDrapoUserConfig { Task Ensure(Dictionary<string, string> values); } } <|start_filename|>src/Middleware/Drapo/js/DrapoLinkedCube.js<|end_filename|> "use strict"; var DrapoLinkedCube = (function () { function DrapoLinkedCube() { this._head = null; } DrapoLinkedCube.prototype.AddOrUpdate = function (context, value) { if (this._head === null) { this._head = this.CreateNode(context, value); return (this._head); } if (context === null) throw new Error('Drapo: The context in DrapoLinkedcube cant be null'); if (this._head.Context.length != context.length) throw new Error('Drapo: The context to insert in linked cube must be the same lenght of the context lenght of head'); var node = this._head; var nodePrevious = null; var nodePreviousIndex = null; var compare = 0; for (var i = 0; i < context.length; i++) { var contextValue = context[i]; while ((compare = this.Compare(contextValue, node.Context[i])) !== 0) { if (compare < 0) { var nodeNew = this.CreateNode(context, value); this.AddNodeNext(nodeNew, node, i); if (node === this._head) this._head = nodeNew; else if (nodePrevious !== null) this.AddNodeNext(nodePrevious, nodeNew, nodePreviousIndex); return (nodeNew); } else { nodePrevious = node; nodePreviousIndex = i; var nodeNext = this.GetNodeNext(node, i); if (nodeNext === null) { var nodeNew = this.CreateNode(context, value); this.AddNodeNext(node, nodeNew, i); return (nodeNew); } else { node = nodeNext; } } } } node.Value = value; return (node); }; DrapoLinkedCube.prototype.Get = function (context) { var entry = null; var node = this._head; var index = 0; while (node !== null) { if (this.IsEqualContext(node.Context, context)) return (node.Value); entry = this.GetNextInContext(node, context, index); if (entry === null) break; node = entry[0]; index = entry[1]; } return (null); }; DrapoLinkedCube.prototype.GetNode = function (context) { if (context == null) return (null); var entry = null; var node = this._head; var index = 0; while (node !== null) { if (this.IsEqualContext(context, node.Context, false)) return (node); entry = this.GetNextInContext(node, context, index); if (entry === null) break; node = entry[0]; index = entry[1]; } return (null); }; DrapoLinkedCube.prototype.Clear = function () { this._head = null; }; DrapoLinkedCube.prototype.Remove = function (context) { if (this._head === null) return (null); var node = this._head; var nodePrevious = null; var nodePreviousIndex = null; var compare = 0; for (var i = 0; ((i < context.length) && (node !== null)); i++) { var contextValue = context[i]; while ((compare = this.Compare(contextValue, node.Context[i])) !== 0) { if (compare < 0) { return (null); } else { nodePrevious = node; nodePreviousIndex = i; var nodeNext = this.GetNodeNext(node, i); node = nodeNext; if (node === null) return (null); } } } if (node !== null) { var isContextToRemove = context.length < this._head.Context.length; var nodeNext = this.GetNextReverse(node, isContextToRemove ? context.length - 1 : null); var nodeNextIndex = this.GetNextReverseIndex(node, isContextToRemove ? context.length - 1 : null); if (nodePrevious === null) { if (nodeNext !== null) { this.MoveLinks(nodeNext, node, nodeNextIndex); } this._head = nodeNext; } else { this.MoveLinks(nodeNext, node, nodeNextIndex); this.AddNodeNext(nodePrevious, nodeNext, nodePreviousIndex); } } return (node); }; DrapoLinkedCube.prototype.GetHead = function () { return (this._head); }; DrapoLinkedCube.prototype.CreateNode = function (context, value) { var node = new DrapoLinkedCubeNode(); node.Context = context; node.Value = value; return (node); }; DrapoLinkedCube.prototype.GetNextInContext = function (node, context, index) { for (var i = index; i < context.length; i++) { var compare = this.Compare(context[i], node.Context[i]); if (compare < 0) return (null); else if (compare === 0) continue; if ((node.Next === null) || (node.Next.length <= i)) return (null); return ([node.Next[i], i]); } return (null); }; DrapoLinkedCube.prototype.Compare = function (value1, value2) { if (value1 < value2) return (-1); if (value1 > value2) return (1); return (0); }; DrapoLinkedCube.prototype.GetNextReverse = function (node, index) { if (index === void 0) { index = null; } if (node.Next === null) return (null); var start = index !== null ? index : node.Next.length - 1; if (start >= node.Next.length) start = node.Next.length - 1; for (var i = start; i >= 0; i--) { var nodeNext = node.Next[i]; if (nodeNext !== null) return (nodeNext); } return (null); }; DrapoLinkedCube.prototype.GetNextReverseIndex = function (node, index) { if (index === void 0) { index = null; } if (node.Next === null) return (null); var start = index !== null ? index : node.Next.length - 1; if (start >= node.Next.length) start = node.Next.length - 1; for (var i = start; i >= 0; i--) { var nodeNext = node.Next[i]; if (nodeNext !== null) return (i); } return (null); }; DrapoLinkedCube.prototype.IsEqualContext = function (context1, context2, checkSize) { if (checkSize === void 0) { checkSize = true; } if ((checkSize) && (context1.length != context2.length)) return (false); for (var i = 0; i < context1.length; i++) if (context1[i] !== context2[i]) return (false); return (true); }; DrapoLinkedCube.prototype.EnsureNodeNext = function (node, index) { if (node.Next === null) node.Next = []; while (node.Next.length <= index) node.Next.push(null); }; DrapoLinkedCube.prototype.AddNodeNext = function (node, nodeNext, index) { this.EnsureNodeNext(node, index); node.Next[index] = nodeNext; if (nodeNext === null) return; if (nodeNext.Next === null) return; this.MoveLinks(node, nodeNext, index); }; DrapoLinkedCube.prototype.MoveLinks = function (node, nodeNext, index) { if (index === void 0) { index = null; } if (node === null) return; if (nodeNext === null) return; if (nodeNext.Next === null) return; this.EnsureNodeNext(node, index); for (var i = 0; ((index === null) || (i < index)) && (i < nodeNext.Next.length); i++) { if (node.Context[i] !== nodeNext.Context[i]) break; if (node.Next[i] === null) node.Next[i] = nodeNext.Next[i]; nodeNext.Next[i] = null; } }; DrapoLinkedCube.prototype.GetNodeNext = function (node, index) { if (node.Next === null) return (null); if (node.Next.length <= index) return (null); return (node.Next[index]); }; DrapoLinkedCube.prototype.ToList = function (node) { if (node === void 0) { node = null; } var list = []; if (node === null) node = this._head; if (node != null) this.AppendNodeToList(list, node); return (list); }; DrapoLinkedCube.prototype.AppendNodeToList = function (list, node) { list.push(node); if (node.Next == null) return; for (var i = 0; i < node.Next.length; i++) { var nodeNext = node.Next[i]; if (nodeNext !== null) this.AppendNodeToList(list, nodeNext); } }; DrapoLinkedCube.prototype.ToListValues = function (node) { if (node === void 0) { node = null; } var listValues = []; var list = this.ToList(node); for (var i = 0; i < list.length; i++) listValues.push(list[i].Value); return (listValues); }; return DrapoLinkedCube; }()); <|start_filename|>src/Web/WebDrapo/wwwroot/DrapoPages/DataQueryAggregationFunction.html<|end_filename|> <!DOCTYPE html> <html> <head> <script src="/drapo.js"></script> <title>Data Query - Aggregation Function</title> </head> <body> <div> <span>Data Query - Aggregation Function</span> <div d-dataKey="objects" d-dataUrlGet="~/Data/GetLevels?children=5"></div> <div d-dataKey="objectsQuery" d-dataType="query" d-dataValue="SELECT Count(Key) AS Count FROM objects"></div> <div> <span>{{objectsQuery.Count}}</span> </div> </div> </body> </html> <|start_filename|>src/Web/WebDrapo/wwwroot/css/themes.dark.css<|end_filename|> body { background-color: black; color: darkgreen; } .background { background-color: green; } <|start_filename|>src/Middleware/Drapo/DrapoView.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; namespace Sysphera.Middleware.Drapo { public class DrapoView { public string Name { set; get; } public string Tag { set; get; } public string Condition { set; get; } } } <|start_filename|>src/Middleware/Drapo/js/DrapoLinkedListNode.js<|end_filename|> "use strict"; var DrapoLinkedListNode = (function () { function DrapoLinkedListNode() { this.Value = null; this.Next = null; this.Index = null; } return DrapoLinkedListNode; }()); <|start_filename|>src/Middleware/Drapo/Pipe/DrapoConnectionManagerSingle.cs<|end_filename|> using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sysphera.Middleware.Drapo.Pipe { public class DrapoConnectionManagerSingle : IDrapoConnectionManager { private readonly ConcurrentDictionary<string, DrapoConnection> _connections = new ConcurrentDictionary<string, DrapoConnection>(); public void Create(string domain, string connectionId, string containerId) { _connections.TryAdd(connectionId, new DrapoConnection(connectionId, domain, containerId)); } public bool Remove(string domain, string connectionId) { return(_connections.TryRemove(connectionId, out _)); } public long Count(string domain) { return (this.GetAll(domain).Count); } public DrapoConnection Get(string domain, string connectionId) { if (_connections.TryGetValue(connectionId, out DrapoConnection connection)) return (connection); return (null); } public bool Identify(string domain, string connectionId, long identity) { DrapoConnection connection = this.Get(domain, connectionId); if (connection == null) return (false); connection.Identity = identity; return (true); } public List<DrapoConnection> GetAll(string domain) { List<DrapoConnection> connections = new List<DrapoConnection>(_connections.Values.ToList().FindAll(c => c.Domain == domain)); return (connections); } public bool Check() { return (false); } } } <|start_filename|>src/Middleware/Drapo/DrapoObjectConverter.cs<|end_filename|> using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace Sysphera.Middleware.Drapo { public class DrapoObjectConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { DrapoObject obj = (DrapoObject)value; writer.WriteStartObject(); foreach (KeyValuePair<string, object> entry in obj.GetProperties(true)) { writer.WritePropertyName(entry.Key); if (this.WriteJsonArray(writer, entry.Value, serializer)) continue; DrapoObject objValue = entry.Value as DrapoObject; if (objValue == null) writer.WriteValue(entry.Value); else this.WriteJson(writer, objValue, serializer); } writer.WriteEnd(); } private bool WriteJsonArray(JsonWriter writer, object value, JsonSerializer serializer) { System.Collections.IList list = value as System.Collections.IList; if (list == null) return (false); writer.WriteStartArray(); foreach (Object itemArray in list) WriteJson(writer, itemArray, serializer); writer.WriteEndArray(); return (true); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { DrapoObject obj = new DrapoObject(); while (reader.Read()) { if (reader.TokenType == JsonToken.PropertyName) continue; if (reader.TokenType == JsonToken.EndObject) continue; obj.Properties.Add(reader.Path, reader.Value); } return(obj); } public override bool CanConvert(Type objectType) { return (objectType == typeof(DrapoObject)); } } } <|start_filename|>src/Middleware/Drapo/DrapoObject.cs<|end_filename|> using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Dynamic; using System.Reflection; using System.Text; namespace Sysphera.Middleware.Drapo { [JsonConverter(typeof(DrapoObjectConverter))] public class DrapoObject : DynamicObject, IDynamicMetaObjectProvider { //Fields private object _instance; private Type _instanceType; private PropertyInfo[] _instancePropertyInfo; private Dictionary<string, object> _properties = new Dictionary<string, object>(); //Properties public Dictionary<string, object> Properties { get => _properties; } private PropertyInfo[] InstancePropertyInfo { get { if (_instancePropertyInfo == null && _instance != null) _instancePropertyInfo = _instance.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly); return (_instancePropertyInfo); } } public DrapoObject() { Initialize(null); } public DrapoObject(object instance) { Initialize(instance); } protected virtual void Initialize(object instance) { _instance = instance; if (instance != null) _instanceType = instance.GetType(); } public override bool TryGetMember(GetMemberBinder binder, out object result) { result = null; if (_properties.ContainsKey(binder.Name)) { result = _properties[binder.Name]; return (true); } if (_instance != null) { try { return GetProperty(_instance, binder.Name, out result); } catch { } } result = null; return (false); } public override bool TrySetMember(SetMemberBinder binder, object value) { if (_instance != null) { try { bool result = SetProperty(_instance, binder.Name, value); if (result) return (true); } catch { } } _properties[binder.Name] = value; return (true); } public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { if (_instance != null) { try { if (InvokeMethod(_instance, binder.Name, args, out result)) return (true); } catch { } } result = null; return (false); } protected bool GetProperty(object instance, string name, out object result) { if (instance == null) instance = this; var memberInfos = _instanceType.GetMember(name, BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance); if (memberInfos != null && memberInfos.Length > 0) { var memberInfo = memberInfos[0]; if (memberInfo.MemberType == MemberTypes.Property) { result = ((PropertyInfo)memberInfo).GetValue(instance, null); return (true); } } result = null; return (false); } protected bool SetProperty(object instance, string name, object value) { if (instance == null) instance = this; Type type = instance.GetType(); PropertyInfo propertyInfo = type.GetProperty(name); if (propertyInfo == null) return (false); Type propertyType = propertyInfo.PropertyType; var targetType = IsNullableType(propertyType) ? Nullable.GetUnderlyingType(propertyType) : propertyType; if (value != null) value = Convert.ChangeType(value, targetType); propertyInfo.SetValue(instance, value, null); return (true); } private static bool IsNullableType(Type type) { return ((type.IsGenericType) && (type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))); } protected bool InvokeMethod(object instance, string name, object[] args, out object result) { if (instance == null) instance = this; var memberInfos = _instanceType.GetMember(name, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance); if (memberInfos != null && memberInfos.Length > 0) { var memberInfo = memberInfos[0] as MethodInfo; result = memberInfo.Invoke(_instance, args); return (true); } result = null; return (false); } public object this[string key] { get { if (this._properties.ContainsKey(key)) return _properties[key]; if (GetProperty(_instance, key, out object result)) return (result); return (null); } set { if (_properties.ContainsKey(key)) { _properties[key] = value; return; } var memberInfos = _instanceType.GetMember(key, BindingFlags.Public | BindingFlags.GetProperty); if (memberInfos != null && memberInfos.Length > 0) SetProperty(_instance, key, value); else _properties[key] = value; } } public IEnumerable<KeyValuePair<string, object>> GetProperties(bool includeInstanceProperties = false) { if (includeInstanceProperties && _instance != null) { foreach (var prop in this.InstancePropertyInfo) yield return (new KeyValuePair<string, object>(prop.Name, prop.GetValue(_instance, null))); } foreach (var key in this._properties.Keys) yield return (new KeyValuePair<string, object>(key, this._properties[key])); } public bool Contains(KeyValuePair<string, object> item, bool includeInstanceProperties = false) { if (_properties.ContainsKey(item.Key)) return (true); if (includeInstanceProperties && _instance != null) { foreach (var prop in this.InstancePropertyInfo) { if (prop.Name == item.Key) return (true); } } return (false); } public T Cast<T>() { T instance = Activator.CreateInstance<T>(); this.Initialize(instance); foreach (KeyValuePair<string, object> entry in this._properties) this.SetProperty(instance, entry.Key, entry.Value); return (instance); } public T GetProperty<T>(string name) { if (this._properties.ContainsKey(name)) return ((T)Convert.ChangeType(this._properties[name], typeof(T))); if (!this.GetProperty(null, name, out object value)) return (default(T)); return((T)Convert.ChangeType(value, typeof(T))); } } } <|start_filename|>src/Web/WebDrapo/Controllers/SectorController.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace WebDrapo.Controllers { [AllowAnonymous] public class SectorController : Controller { [HttpGet] public string GetContentDynamic(int levels = 0, int children = 2) { StringBuilder builder = new StringBuilder(); builder.AppendLine("<div>"); builder.AppendLine("<span>Content Dynamic</span>"); InsertSectorToContentDynamic(builder, string.Empty, levels, children); builder.AppendLine("</div>"); return (builder.ToString()); } private void InsertSectorToContentDynamic(StringBuilder builder, string prefix, int levels, int children) { if (levels > 0) { for (int i = 0; i < children; i++) InsertSectorToContentDynamicNonLeaf(builder, $"{prefix}_L{levels}C{i}", levels - 1, children); } else { for (int i = 0; i < children; i++) InsertSectorToContentDynamicLeaf(builder, $"{prefix}_C{i}"); } } private void InsertSectorToContentDynamicNonLeaf(StringBuilder builder, string prefix, int levels, int children) { builder.AppendLine($"<div d-sector='{prefix}' >"); InsertSectorToContentDynamic(builder, prefix, levels, children); builder.AppendLine("</div>"); } private void InsertSectorToContentDynamicLeaf(StringBuilder builder, string sectorName) { builder.AppendLine($"<div d-sector='{sectorName}' >"); builder.AppendLine(" <div d-dataKey='items' d-dataUrlGet='~/Data/GetModelSample'></div>"); builder.AppendLine(" <div>"); builder.AppendLine(" <div d-for='item in items'>"); builder.AppendLine(" <input type='text' d-model='{{item.Key}}'>"); builder.AppendLine(" <span>{{item.Key}}</span>"); builder.AppendLine(" <br />"); builder.AppendLine(" </div>"); builder.AppendLine(" </div>"); builder.AppendLine(" <br />"); builder.AppendLine("</div>"); } } } <|start_filename|>src/Web/WebDrapo/Controllers/HelpController.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using WebDrapo.Model; using Microsoft.AspNetCore.Authorization; namespace WebDrapo.Controllers { [AllowAnonymous] public class HelpController : Controller { [HttpGet] public IEnumerable<KeyValueVO> Index() { List<KeyValueVO> dictionary = new List<KeyValueVO>(); dictionary.Add(new KeyValueVO() { Key = "sector", Value = "Sectors", Children = GetSectorTags()}); dictionary.Add(new KeyValueVO() { Key = "sector", Value = "Data Handlers", Children = GetDataTags() }); dictionary.Add(new KeyValueVO() { Key = "sector", Value = "Statements", Children = GetStatementTags() }); dictionary.Add(new KeyValueVO() { Key = "sector", Value = "Configurations", Children = GetConfigurationTags() }); dictionary.Add(new KeyValueVO() { Key = "sector", Value = "Events", Children = GetEventTags() }); dictionary.Add(new KeyValueVO() { Key = "sector", Value = "CSS Handlers", Children = GetCSSTags() }); return dictionary; } private List<KeyValueVO> GetSectorTags() { List<KeyValueVO> sectorTags = new List<KeyValueVO>(); sectorTags.Add(new KeyValueVO() { Key = "d-sector", Value = "Name of a sector that is contained by another sector" }); sectorTags.Add(new KeyValueVO() { Key = "d-sector-url", Value = "Relative path to a page that is contained by another page" }); sectorTags.Add(new KeyValueVO() { Key = "d-sector-parent", Value = "Name of a sector that contains other sector" }); sectorTags.Add(new KeyValueVO() { Key = "d-sector-parent-url", Value = "Relative path to a page that contains other page" }); sectorTags.Add(new KeyValueVO() { Key = "d-route", Value = "True by default, indicates whether or not to use routing features" }); return sectorTags; } private List<KeyValueVO> GetDataTags() { List<KeyValueVO> dataTags = new List<KeyValueVO>(); dataTags.Add(new KeyValueVO() { Key = "d-dataKey", Value = "Data identifier" }); dataTags.Add(new KeyValueVO() { Key = "d-dataUrlGet", Value = "GET method that will return data associated with d-dataKey" }); dataTags.Add(new KeyValueVO() { Key = "d-dataUrlSet", Value = "POST method that will be called on d-dataKey updates" }); dataTags.Add(new KeyValueVO() { Key = "d-dataType=\"object\"", Value = "Indicates that d-dataKey is a object created on client side" }); dataTags.Add(new KeyValueVO() { Key = "d-dataType=\"array\"", Value = "Indicates that d-dataKey is an array of objects created on client side" }); dataTags.Add(new KeyValueVO() { Key = "d-dataType=\"value\"", Value = "Indicates that d-dataKey is a primitive object created on client side" }); dataTags.Add(new KeyValueVO() { Key = "d-dataValue", Value = "Value of a d-dataType identifier value typed"}); dataTags.Add(new KeyValueVO() { Key = "d-model", Value = "Indicates that d-dataKey is an object binded to server side" }); dataTags.Add(new KeyValueVO() { Key = "d-dataProperty-<name>", Value = "Name of a property inside object defined by d-dataType" }); dataTags.Add(new KeyValueVO() { Key = "d-attr-<name>", Value = "Value of object property d-dataProperty-<name>" }); dataTags.Add(new KeyValueVO() { Key = "d-dataProperty-<name>-name", Value = "Name of a property inside object defined by d-dataType" }); dataTags.Add(new KeyValueVO() { Key = "d-dataProperty-<name>-value", Value = "Value of a property inside object defined by d-dataType" }); dataTags.Add(new KeyValueVO() { Key = "d-dataLazy", Value = "When set to true, data will be loaded in increments" }); dataTags.Add(new KeyValueVO() { Key = "d-dataLazyStart", Value = "Start index of data item" }); dataTags.Add(new KeyValueVO() { Key = "d-dataLazyIncrement", Value = "Quantity of data items to be loaded at each increment" }); dataTags.Add(new KeyValueVO() { Key = "d-dataDelay", Value = "When set to true, loads properties individually instead of the whole object" }); dataTags.Add(new KeyValueVO() { Key = "d-dataUnitOfWork", Value = "When set to true, d-dataKey object will be treated as DataSet" }); return dataTags; } private List<KeyValueVO> GetStatementTags() { List<KeyValueVO> statementTags = new List<KeyValueVO>(); statementTags.Add(new KeyValueVO() { Key = "d-for", Value = "Same behavior as \"foreach\""}); statementTags.Add(new KeyValueVO() { Key = "d-if", Value = "Same behavior as \"if\"" }); return statementTags; } private List<KeyValueVO> GetConfigurationTags() { List<KeyValueVO> configurationTags = new List<KeyValueVO>(); configurationTags.Add(new KeyValueVO() { Key = "d-dataConfigGet", Value = "Object to access configuration items" }); configurationTags.Add(new KeyValueVO() { Key = "d-dataCookieGet", Value = "Object to access cookie items" }); return configurationTags; } private List<KeyValueVO> GetEventTags() { List<KeyValueVO> eventTags = new List<KeyValueVO>(); eventTags.Add(new KeyValueVO() { Key = "d-model-event", Value = "Changes d-model event" }); eventTags.Add(new KeyValueVO() { Key = "d-on-click", Value = "Functions to be called by OnClick events" }); eventTags.Add(new KeyValueVO() { Key = "d-on-change", Value = "Functions to be called by OnChange events" }); eventTags.Add(new KeyValueVO() { Key = "d-on-keyup-enter", Value = "Functions to be called by KeyUp events when key is Enter" }); eventTags.Add(new KeyValueVO() { Key = "d-on-dblclick", Value = "Functions to be called by DoubleClick events" }); eventTags.Add(new KeyValueVO() { Key = "d-on-blur", Value = "Functions to be called by OnBlur events" }); return eventTags; } private List<KeyValueVO> GetCSSTags() { List<KeyValueVO> cssTags = new List<KeyValueVO>(); cssTags.Add(new KeyValueVO() { Key = "d-class", Value = "Changes element css selector" }); return cssTags; } [HttpGet] public string FindTag(string key) { List<KeyValueVO> tags = (List<KeyValueVO>)Index(); foreach (KeyValueVO tag in tags) { if (tag.Key == key) return tag.Value; string childValue = FindTagInChildren(key, tag.Children); if (childValue != null) return childValue; } return null; } private string FindTagInChildren(string key, List<KeyValueVO> children) { foreach (KeyValueVO tag in children) { if (tag.Key == key) return tag.Value; string childValue = FindTagInChildren(key, tag.Children); if (childValue != null) return childValue; } return null; } [HttpGet] public string GetUsage(string key) { if (key == "d-model-event") return "<input class=\"edit\" type=\"text\" d-model=\"{{todo.Task}}\" d-model-event=\"blur\" d-on-blur=\"UncheckItemField({{todo.Edit}},false)\">"; else if (key == "d-on-click") return "<input type=\"button\" value=\"Talk\" d-on-click=\"AddDataItem(chats, user, false); PostData(chats)\"/>"; else if (key == "d-on-change") return "<select d-model=\"{{drapo.theme}}\" d-on-change=\"PostData(drapo); ReloadPage()\">"; else if (key == "d-on-keyup-enter") return "<input type=\"text\" class=\"new- todo\" d-model=\"{{taskAdd.Task}}\" d-on-keyup-enter=\"AddDataItem(todos, taskAdd); ClearDataField(taskAdd, Task)\">"; else if (key == "d-on-dblclick") return "<label d-on-dblclick=\"CheckItemField({{todo.Edit}})\">\"Text\"</label>"; else if (key == "d-on-blur") return "<input class=\"edit\" type=\"text\" d-model=\"{{todo.Task}}\" d-model-event=\"blur\" d-on-blur=\"UncheckItemField({{todo.Edit}},false)\">"; else if (key == "d-sector") return "<div d-sector=\"sector\" d-sector-url=\"/DrapoPages/RouterOne.html\">"; else if (key == "d-sector-url") return "<div d-sector=\"sector\" d-sector-url=\"/DrapoPages/RouterOne.html\">"; else if (key == "d-sector-parent") return "<div d-sector-parent-url=\"/DrapoPages/RouterMaster.html\" d-sector-parent=\"sector\">"; else if (key == "d-sector-parent-url") return "<div d-sector-parent-url=\"/DrapoPages/RouterMaster.html\" d-sector-parent=\"sector\">"; else if (key == "d-route") return "<div d-sector=\"sectorSubMenu\" d-route=\"false\">"; else if (key == "d-dataKey") return "<div d-dataKey=\"users\" d-dataUrlGet=\"/Data/GetIFSample\">"; else if (key == "d-dataUrlGet") return "<div d-dataKey=\"cultures\" d-dataUrlGet=\"/Culture/GetCultures\">"; else if (key == "d-dataUrlSet") return "<div d-dataKey=\"chats\" d-dataUnitOfWork=\"true\" d-dataUrlGet=\"/Chat/Get\" d-dataUrlSet=\"/Chat/Set\">"; else if (key == "d-dataType=\"object\"") return "<div d-dataKey=\"response\" d-dataType=\"object\">"; else if (key == "d-dataType=\"array\"") return "<div d-dataKey=\"list\" d-dataType=\"array\">"; else if (key == "d-dataType=\"value\"") return "<div d-dataKey=\"response\" d-dataType=\"value\" d-dataValue=\"NewValue\">"; else if (key == "d-dataValue") return "<div d-dataKey=\"response\" d-dataType=\"value\" d-dataValue=\"NewValue\">"; else if (key == "d-model") return "<input type=\"text\" d-model=\"{{keyValue.Key}}\"/>"; else if (key == "d-dataProperty-<name>") return "<div d-datakey=\"config\" d-dataType=\"object\" d-dataproperty-showactive=\"true\" d-dataproperty-showcompleted=\"true\">"; else if (key == "d-attr-<name>") return "<input d-attr-placeholder=\"{{res.placeholder}}\" type=\"text\" d-attr-title=\"{{res.Tooltip}} \" placeholder=\"Name here\" title=\"I am a tip !\"/>"; else if (key == "d-dataProperty-<name>-name") return "<div d-datakey=\"keyValue\" d-dataType=\"object\" d-dataproperty-key-name=\"Key\" d-dataproperty-key-value=\"admin\" d-dataurlset=\"/Authentication/Login\">"; else if (key == "d-dataProperty-<name>-value") return "<div d-datakey=\"keyValue\" d-dataType=\"object\" d-dataproperty-key-name=\"Key\" d-dataproperty-key-value=\"admin\" d-dataurlset=\"/Authentication/Login\">"; else if (key == "d-dataLazy") return "< div d-dataKey = \"users\" d-dataLazy = \"true\" d-dataLazyStart = \"0\" d-dataLazyIncrement = \"100\" d - dataUrlGet = \"/Data/GetData\"> "; else if (key == "d-dataLazyStart") return "< div d-dataKey = \"users\" d-dataLazy = \"true\" d-dataLazyStart = \"0\" d-dataLazyIncrement = \"100\" d - dataUrlGet = \"/Data/GetData\"> "; else if (key == "d-dataLazyIncrement") return "< div d-dataKey = \"users\" d-dataLazy = \"true\" d-dataLazyStart = \"0\" d-dataLazyIncrement = \"100\" d - dataUrlGet = \"/Data/GetData\"> "; else if (key == "d-dataDelay") return "<div d-dataKey=\"culture\" d-dataDelay=\"true\" d-dataUrlGet=\"/Data/GetCulture\">"; else if (key == "d-dataUnitOfWork") return "<div d-dataKey=\"chats\" d-dataUnitOfWork=\"true\" d-dataUrlGet=\"/Chat/Get\" d-dataUrlSet=\"/Chat/Set\">"; else if (key == "d-for") return "<div d-for=\"user in users\">"; else if (key == "d-if") return "<option d-for=\"user in users\" d-if=\"{{user.Visible}}\" value=\"{{user.Key}}\">"; else if (key == "d-dataConfigGet") return "<div d-dataKey=\"views\" d-dataConfigGet=\"Views\">"; else if (key == "d-dataCookieGet") return "<div d-dataKey=\"drapo\" d-dataCookieGet=\"drapo\">"; return ""; } [HttpGet] public IEnumerable<KeyValueVO> GetRelatedTags(string key) { List<KeyValueVO> relatedTags = new List<KeyValueVO>(); if (key == "d-model-event") { relatedTags.Add(new KeyValueVO() { Key = "d-on-click", Value = "Functions to be called by OnClick events" }); relatedTags.Add(new KeyValueVO() { Key = "d-on-change", Value = "Functions to be called by OnChange events" }); relatedTags.Add(new KeyValueVO() { Key = "d-on-keyup-enter", Value = "Functions to be called by KeyUp events when key is Enter" }); relatedTags.Add(new KeyValueVO() { Key = "d-on-dblclick", Value = "Functions to be called by DoubleClick events" }); relatedTags.Add(new KeyValueVO() { Key = "d-on-blur", Value = "Functions to be called by OnBlur events" }); } else if (key == "d-on-click") { relatedTags.Add(new KeyValueVO() { Key = "d-model-event", Value = "Changes d-model event" }); relatedTags.Add(new KeyValueVO() { Key = "d-on-change", Value = "Functions to be called by OnChange events" }); relatedTags.Add(new KeyValueVO() { Key = "d-on-keyup-enter", Value = "Functions to be called by KeyUp events when key is Enter" }); relatedTags.Add(new KeyValueVO() { Key = "d-on-dblclick", Value = "Functions to be called by DoubleClick events" }); relatedTags.Add(new KeyValueVO() { Key = "d-on-blur", Value = "Functions to be called by OnBlur events" }); } else if (key == "d-on-change") { relatedTags.Add(new KeyValueVO() { Key = "d-model-event", Value = "Changes d-model event" }); relatedTags.Add(new KeyValueVO() { Key = "d-on-click", Value = "Functions to be called by OnClick events" }); relatedTags.Add(new KeyValueVO() { Key = "d-on-keyup-enter", Value = "Functions to be called by KeyUp events when key is Enter" }); relatedTags.Add(new KeyValueVO() { Key = "d-on-dblclick", Value = "Functions to be called by DoubleClick events" }); relatedTags.Add(new KeyValueVO() { Key = "d-on-blur", Value = "Functions to be called by OnBlur events" }); } else if (key == "d-on-keyup-enter") { relatedTags.Add(new KeyValueVO() { Key = "d-model-event", Value = "Changes d-model event" }); relatedTags.Add(new KeyValueVO() { Key = "d-on-click", Value = "Functions to be called by OnClick events" }); relatedTags.Add(new KeyValueVO() { Key = "d-on-change", Value = "Functions to be called by OnChange events" }); relatedTags.Add(new KeyValueVO() { Key = "d-on-dblclick", Value = "Functions to be called by DoubleClick events" }); relatedTags.Add(new KeyValueVO() { Key = "d-on-blur", Value = "Functions to be called by OnBlur events" }); } else if (key == "d-on-dblclick") { relatedTags.Add(new KeyValueVO() { Key = "d-model-event", Value = "Changes d-model event" }); relatedTags.Add(new KeyValueVO() { Key = "d-on-click", Value = "Functions to be called by OnClick events" }); relatedTags.Add(new KeyValueVO() { Key = "d-on-change", Value = "Functions to be called by OnChange events" }); relatedTags.Add(new KeyValueVO() { Key = "d-on-keyup-enter", Value = "Functions to be called by KeyUp events when key is Enter" }); relatedTags.Add(new KeyValueVO() { Key = "d-on-blur", Value = "Functions to be called by OnBlur events" }); } else if (key == "d-on-blur") { relatedTags.Add(new KeyValueVO() { Key = "d-model-event", Value = "Changes d-model event" }); relatedTags.Add(new KeyValueVO() { Key = "d-on-click", Value = "Functions to be called by OnClick events" }); relatedTags.Add(new KeyValueVO() { Key = "d-on-change", Value = "Functions to be called by OnChange events" }); relatedTags.Add(new KeyValueVO() { Key = "d-on-keyup-enter", Value = "Functions to be called by KeyUp events when key is Enter" }); relatedTags.Add(new KeyValueVO() { Key = "d-on-dblclick", Value = "Functions to be called by DoubleClick events" }); } else if (key == "d-sector") { relatedTags.Add(new KeyValueVO() { Key = "d-sector-url", Value = "Relative path to a page that is contained by another page" }); } else if (key == "d-sector-url") { relatedTags.Add(new KeyValueVO() { Key = "d-sector", Value = "Name of a sector that is contained by another sector" }); relatedTags.Add(new KeyValueVO() { Key = "d-route", Value = "True by default, indicates whether or not to use routing features" }); } else if (key == "d-sector-parent") { relatedTags.Add(new KeyValueVO() { Key = "d-sector-parent-url", Value = "Relative path to a page that contains other page" }); } else if (key == "d-sector-parent-url") { relatedTags.Add(new KeyValueVO() { Key = "d-sector-parent", Value = "Name of a sector that contains other sector" }); relatedTags.Add(new KeyValueVO() { Key = "d-route", Value = "True by default, indicates whether or not to use routing features" }); } else if (key == "d-route") { relatedTags.Add(new KeyValueVO() { Key = "d-sector-parent-url", Value = "Relative path to a page that contains other page" }); relatedTags.Add(new KeyValueVO() { Key = "d-sector", Value = "Name of a sector that is contained by another sector" }); } else if (key == "d-dataKey") { relatedTags.Add(new KeyValueVO() { Key = "d-dataUrlGet", Value = "GET method that will return data associated with d-dataKey" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataUrlSet", Value = "POST method that will be called on d-dataKey updates" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataType=\"object\"", Value = "Indicates that d-dataKey is a object created on client side" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataType=\"array\"", Value = "Indicates that d-dataKey is an array of objects created on client side" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataType=\"value\"", Value = "Indicates that d-dataKey is a primitive object created on client side" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataValue", Value = "Value of a d-dataType identifier value typed" }); relatedTags.Add(new KeyValueVO() { Key = "d-model", Value = "Indicates that d-dataKey is an object binded to server side" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataUnitOfWork", Value = "When set to true, d-dataKey object will be treated as DataSet" }); } else if (key == "d-dataUrlGet") { relatedTags.Add(new KeyValueVO() { Key = "d-dataKey", Value = "Data identifier" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataUrlSet", Value = "POST method that will be called on d-dataKey updates" }); relatedTags.Add(new KeyValueVO() { Key = "d-model", Value = "Indicates that d-dataKey is an object binded to server side" }); } else if (key == "d-dataUrlSet") { relatedTags.Add(new KeyValueVO() { Key = "d-dataKey", Value = "Data identifier" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataUrlGet", Value = "GET method that will return data associated with d-dataKey" }); relatedTags.Add(new KeyValueVO() { Key = "d-model", Value = "Indicates that d-dataKey is an object binded to server side" }); } else if (key == "d-dataType=\"object\"") { relatedTags.Add(new KeyValueVO() { Key = "d-dataKey", Value = "Data identifier" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataType=\"array\"", Value = "Indicates that d-dataKey is an array of objects created on client side" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataType=\"value\"", Value = "Indicates that d-dataKey is a primitive object created on client side" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataValue", Value = "Value of a d-dataType identifier value typed" }); relatedTags.Add(new KeyValueVO() { Key = "d-model", Value = "Indicates that d-dataKey is an object binded to server side" }); } else if (key == "d-dataType=\"array\"") { relatedTags.Add(new KeyValueVO() { Key = "d-dataKey", Value = "Data identifier" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataType=\"object\"", Value = "Indicates that d-dataKey is a object created on client side" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataType=\"value\"", Value = "Indicates that d-dataKey is a primitive object created on client side" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataValue", Value = "Value of a d-dataType identifier value typed" }); relatedTags.Add(new KeyValueVO() { Key = "d-model", Value = "Indicates that d-dataKey is an object binded to server side" }); } else if (key == "d-dataType=\"value\"") { relatedTags.Add(new KeyValueVO() { Key = "d-dataKey", Value = "Data identifier" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataType=\"object\"", Value = "Indicates that d-dataKey is a object created on client side" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataType=\"array\"", Value = "Indicates that d-dataKey is an array of objects created on client side" }); relatedTags.Add(new KeyValueVO() { Key = "d-model", Value = "Indicates that d-dataKey is an object binded to server side" }); } else if (key == "d-dataValue") { relatedTags.Add(new KeyValueVO() { Key = "d-dataKey", Value = "Data identifier" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataType=\"object\"", Value = "Indicates that d-dataKey is a object created on client side" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataType=\"array\"", Value = "Indicates that d-dataKey is an array of objects created on client side" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataType=\"value\"", Value = "Indicates that d-dataKey is a primitive object created on client side" }); relatedTags.Add(new KeyValueVO() { Key = "d-model", Value = "Indicates that d-dataKey is an object binded to server side" }); } else if (key == "d-model") { relatedTags.Add(new KeyValueVO() { Key = "d-dataKey", Value = "Data identifier" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataValue", Value = "Value of a d-dataType identifier value typed" }); } else if (key == "d-dataProperty-<name>") { relatedTags.Add(new KeyValueVO() { Key = "d-dataKey", Value = "Data identifier" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataType=\"object\"", Value = "Indicates that d-dataKey is a object created on client side" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataType=\"array\"", Value = "Indicates that d-dataKey is an array of objects created on client side" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataType=\"value\"", Value = "Indicates that d-dataKey is a primitive object created on client side" }); relatedTags.Add(new KeyValueVO() { Key = "d-attr-<name>", Value = "Value of object property d-dataProperty-<name>" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataProperty-<name>-name", Value = "Name of a property inside object defined by d-dataType" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataProperty-<name>-value", Value = "Value of a property inside object defined by d-dataType" }); } else if (key == "d-attr-<name>") { relatedTags.Add(new KeyValueVO() { Key = "d-dataKey", Value = "Data identifier" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataType=\"object\"", Value = "Indicates that d-dataKey is a object created on client side" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataType=\"array\"", Value = "Indicates that d-dataKey is an array of objects created on client side" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataType=\"value\"", Value = "Indicates that d-dataKey is a primitive object created on client side" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataProperty-<name>", Value = "Name of a property inside object defined by d-dataType" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataProperty-<name>-name", Value = "Name of a property inside object defined by d-dataType" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataProperty-<name>-value", Value = "Value of a property inside object defined by d-dataType" }); } else if (key == "d-dataProperty-<name>-name") { relatedTags.Add(new KeyValueVO() { Key = "d-dataKey", Value = "Data identifier" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataType=\"object\"", Value = "Indicates that d-dataKey is a object created on client side" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataType=\"array\"", Value = "Indicates that d-dataKey is an array of objects created on client side" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataType=\"value\"", Value = "Indicates that d-dataKey is a primitive object created on client side" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataProperty-<name>", Value = "Name of a property inside object defined by d-dataType" }); relatedTags.Add(new KeyValueVO() { Key = "d-attr-<name>", Value = "Value of object property d-dataProperty-<name>" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataProperty-<name>-value", Value = "Value of a property inside object defined by d-dataType" }); } else if (key == "d-dataProperty-<name>-value") { relatedTags.Add(new KeyValueVO() { Key = "d-dataKey", Value = "Data identifier" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataType=\"object\"", Value = "Indicates that d-dataKey is a object created on client side" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataType=\"array\"", Value = "Indicates that d-dataKey is an array of objects created on client side" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataType=\"value\"", Value = "Indicates that d-dataKey is a primitive object created on client side" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataProperty-<name>", Value = "Name of a property inside object defined by d-dataType" }); relatedTags.Add(new KeyValueVO() { Key = "d-attr-<name>", Value = "Value of object property d-dataProperty-<name>" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataProperty-<name>-name", Value = "Name of a property inside object defined by d-dataType" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataLazy", Value = "When set to true, data will be loaded in increments" }); } else if (key == "d-dataLazy") { relatedTags.Add(new KeyValueVO() { Key = "d-dataLazyStart", Value = "Start index of data item" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataLazyIncrement", Value = "Quantity of data items to be loaded at each increment" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataDelay", Value = "When set to true, loads properties individually instead of the whole object" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataUnitOfWork", Value = "When set to true, d-dataKey object will be treated as DataSet" }); } else if (key == "d-dataLazyStart") { relatedTags.Add(new KeyValueVO() { Key = "d-dataLazy", Value = "When set to true, data will be loaded in increments" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataLazyIncrement", Value = "Quantity of data items to be loaded at each increment" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataDelay", Value = "When set to true, loads properties individually instead of the whole object" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataUnitOfWork", Value = "When set to true, d-dataKey object will be treated as DataSet" }); } else if (key == "d-dataLazyIncrement") { relatedTags.Add(new KeyValueVO() { Key = "d-dataLazy", Value = "When set to true, data will be loaded in increments" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataLazyStart", Value = "Start index of data item" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataDelay", Value = "When set to true, loads properties individually instead of the whole object" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataUnitOfWork", Value = "When set to true, d-dataKey object will be treated as DataSet" }); } else if (key == "d-dataDelay") { relatedTags.Add(new KeyValueVO() { Key = "d-dataLazy", Value = "When set to true, data will be loaded in increments" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataLazyStart", Value = "Start index of data item" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataLazyIncrement", Value = "Quantity of data items to be loaded at each increment" }); relatedTags.Add(new KeyValueVO() { Key = "d-dataUnitOfWork", Value = "When set to true, d-dataKey object will be treated as DataSet" }); } else if (key == "d-dataUnitOfWork") { relatedTags.Add(new KeyValueVO() { Key = "d-dataKey", Value = "Data identifier" }); } else if (key == "d-for") { relatedTags.Add(new KeyValueVO() { Key = "d-if", Value = "Same behavior as \"if\"" }); } else if (key == "d-if") { relatedTags.Add(new KeyValueVO() { Key = "d-for", Value = "Same behavior as \"foreach\"" }); } else if (key == "d-dataConfigGet") { relatedTags.Add(new KeyValueVO() { Key = "d-dataCookieGet", Value = "Object to access cookie items" }); } else if (key == "d-dataCookieGet") { relatedTags.Add(new KeyValueVO() { Key = "d-dataConfigGet", Value = "Object to access configuration items" }); } return relatedTags; } [HttpGet] public KeyValueVO GetSelectedTag() { KeyValueVO selectedTag = new KeyValueVO() { Key = "d-on-click", Value = "Functions to be called by OnClick events" }; return selectedTag; } } } <|start_filename|>src/Test/WebDrapo.Test/Pages/PropertiesSameTag.Test.html<|end_filename|> <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> <meta charset="utf-8" /> <script src="/drapo.js"></script> <title>Properties - Same Tag</title> </head> <body> <div d-datakey="users" d-dataurlget="/Data/GetLevels?Levels=0"></div> <div d-for="user in users" style="display: none;"> <span><b>Key: {{user.Key}}</b> - Value: {{user.Value}}</span> </div><div> <span><b>Key: L0K0</b> - Value: L0V0</span> </div><div> <span><b>Key: L0K1</b> - Value: L0V1</span> </div><div> <span><b>Key: L0K2</b> - Value: L0V2</span> </div><div> <span><b>Key: L0K3</b> - Value: L0V3</span> </div><div> <span><b>Key: L0K4</b> - Value: L0V4</span> </div> </body></html> <|start_filename|>src/Middleware/Drapo/Pipe/DrapoPipeAudienceType.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; namespace Sysphera.Middleware.Drapo.Pipe { public enum DrapoPipeAudienceType { Others, Me, Everyone } } <|start_filename|>src/Middleware/Drapo/User/DrapoUserConfig.cs<|end_filename|> using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Sysphera.Middleware.Drapo.User { public class DrapoUserConfig : IDrapoUserConfig { private DrapoMiddlewareOptions _options; private IHttpContextAccessor _context; public DrapoUserConfig(DrapoMiddlewareOptions options, IHttpContextAccessor context) { this._options = options; this._context = context; } public Task Ensure(Dictionary<string, string> values) { Dictionary<string, string> valuesBefore = this.Extract(); Dictionary<string, string> valuesJoin = this.Join(valuesBefore, values); CookieOptions option = new CookieOptions(); option.Expires = new DateTimeOffset(new DateTime(2980, 06, 03)); string value = this.CreateCookieValue(valuesJoin); this._context.HttpContext.Response.Cookies.Append(this._options.Config.CookieName, value, option); return (Task.CompletedTask); } private Dictionary<string, string> Extract() { if (!this._context.HttpContext.Request.Cookies.ContainsKey(this._options.Config.CookieName)) return (null); string value = this._context.HttpContext.Request.Cookies[this._options.Config.CookieName]; return (this.CreateValues(value)); } private Dictionary<string, string> Join(Dictionary<string, string> values1, Dictionary<string, string> values2) { if (values1 == null) return (values2); if (values2 == null) return (values1); foreach (KeyValuePair<string, string> entry in values2) { if (values1.ContainsKey(entry.Key)) values1[entry.Key] = entry.Value; else values1.Add(entry.Key,entry.Value); } return (values1); } private string CreateCookieValue(Dictionary<string, string> values) { StringBuilder builder = new StringBuilder(); foreach (KeyValuePair<string, string> entry in values) { if (builder.Length > 0) builder.Append("&"); builder.Append($"{entry.Key}={entry.Value}"); } return (builder.ToString()); } private Dictionary<string, string> CreateValues(string value) { Dictionary<string, string> values = new Dictionary<string, string>(); string[] valuesSplit = value.Split("&"); foreach (string valueSplit in valuesSplit) { if (string.IsNullOrEmpty(valueSplit)) continue; string[] keyValue = valueSplit.Split("="); if (keyValue.Length != 2) continue; values.Add(keyValue[0], keyValue[1]); } return (values); } } } <|start_filename|>src/Web/WebDrapo/Model/TabsVM.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebDrapo.Model { public class TabsVM { public List<TabVM> Tabs { set; get; } public int TabIndex { set; get; } public TabsVM() { this.Tabs = new List<TabVM>(); } } } <|start_filename|>src/Web/WebDrapo/wwwroot/components/state/state.css<|end_filename|> .state { } <|start_filename|>src/Web/WebDrapo/wwwroot/DrapoPages/ControlFlowForDictionary.html<|end_filename|> <!DOCTYPE html> <html> <head> <script src="/drapo.js"></script> <title>Control Flow - Dictionary</title> </head> <body> <span>Control Flow - Dictionary</span> <div d-dataKey="dictionary" d-dataUrlGet="/Data/GetDictionary"></div> <div d-for="entry in dictionary"> <br> <span>Key: {{entry.Key}}</span><br> <div d-for="value in entry.Value"> <span>Value.Key: {{value.Key}}</span><br> <span>Value.Value: {{value.Value}}</span><br> </div> </div> </body> </html> <|start_filename|>src/Test/WebDrapo.Test/Pages/ControlFlowForRecursiveIndexRelative.Test.html<|end_filename|> <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> <script src="/drapo.js"></script> <title>Control Flow - For - Index Relative</title> </head> <body> <span>Control Flow - For - Index Relative</span> <div d-datakey="users" d-dataurlget="/Data/GetLevels?Levels=3&amp;Children=3"></div> <div d-for="user in users" style="display: none;"> <br /> <span>Key: {{user.Key}}</span><br /> <span>Value: {{user.Value}}</span><br /> <span>Index Relative: {{user._IndexRelative}}</span><br /> <span>Children</span> <br /> <div d-for="user in user.Children"></div> </div><div> <br /> <span>Key: L3K0</span><br /> <span>Value: L3V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L2K0</span><br /> <span>Value: L2V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L1K0</span><br /> <span>Value: L1V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K2</span><br /> <span>Value: L0V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> </div> </div><div> <br /> <span>Key: L1K1</span><br /> <span>Value: L1V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K2</span><br /> <span>Value: L0V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> </div> </div><div> <br /> <span>Key: L1K2</span><br /> <span>Value: L1V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K2</span><br /> <span>Value: L0V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> </div> </div> </div><div> <br /> <span>Key: L2K1</span><br /> <span>Value: L2V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L1K0</span><br /> <span>Value: L1V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K2</span><br /> <span>Value: L0V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> </div> </div><div> <br /> <span>Key: L1K1</span><br /> <span>Value: L1V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K2</span><br /> <span>Value: L0V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> </div> </div><div> <br /> <span>Key: L1K2</span><br /> <span>Value: L1V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K2</span><br /> <span>Value: L0V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> </div> </div> </div><div> <br /> <span>Key: L2K2</span><br /> <span>Value: L2V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L1K0</span><br /> <span>Value: L1V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K2</span><br /> <span>Value: L0V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> </div> </div><div> <br /> <span>Key: L1K1</span><br /> <span>Value: L1V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K2</span><br /> <span>Value: L0V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> </div> </div><div> <br /> <span>Key: L1K2</span><br /> <span>Value: L1V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K2</span><br /> <span>Value: L0V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> </div> </div> </div> </div><div> <br /> <span>Key: L3K1</span><br /> <span>Value: L3V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L2K0</span><br /> <span>Value: L2V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L1K0</span><br /> <span>Value: L1V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K2</span><br /> <span>Value: L0V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> </div> </div><div> <br /> <span>Key: L1K1</span><br /> <span>Value: L1V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K2</span><br /> <span>Value: L0V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> </div> </div><div> <br /> <span>Key: L1K2</span><br /> <span>Value: L1V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K2</span><br /> <span>Value: L0V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> </div> </div> </div><div> <br /> <span>Key: L2K1</span><br /> <span>Value: L2V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L1K0</span><br /> <span>Value: L1V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K2</span><br /> <span>Value: L0V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> </div> </div><div> <br /> <span>Key: L1K1</span><br /> <span>Value: L1V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K2</span><br /> <span>Value: L0V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> </div> </div><div> <br /> <span>Key: L1K2</span><br /> <span>Value: L1V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K2</span><br /> <span>Value: L0V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> </div> </div> </div><div> <br /> <span>Key: L2K2</span><br /> <span>Value: L2V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L1K0</span><br /> <span>Value: L1V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K2</span><br /> <span>Value: L0V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> </div> </div><div> <br /> <span>Key: L1K1</span><br /> <span>Value: L1V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K2</span><br /> <span>Value: L0V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> </div> </div><div> <br /> <span>Key: L1K2</span><br /> <span>Value: L1V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K2</span><br /> <span>Value: L0V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> </div> </div> </div> </div><div> <br /> <span>Key: L3K2</span><br /> <span>Value: L3V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L2K0</span><br /> <span>Value: L2V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L1K0</span><br /> <span>Value: L1V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K2</span><br /> <span>Value: L0V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> </div> </div><div> <br /> <span>Key: L1K1</span><br /> <span>Value: L1V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K2</span><br /> <span>Value: L0V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> </div> </div><div> <br /> <span>Key: L1K2</span><br /> <span>Value: L1V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K2</span><br /> <span>Value: L0V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> </div> </div> </div><div> <br /> <span>Key: L2K1</span><br /> <span>Value: L2V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L1K0</span><br /> <span>Value: L1V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K2</span><br /> <span>Value: L0V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> </div> </div><div> <br /> <span>Key: L1K1</span><br /> <span>Value: L1V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K2</span><br /> <span>Value: L0V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> </div> </div><div> <br /> <span>Key: L1K2</span><br /> <span>Value: L1V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K2</span><br /> <span>Value: L0V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> </div> </div> </div><div> <br /> <span>Key: L2K2</span><br /> <span>Value: L2V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L1K0</span><br /> <span>Value: L1V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K2</span><br /> <span>Value: L0V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> </div> </div><div> <br /> <span>Key: L1K1</span><br /> <span>Value: L1V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K2</span><br /> <span>Value: L0V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> </div> </div><div> <br /> <span>Key: L1K2</span><br /> <span>Value: L1V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> <div> <br /> <span>Key: L0K0</span><br /> <span>Value: L0V0</span><br /> <span>Index Relative: 0</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K1</span><br /> <span>Value: L0V1</span><br /> <span>Index Relative: 1</span><br /> <span>Children</span> <br /> </div><div> <br /> <span>Key: L0K2</span><br /> <span>Value: L0V2</span><br /> <span>Index Relative: 2</span><br /> <span>Children</span> <br /> </div> </div> </div> </div> </body></html> <|start_filename|>src/Middleware/Drapo/DrapoDynamicResponse.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; namespace Sysphera.Middleware.Drapo { public class DrapoDynamicResponse { public string Content { set; get; } public bool IsContext { set; get; } public DateTime LastModified { set; get; } public int? Status { set; get; } public Dictionary<string, string> Headers { set; get; } } } <|start_filename|>src/Middleware/Drapo/DrapoUnitOfWork.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; namespace Sysphera.Middleware.Drapo { public class DrapoUnitOfWork<T> { public List<T> Inserted { set; get; } public List<T> Updated { set; get; } public List<T> Deleted { set; get; } public List<T> Entities { set; get; } } } <|start_filename|>src/Web/WebDrapo/Controllers/ServerController.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace WebDrapo.Controllers { [AllowAnonymous] public class ServerController : Controller { [HttpGet] public ActionResult Redirect() { ContentResult content = new ContentResult(); content.StatusCode = 204; Response.Headers.Add("Location", "~/DrapoPages/ServerResponseRedirected.html"); return (content); } public ActionResult GetNoCache([FromQuery] string value) { string content = $"<div><span>{value}</span></div>"; this.Response.Headers.Add("cache-control", "no-store"); return (Ok(content)); } } } <|start_filename|>src/Web/WebDrapo/wwwroot/components/labelinputsubscribemustache/labelinputsubscribemustache.css<|end_filename|> .labelinputsubscribe { } .labelinputsubscribe > span { color: green; } .labelinputsubscribe > input { color: red; } .labelinputsubscribe > input:focus { background-color : black; } <|start_filename|>src/Middleware/Drapo/components/debugger/debugger.js<|end_filename|> function debuggerConstructor(el, app) { } <|start_filename|>src/Web/WebDrapo/Model/MenuItemVM.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebDrapo.Model { public class MenuItemVM { public string Name { set; get; } public string Type { set; get; } public string TypeImageClass { set; get; } public string Action { set; get; } public string Activated { set; get; } public string Url { set; get; } public bool Selected { set; get; } } } <|start_filename|>src/Test/WebDrapo.Test/Pages/ControlFlowForObject.Test.html<|end_filename|> <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> <script src="/drapo.js"></script> <title>Drapo For</title> </head> <body> <h1><span>For Object</span></h1> <div d-datakey="objects" d-dataurlget="/Culture/GetResourcesPT"></div> <ul> <li d-for="object in objects" style="display: none;">{{object.Key}} - {{object.Value}}</li><li>0 - 0</li><li>1 - 1</li><li>2 - 2</li><li>3 - 3</li><li>4 - 4</li><li>5 - 5</li><li>6 - 6</li><li>7 - 7</li><li>8 - 8</li><li>9 - 9</li><li>User - Usuário</li><li>Name - Nome</li><li>Date - Data</li> </ul> </body></html> <|start_filename|>src/Web/WebDrapo/Model/ObjectComplexVM.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebDrapo.Model { public class ObjectComplexVM { public string Name { set; get; } public Dictionary<string,string> Properties { set; get; } public ObjectComplexVM Child { set; get;} public ObjectComplexVM() { this.Properties = new Dictionary<string, string>(); } } } <|start_filename|>src/Middleware/Drapo/DrapoFile.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; namespace Sysphera.Middleware.Drapo { public class DrapoFile { public string Key { set; get; } public bool Exists { set; get; } public string Path { set; get; } public string ETag { set; get; } public string LastModified { set; get; } public string ContentData { set; get; } } } <|start_filename|>src/Web/WebDrapo/Views/Home/Index.cshtml<|end_filename|> <div> <div class="row"> <div class="col-sm-2 col-sm-push-4"> <h1>Drapo Live Demo</h1> <img src="https://powerplanning.visualstudio.com/_apis/public/build/definitions/9a8d97bc-da81-44f5-9988-e2a03c19cdcf/2/badge" /> </div> </div> <hr /> <div class="row"> <div class="col-sm-2 col-sm-push-4"> <h2>sectors</h2> </div> </div> <div class="row"> <div class="col-sm-3"> <h3><a href="~/DrapoPages/PageSimple.html">Simple</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/PageMasterMaster.html">Master</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/PageMasterChild.html">Child</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/PageMasterGrandChild.html">Grand Child</a></h3> </div> </div> <hr /> <div class="row"> <div class="col-sm-2 col-sm-push-4"> <h2>data</h2> </div> </div> <div class="row"> <div class="col-sm-3"> <h3><a href="~/DrapoPages/DataSimpleLoad.html">Simple</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/DataFullLoad.html">Large</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/DataIncrementalLoad.html">Incremental</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/DataValue.html">Value</a></h3> </div> </div> <hr /> <div class="row"> <div class="col-sm-2 col-sm-push-4"> <h2>d-for</h2> </div> </div> <div class="row"> <div class="col-sm-3"> <h3><a href="~/DrapoPages/ControlFlowForUl.html">UL</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/ControlFlowForSelect.html">Select</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/ControlFlowForNested.html">Nested</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/ControlFlowForRecursive.html">Recursive</a></h3> </div> </div> <div class="row"> <div class="col-sm-3"> <h3><a href="~/DrapoPages/ControlFlowForArray.html">Array</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/ControlFlowForJson.html">Json</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/ControlFlowForRecursiveIF.html">Recursive IF</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/ControlFlowForRecursiveIndex.html">Recursive Index</a></h3> </div> </div> <div class="row"> <div class="col-sm-3"> <h3><a href="~/DrapoPages/ControlFlowForRecursiveLevel.html">Recursive Level</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/ControlFlowForRecursiveIndexRelative.html">Recursive Index Relative</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/ControlFlowForMustacheInsideFor.html">Mustache Inside For</a></h3> </div> <div class="col-sm-3"> </div> </div> <hr /> <div class="row"> <div class="col-sm-2 col-sm-push-4"> <h2>d-if</h2> </div> </div> <div class="row"> <div class="col-sm-3"> <h3><a href="~/DrapoPages/ControlFlowIfUl.html">UL</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/ControlFlowIfSelect.html">Select</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/ControlFlowIfObject.html">Object</a></h3> </div> </div> <hr /> <div class="row"> <div class="col-sm-2 col-sm-push-4"> <h2>d-model</h2> </div> </div> <div class="row"> <div class="col-sm-2"> <h3><a href="~/DrapoPages/ControlFlowModelInputCheckbox.html">Checkbox</a></h3> </div> <div class="col-sm-2"> <h3><a href="~/DrapoPages/ControlFlowModelSelect.html">Select</a></h3> </div> <div class="col-sm-2"> <h3><a href="~/DrapoPages/ControlFlowModelInputText.html">Text</a></h3> </div> <div class="col-sm-2"> <h3><a href="~/DrapoPages/ControlFlowModelTextArea.html">TextArea</a></h3> </div> <div class="col-sm-2"> <h3><a href="~/DrapoPages/ControlFlowModelInputPassword.html">Password</a></h3> </div> </div> <div class="row"> <div class="col-sm-2"> <h3><a href="~/DrapoPages/MustacheNull.html">Mustache Null</a></h3> </div> <div class="col-sm-2"> <h3><a href="~/DrapoPages/ModelObject.html">Model Object</a></h3> </div> <div class="col-sm-2"> </div> <div class="col-sm-2"> </div> <div class="col-sm-2"> </div> </div> <hr /> <div class="row"> <div class="col-sm-2 col-sm-push-4"> <h2>d-attr-</h2> </div> </div> <div class="row"> <div class="col-sm-3"> <h3><a href="~/DrapoPages/Attribute.html">Simple</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/ControlFlowForAttribute.html">For</a></h3> </div> </div> <hr /> <div class="row"> <div class="col-sm-2 col-sm-push-4"> <h2>route</h2> </div> </div> <div class="row"> <div class="col-sm-3"> <h3><a href="~/DrapoPages/RouterMaster.html">Route Master</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/RouterOne.html">Router One</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/RouterTwo.html">Router Two</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/RouterThree.html">Router Three</a></h3> </div> </div> <hr /> <div class="row"> <div class="col-sm-2 col-sm-push-4"> <h2>events</h2> </div> </div> <div class="row"> <div class="col-sm-3"> <h3><a href="~/DrapoPages/EventClickContext.html">Click Context</a></h3> </div> </div> <hr /> <div class="row"> <div class="col-sm-2 col-sm-push-4"> <h2>functions</h2> </div> </div> <div class="row"> <div class="col-sm-3"> <h3><a href="~/DrapoPages/FunctionPostDataItem.html">PostDataItem</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/FunctionIF.html">IF</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/FunctionUpdateDataField.html">UpdateDataField</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/FunctionFocus.html">Focus</a></h3> </div> </div> <div class="row"> <div class="col-sm-3"> <h3><a href="~/DrapoPages/FunctionContainsDataItem.html">ContainsDataItem</a></h3> </div> <div class="col-sm-3"> </div> <div class="col-sm-3"> </div> <div class="col-sm-3"> </div> </div> <hr /> <div class="row"> <div class="col-sm-2 col-sm-push-4"> <h2>custom</h2> </div> </div> <div class="row"> <div class="col-sm-3"> <h3><a href="~/DrapoPages/Themes.html">Themes</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/Views.html">Views</a></h3> </div> </div> <hr /> <div class="row"> <div class="col-sm-2 col-sm-push-4"> <h2>components</h2> </div> </div> <div class="row"> <div class="col-sm-3"> <h3><a href="~/DrapoPages/ComponentMenuApplicationHtml.html">MenuApplication html</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/ComponentMenuApplicationComponent.html">MenuApplicationcomponent</a></h3> </div> </div> <hr /> <div class="row"> <div class="col-sm-2 col-sm-push-4"> <h2>security</h2> </div> </div> <div class="row"> <div class="col-sm-3"> <h3><a href="~/DrapoPages/Authentication.html">Authentication</a></h3> </div> </div> <hr /> <div class="row"> <div class="col-sm-2 col-sm-push-4"> <h2>samples</h2> </div> </div> <div class="row"> <div class="col-sm-3"> <h3><a href="~/DrapoPages/Culture.html">Culture</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/Chat.html">Chat</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/Todo.html">Todo</a></h3> </div> <div class="col-sm-3"> <h3><a href="~/DrapoPages/PropertiesSameTag.html">PropertiesSameTag</a></h3> </div> </div> <hr /> </div> <|start_filename|>src/Middleware/Drapo/js/DrapoLinkedTable.js<|end_filename|> "use strict"; var DrapoLinkedTable = (function () { function DrapoLinkedTable() { this._head = null; } DrapoLinkedTable.prototype.AddOrUpdate = function (row, column, value) { if (this._head === null) { this._head = new DrapoLinkedTableNode(); this._head.Row = row; this._head.Column = column; } var node = this._head; var nodeRowPrevious = null; var isEnd = false; while (node.Row !== row) { nodeRowPrevious = node; if ((isEnd = (node.NextRow === null)) || (node.NextRow.Row > row)) { var nodeRow = new DrapoLinkedTableNode(); nodeRow.Row = row; nodeRow.Column = column; if ((isEnd) && (node.Row < row)) { node.NextRow = nodeRow; } else if (node === this._head) { nodeRow.NextRow = node; this._head = nodeRow; } else { nodeRow.NextRow = node.NextRow; node.NextRow = nodeRow; } node = nodeRow; } else { node = node.NextRow; } } var nodeRowHead = node; while (node.Column !== column) { if ((isEnd = (node.NextCell === null)) || (node.NextCell.Column > column)) { var nodeCell = new DrapoLinkedTableNode(); nodeCell.Row = row; nodeCell.Column = column; if ((isEnd) && (node.Column < column)) { node.NextCell = nodeCell; } else if (node === nodeRowHead) { nodeCell.NextCell = node; if (nodeRowHead.Row !== nodeRowPrevious.Row) nodeRowPrevious.NextRow = nodeCell; } else { nodeCell.NextCell = node.NextCell; node.NextCell = nodeCell; } node = nodeCell; } else { node = node.NextCell; } } node.Value = value; }; DrapoLinkedTable.prototype.Get = function (row, column) { var node = this._head; while (node !== null) { if (node.Row < row) { node = node.NextRow; } else if (node.Row > row) { return (null); } else if (node.Row === row) { if (node.Column < column) node = node.NextCell; else if (node.Column > column) return (null); else return (node.Value); } } return (null); }; DrapoLinkedTable.prototype.GetHead = function () { return (this._head); }; DrapoLinkedTable.prototype.Delete = function (row, column) { }; return DrapoLinkedTable; }()); <|start_filename|>src/Web/WebDrapo/Model/DateObjectVM.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebDrapo.Model { public class DateObjectVM { public Object Value { set; get; } public string Format { set; get; } public string Tag { set; get; } public string Culture { set; get; } } } <|start_filename|>src/Web/WebDrapo/wwwroot/css/themes.light.css<|end_filename|> body { background-color: lightgray; } .background { background-color: yellow; } <|start_filename|>src/Web/WebDrapo/wwwroot/components/linkedcube/linkedcube.js<|end_filename|> var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; function linkedcubeConstructor(el, app) { return __awaiter(this, void 0, void 0, function () { var instance; return __generator(this, function (_a) { switch (_a.label) { case 0: instance = new LinkedCube(el, app); return [4, instance.Initalize()]; case 1: _a.sent(); return [2, (instance)]; } }); }); } var LinkedCube = (function () { function LinkedCube(el, app) { this._el = null; this._cube = null; this._el = el; this._app = app; } LinkedCube.prototype.Initalize = function () { return __awaiter(this, void 0, void 0, function () { var type; return __generator(this, function (_a) { switch (_a.label) { case 0: this._cube = new DrapoLinkedCube(); type = this._el.getAttribute('dc-type'); if (!(type === 'add')) return [3, 10]; return [4, this.Add('p1', 'r1', 'c1', 'v1')]; case 1: _a.sent(); return [4, this.Add('p1', 'r2', 'c1', 'v2')]; case 2: _a.sent(); return [4, this.Add('p1', 'r2', 'c2', 'v3')]; case 3: _a.sent(); return [4, this.Add('p1', 'r1', 'c3', 'v4')]; case 4: _a.sent(); return [4, this.Add('p2', 'r2', 'c1', 'v5')]; case 5: _a.sent(); return [4, this.Add('p3', 'r1', 'c1', 'v6')]; case 6: _a.sent(); return [4, this.Add('p2', 'r1', 'c1', 'v7')]; case 7: _a.sent(); return [4, this.Add('p2', 'r1', 'c2', 'v8')]; case 8: _a.sent(); return [4, this.Add('p0', 'r1', 'c1', 'v9')]; case 9: _a.sent(); return [3, 23]; case 10: if (!(type === 'remove')) return [3, 23]; return [4, this.Add('p1', 'r1', 'c1', 'v1')]; case 11: _a.sent(); return [4, this.Add('p1', 'r2', 'c1', 'v2')]; case 12: _a.sent(); return [4, this.Add('p1', 'r2', 'c2', 'v3')]; case 13: _a.sent(); return [4, this.Add('p1', 'r1', 'c3', 'v4')]; case 14: _a.sent(); return [4, this.Add('p2', 'r2', 'c1', 'v5')]; case 15: _a.sent(); return [4, this.Add('p3', 'r1', 'c1', 'v6')]; case 16: _a.sent(); return [4, this.Add('p2', 'r1', 'c1', 'v7')]; case 17: _a.sent(); return [4, this.Add('p2', 'r1', 'c2', 'v8')]; case 18: _a.sent(); return [4, this.Add('p0', 'r1', 'c1', 'v9')]; case 19: _a.sent(); return [4, this.Remove('p2', '', '')]; case 20: _a.sent(); return [4, this.Remove('p1', 'r2', 'c1')]; case 21: _a.sent(); return [4, this.Remove('p0', 'r1', '')]; case 22: _a.sent(); _a.label = 23; case 23: return [2]; } }); }); }; LinkedCube.prototype.GetElementCube = function () { return this._el.children[2]; }; LinkedCube.prototype.Add = function (page, row, column, value) { return __awaiter(this, void 0, void 0, function () { var context; return __generator(this, function (_a) { switch (_a.label) { case 0: context = [page, row, column]; this._cube.AddOrUpdate(context, value); return [4, this.Render()]; case 1: _a.sent(); return [2]; } }); }); }; LinkedCube.prototype.Clear = function () { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { this._cube.Clear(); this.Render(); return [2]; }); }); }; LinkedCube.prototype.Remove = function (page, row, column) { return __awaiter(this, void 0, void 0, function () { var context; return __generator(this, function (_a) { switch (_a.label) { case 0: context = []; if (page != '') context.push(page); if (row != '') context.push(row); if (column != '') context.push(column); this._cube.Remove(context); return [4, this.Render()]; case 1: _a.sent(); return [2]; } }); }); }; LinkedCube.prototype.Render = function () { return __awaiter(this, void 0, void 0, function () { var elCube, fragment, node; return __generator(this, function (_a) { elCube = this.GetElementCube(); while (elCube.children.length > 0) elCube.removeChild(elCube.children[0]); fragment = document.createDocumentFragment(); node = this._cube.GetHead(); this.InsertNodeElement(fragment, node, null, 0, 0); elCube.appendChild(fragment); return [2]; }); }); }; LinkedCube.prototype.InsertNodeElement = function (fragment, node, nodePrevious, index, identation) { var elDiv = document.createElement('div'); var elSpan = document.createElement('span'); elSpan.style.left = (identation * 20) + 'px'; elSpan.textContent = this.CreateNodeText(node, nodePrevious, index); if (this.HasError(node, nodePrevious, index)) elSpan.style.color = 'red'; else elSpan.style.color = 'green'; elDiv.appendChild(elSpan); fragment.appendChild(elDiv); if (node.Next === null) return; for (var i = node.Next.length - 1; i >= 0; i--) { var nodeNext = node.Next[i]; if (nodeNext === null) continue; this.InsertNodeElement(fragment, nodeNext, node, i, i); } }; LinkedCube.prototype.CreateNodeText = function (node, nodePrevious, index) { var text = '[' + this.CreateContextText(node.Context) + '] ' + node.Value; if (nodePrevious !== null) { text = text + ' : ' + index + ' <= (' + this.CreateContextText(nodePrevious.Context) + ')'; } return (text); }; LinkedCube.prototype.CreateContextText = function (context) { var text = ''; for (var i = 0; i < context.length; i++) { if (i > 0) text = text + ','; text = text + context[i]; } return (text); }; LinkedCube.prototype.HasError = function (node, nodePrevious, index) { if (nodePrevious === null) return (false); for (var i = 0; i < index; i++) { if (node.Context[i] !== nodePrevious.Context[i]) return (true); } return (false); }; return LinkedCube; }()); <|start_filename|>src/Web/WebDrapo/wwwroot/components/code/code.css<|end_filename|> .code { } <|start_filename|>src/Web/WebDrapo/Dockerfile<|end_filename|> FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 ARG source=. WORKDIR /app EXPOSE 9991 COPY ${source:-obj/Docker/publish} . ENTRYPOINT ["dotnet", "WebDrapo.dll"] <|start_filename|>src/Web/WebDrapo/Controllers/PlumberController.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Sysphera.Middleware.Drapo.Pipe; namespace WebDrapo.Controllers { [AllowAnonymous] public class PlumberController : Controller { private IDrapoPlumber _plumber; public PlumberController(IDrapoPlumber plumber) { this._plumber = plumber; } [HttpPost] public void Execute([FromBody] string expression) { _plumber.Send(new DrapoPipeMessage() {Type = DrapoPipeMessageType.Execute, Data = expression }, DrapoPipeAudienceType.Me); } [HttpGet] public async Task<long> GetCount() { return (await _plumber.Count()); } } } <|start_filename|>src/Middleware/Drapo/Pipe/DrapoPipeMessage.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; namespace Sysphera.Middleware.Drapo.Pipe { public class DrapoPipeMessage { private DrapoPipeMessageType _type = DrapoPipeMessageType.Storage; private string _data = null; public DrapoPipeMessageType Type { get => _type; set => _type = value; } public string Data { get => _data; set => _data = value; } } } <|start_filename|>src/Web/WebDrapo/Program.cs<|end_filename|> using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; namespace WebDrapo { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseUrls("http://0.0.0.0:9991"); webBuilder.UseContentRoot(Directory.GetCurrentDirectory()); webBuilder.ConfigureKestrel((content, options) => { }); webBuilder.UseIISIntegration(); webBuilder.ConfigureLogging((hostingContext, logging) => { //logging.AddConsole(); //logging.AddDebug(); }); webBuilder.UseStartup<Startup>(); }); } } <|start_filename|>src/Web/WebDrapo/wwwroot/DrapoPages/FunctionUpdateData.html<|end_filename|> <!DOCTYPE html> <html> <head> <script src="/drapo.js"></script> <title>Function - UpdateDataFieldLookup</title> </head> <body> <span>Function - UpdateDataFieldLookup</span> <div d-dataKey="data" d-dataUrlGet="/Data"></div> <div d-dataKey="dataCopy" d-dataType="object"></div> <div> <ul> <li d-for="item in data">{{item.Key}} - {{item.Value}}</li> </ul> </div> <div> <ul> <li d-for="item in dataCopy">{{item.Key}} - {{item.Value}}</li> </ul> </div> <br /> <div d-dataKey="loader" d-dataType="function" d-dataLoadType="startup" d-dataValue="UpdateData(dataCopy,{{data}})"></div> </body> </html> <|start_filename|>src/Middleware/Drapo/DrapoDynamicHandler.cs<|end_filename|> using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace Sysphera.Middleware.Drapo { public class DrapoDynamicHandler { public string Name { set; get; } public string Tag { set; get; } public string ContentType { set; get; } public bool UseTheme { set; get; } public bool UseView { set; get; } [IgnoreDataMember] public Func<DrapoDynamicRequest, Task<DrapoDynamicResponse>> Handler { set; get; } } } <|start_filename|>src/Web/WebDrapo/wwwroot/DrapoPages/ControlFlowForMustacheInsideFor.html<|end_filename|> <!DOCTYPE html> <html> <head> <script src="/drapo.js"></script> <title>Control Flow - For - Mustache Inside For</title> </head> <body> <span>Control Flow - For - Mustache Inside For</span> <div d-dataKey="entries" d-dataUrlGet="/Data/GetLevels?Levels=3&Children=2"></div> <div d-for="entry in entries"> <br> <div style="float:left"> <span d-for="level in (1..{{entry._Level}})">-</span> </div> <span>{{entry.Key}}</span> <div d-for="entry in entry.Children"></div> </div> </body> </html> <|start_filename|>src/Web/WebDrapo/wwwroot/components/labelInput/labelinput.css<|end_filename|> .labelinput { } .labelinput > span { color: green; } .labelinput > input { color: red; } <|start_filename|>src/Web/WebDrapo/Model/TabVM.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebDrapo.Model { public class TabVM { public string Name { set; get; } public List<KeyValueVO> Items { set; get; } } } <|start_filename|>src/Middleware/Drapo/js/DrapoExpressionItemType.js<|end_filename|> "use strict"; var DrapoExpressionItemType; (function (DrapoExpressionItemType) { DrapoExpressionItemType[DrapoExpressionItemType["Block"] = 0] = "Block"; DrapoExpressionItemType[DrapoExpressionItemType["Text"] = 1] = "Text"; DrapoExpressionItemType[DrapoExpressionItemType["Function"] = 2] = "Function"; DrapoExpressionItemType[DrapoExpressionItemType["Mustache"] = 3] = "Mustache"; DrapoExpressionItemType[DrapoExpressionItemType["Comparator"] = 4] = "Comparator"; DrapoExpressionItemType[DrapoExpressionItemType["Logical"] = 5] = "Logical"; DrapoExpressionItemType[DrapoExpressionItemType["Deny"] = 6] = "Deny"; DrapoExpressionItemType[DrapoExpressionItemType["Arithmetic"] = 7] = "Arithmetic"; })(DrapoExpressionItemType || (DrapoExpressionItemType = {})); <|start_filename|>src/Middleware/Drapo/Pipe/IDrapoPlumber.cs<|end_filename|> using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Sysphera.Middleware.Drapo.Pipe { public interface IDrapoPlumber { Task<bool> Send(DrapoPipeMessage message, DrapoPipeAudienceType recipient = DrapoPipeAudienceType.Others); Task<long> Count(); Task<bool> Identify(long identity); Task<List<DrapoConnection>> GetConnections(); bool CheckConnections(); } } <|start_filename|>src/Middleware/Drapo/tslint.json<|end_filename|> { "extends": "tslint:recommended", "rules": { "no-floating-promises": true, "variable-name": false, "quotemark": [ false, "single" ], "max-line-length": false, "comment-format": false, "curly": false, "one-line": false, "member-ordering": false, "eofline": false, "space-before-function-paren": false, "prefer-for-of": false, "prefer-const": true, "no-console": true, "semicolon": true, "no-empty": true, "no-conditional-assignment": false, "array-type": false, "no-trailing-whitespace": true, "no-var-keyword": true, "member-access": true, "trailing-comma": true, "no-bitwise": true, "no-reference": false, "arrow-parens": true, "whitespace": true, "one-variable-per-declaration": true, "no-angle-bracket-type-assertion": true, "forin": false, "triple-equals": false, "typedef-whitespace": true, "no-shadowed-variable": true, "no-string-literal": true, "ban-types": true, "object-literal-shorthand": true, "object-literal-sort-keys": true, "only-arrow-functions": true, "no-unused-expression" : true } } <|start_filename|>src/Middleware/Drapo/js/DrapoLinkedTableNode.js<|end_filename|> "use strict"; var DrapoLinkedTableNode = (function () { function DrapoLinkedTableNode() { this.Value = null; this.NextCell = null; this.NextRow = null; this.Row = null; this.Column = null; } return DrapoLinkedTableNode; }()); <|start_filename|>src/Web/WebDrapo/wwwroot/DrapoPages/ClassMustache.html<|end_filename|> <!DOCTYPE html> <html> <head> <script src="/drapo.js"></script> <title>Class Mustache</title> <style> .selected { background-color: red; } </style> </head> <body> <div> <span>Class Mustache</span> <div d-dataKey="selection" d-dataType="object" d-dataProperty-class="selected"></div> <ul> <li d-class="{{{selection.class}}}"> First </li> <li> Second </li> </ul> </div> </body> </html> <|start_filename|>src/Middleware/Drapo/js/DrapoStorageLinkType.js<|end_filename|> "use strict"; var DrapoStorageLinkType; (function (DrapoStorageLinkType) { DrapoStorageLinkType[DrapoStorageLinkType["Render"] = 0] = "Render"; DrapoStorageLinkType[DrapoStorageLinkType["RenderClass"] = 1] = "RenderClass"; DrapoStorageLinkType[DrapoStorageLinkType["Reload"] = 2] = "Reload"; DrapoStorageLinkType[DrapoStorageLinkType["Pointer"] = 3] = "Pointer"; })(DrapoStorageLinkType || (DrapoStorageLinkType = {})); <|start_filename|>src/Middleware/Drapo/Pipe/DrapoPlumber.cs<|end_filename|> using Microsoft.AspNetCore.SignalR; using Sysphera.Middleware.Drapo.Request; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sysphera.Middleware.Drapo.Pipe { public class DrapoPlumber : IDrapoPlumber { private readonly DrapoMiddlewareOptions _options; private readonly IDrapoRequestReader _requestReader; private readonly IHubContext<DrapoPlumberHub> _hub; private readonly IDrapoConnectionManager _connectionManager; public DrapoPlumber(DrapoMiddlewareOptions options, IDrapoRequestReader requestHeaderReader, IHubContext<DrapoPlumberHub> hub, IDrapoConnectionManager connectionManager) { this._options = options; this._requestReader = requestHeaderReader; this._hub = hub; _connectionManager = connectionManager; } public async Task<bool> Send(DrapoPipeMessage message, DrapoPipeAudienceType recipient) { IClientProxy proxy = this.GetRecipients(recipient); if (proxy == null) return (await Task.FromResult<bool>(false)); await proxy.SendAsync(this._options.Config.PipeActionNotify, message); return (await Task.FromResult<bool>(true)); } private IClientProxy GetRecipients(DrapoPipeAudienceType recipient) { string connectionId = this._requestReader.GetPipeHeaderConnectionId(); if (string.IsNullOrEmpty(connectionId)) return (null); DrapoConnection connection = _connectionManager.Get(_requestReader.GetDomain() ?? string.Empty, connectionId); if (connection == null) return (null); if (recipient == DrapoPipeAudienceType.Others) return (this._hub.Clients.GroupExcept(connection.Domain, new List<string>(){ connectionId })); else if (recipient == DrapoPipeAudienceType.Me) return (this._hub.Clients.Client(connectionId)); else if (recipient == DrapoPipeAudienceType.Everyone) return (this._hub.Clients.Group(connection.Domain)); return (null); } public async Task<long> Count() { return (await Task.FromResult<long>(_connectionManager.Count(_requestReader.GetDomain() ?? string.Empty))); } public async Task<bool> Identify(long identity) { string connectionId = this._requestReader.GetPipeHeaderConnectionId(); if (string.IsNullOrEmpty(connectionId)) return (false); bool updated = _connectionManager.Identify(_requestReader.GetDomain() ?? string.Empty, connectionId, identity); return (await Task.FromResult<bool>(updated)); } public async Task<List<DrapoConnection>> GetConnections() { List<DrapoConnection> connections = _connectionManager.GetAll(_requestReader.GetDomain() ?? string.Empty); return (await Task.FromResult<List<DrapoConnection>>(connections)); } public bool CheckConnections() { return (_connectionManager.Check()); } } } <|start_filename|>src/Middleware/Drapo/js/DrapoPipeMessageType.js<|end_filename|> "use strict"; var DrapoPipeMessageType; (function (DrapoPipeMessageType) { DrapoPipeMessageType[DrapoPipeMessageType["Register"] = 0] = "Register"; DrapoPipeMessageType[DrapoPipeMessageType["Storage"] = 1] = "Storage"; DrapoPipeMessageType[DrapoPipeMessageType["Execute"] = 2] = "Execute"; })(DrapoPipeMessageType || (DrapoPipeMessageType = {})); <|start_filename|>src/Web/WebDrapo/wwwroot/css/validation.css<|end_filename|> .cloak { display: none; } .validatorValid { display: none; } .validationUnchecked { display: none; } .validatorInvalid { }
heber-junior/drapo
<|start_filename|>Source/CSProfiling/Shiny/ShinyTools.c<|end_filename|> /* The MIT License Copyright (c) 2007-2010 <NAME> http://code.google.com/p/shinyprofiler/ 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. */ #include "ShinyTools.h" #if SHINY_PLATFORM == SHINY_PLATFORM_WIN32 #define WIN32_LEAN_AND_MEAN #include <windows.h> #elif SHINY_PLATFORM == SHINY_PLATFORM_POSIX #include <sys/time.h> #endif /*---------------------------------------------------------------------------*/ const ShinyTimeUnit* ShinyGetTimeUnit(float ticks) { static ShinyTimeUnit units[4] = { {0} }; if (units[0].tickFreq == 0) { /* auto initialize first time */ units[0].tickFreq = ShinyGetTickFreq() / 1.0f; units[0].invTickFreq = ShinyGetTickInvFreq() * 1.0f; units[0].suffix = "s"; units[1].tickFreq = ShinyGetTickFreq() / 1000.0f; units[1].invTickFreq = ShinyGetTickInvFreq() * 1000.0f; units[1].suffix = "ms"; units[2].tickFreq = ShinyGetTickFreq() / 1000000.0f; units[2].invTickFreq = ShinyGetTickInvFreq() * 1000000.0f; units[2].suffix = "us"; units[3].tickFreq = ShinyGetTickFreq() / 1000000000.0f; units[3].invTickFreq = ShinyGetTickInvFreq() * 1000000000.0f; units[3].suffix = "ns"; } if (units[0].tickFreq < ticks) return &units[0]; else if (units[1].tickFreq < ticks) return &units[1]; else if (units[2].tickFreq < ticks) return &units[2]; else return &units[3]; } /*---------------------------------------------------------------------------*/ #if SHINY_PLATFORM == SHINY_PLATFORM_WIN32 void ShinyGetTicks(shinytick_t *p) { QueryPerformanceCounter((LARGE_INTEGER*)(p)); } shinytick_t ShinyGetTickFreq(void) { static shinytick_t freq = 0; if (freq == 0) QueryPerformanceFrequency((LARGE_INTEGER*)(&freq)); return freq; } float ShinyGetTickInvFreq(void) { static float invfreq = 0; if (invfreq == 0) invfreq = 1.0f / ShinyGetTickFreq(); return invfreq; } /*---------------------------------------------------------------------------*/ #elif SHINY_PLATFORM == SHINY_PLATFORM_POSIX void ShinyGetTicks(shinytick_t *p) { struct timeval time; gettimeofday(&time, NULL); *p = time.tv_sec * 1000000 + time.tv_usec; } shinytick_t ShinyGetTickFreq(void) { return 1000000; } float ShinyGetTickInvFreq(void) { return 1.0f / 1000000.0f; } #endif <|start_filename|>Source/CSProfiling/Shiny/ShinyNodePool.h<|end_filename|> /* The MIT License Copyright (c) 2007-2010 <NAME> http://code.google.com/p/shinyprofiler/ 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. */ #ifndef SHINY_NODE_POOL_H #define SHINY_NODE_POOL_H #include "ShinyNode.h" #if SHINY_IS_COMPILED == TRUE #ifdef __cplusplus extern "C" { #endif /*---------------------------------------------------------------------------*/ typedef struct _ShinyNodePool { struct _ShinyNodePool* nextPool; ShinyNode *_nextItem; ShinyNode *endOfItems; ShinyNode _items[1]; } ShinyNodePool; /*---------------------------------------------------------------------------*/ SHINY_INLINE ShinyNode* ShinyNodePool_firstItem(ShinyNodePool *self) { return &(self->_items[0]); } SHINY_INLINE ShinyNode* ShinyNodePool_newItem(ShinyNodePool *self) { return self->_nextItem++; } ShinyNodePool* ShinyNodePool_create(uint32_t a_items); void ShinyNodePool_destroy(ShinyNodePool *self); uint32_t ShinyNodePool_memoryUsageChain(ShinyNodePool *first); #ifdef __cplusplus } /* end of extern "C" */ #endif #endif /* if SHINY_IS_COMPILED == TRUE */ #endif /* end of include guard */ <|start_filename|>Source/CSProfiling/Shiny/ShinyNode.c<|end_filename|> /* The MIT License Copyright (c) 2007-2010 <NAME> http://code.google.com/p/shinyprofiler/ 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. */ #include "ShinyNode.h" #include "ShinyZone.h" #include "ShinyNodeState.h" #include <memory.h> #if SHINY_IS_COMPILED == TRUE /*---------------------------------------------------------------------------*/ ShinyNode _ShinyNode_dummy = { /* _last = */ { 0, 0 }, /* zone = */ NULL, /* parent = */ NULL, /* nextSibling = */ NULL, /* firstChild = */ NULL, /* lastChild = */ NULL }; /*---------------------------------------------------------------------------*/ void ShinyNode_updateTree(ShinyNode* first, float a_damping) { ShinyNodeState *top = NULL; ShinyNode *node = first; for (;;) { do { top = ShinyNodeState_push(top, node); node = node->firstChild; } while (node); for (;;) { node = ShinyNodeState_finishAndGetNext(top, a_damping); top = ShinyNodeState_pop(top); if (node) break; else if (!top) return; } } } /*---------------------------------------------------------------------------*/ void ShinyNode_updateTreeClean(ShinyNode* first) { ShinyNodeState *top = NULL; ShinyNode *node = first; for (;;) { do { top = ShinyNodeState_push(top, node); node = node->firstChild; } while (node); for (;;) { node = ShinyNodeState_finishAndGetNextClean(top); top = ShinyNodeState_pop(top); if (node) break; else if (!top) return; } } } /*---------------------------------------------------------------------------*/ const ShinyNode* ShinyNode_findNextInTree(const ShinyNode* self) { if (self->firstChild) { return self->firstChild; } else if (self->nextSibling) { return self->nextSibling; } else { ShinyNode* pParent = self->parent; while (!ShinyNode_isRoot(pParent)) { if (pParent->nextSibling) return pParent->nextSibling; else pParent = pParent->parent; } return NULL; } } /*---------------------------------------------------------------------------*/ void ShinyNode_clear(ShinyNode* self) { memset(self, 0, sizeof(ShinyNode)); } /*---------------------------------------------------------------------------*/ void ShinyNode_enumerateNodes(const ShinyNode* a_node, void (*a_func)(const ShinyNode*)) { a_func(a_node); if (a_node->firstChild) ShinyNode_enumerateNodes(a_node->firstChild, a_func); if (a_node->nextSibling) ShinyNode_enumerateNodes(a_node->nextSibling, a_func); } #endif <|start_filename|>Source/CSProfiling/Shiny/ShinyConfig.h<|end_filename|> /* The MIT License Copyright (c) 2007-2010 <NAME> http://code.google.com/p/shinyprofiler/ 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. */ #ifndef SHINY_CONFIG_H #define SHINY_CONFIG_H /*---------------------------------------------------------------------------*/ /* SHINY_IS_COMPILED is the master on or off swith at compile time. Define it to TRUE or FALSE before including header Shiny.h or inside ShinyConfig.h. Default is TRUE. */ #ifndef SHINY_IS_COMPILED #define SHINY_IS_COMPILED TRUE #endif /* TODO: */ #ifndef SHINY_STATIC_LINK #define SHINY_STATIC_LINK TRUE #endif /* if SHINY_LOOKUP_RATE is defined to TRUE then Shiny will record the success of its hash function. This is useful for debugging. Default is FALSE. */ #ifndef SHINY_LOOKUP_RATE #define SHINY_LOOKUP_RATE FALSE #endif /* if SHINY_HAS_ENABLED is defined to TRUE then Shiny can be enabled and disabled at runtime. TODO: bla bla... */ #ifndef SHINY_HAS_ENABLED #define SHINY_HAS_ENABLED FALSE #endif /* TODO: */ #define SHINY_OUTPUT_MODE_FLAT 0x1 /* TODO: */ #define SHINY_OUTPUT_MODE_TREE 0x2 /* TODO: */ #define SHINY_OUTPUT_MODE_BOTH 0x3 /* TODO: */ #ifndef SHINY_OUTPUT_MODE #define SHINY_OUTPUT_MODE SHINY_OUTPUT_MODE_BOTH #endif #endif /* end of include guard */ <|start_filename|>Source/CSProfiling/Shiny/ShinyZone.h<|end_filename|> /* The MIT License Copyright (c) 2007-2010 <NAME> http://code.google.com/p/shinyprofiler/ 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. */ #ifndef SHINY_ZONE_H #define SHINY_ZONE_H #include "ShinyData.h" #include <memory.h> #if SHINY_IS_COMPILED == TRUE #ifdef __cplusplus extern "C" { #endif /*---------------------------------------------------------------------------*/ #define SHINY_ZONE_STATE_HIDDEN 0 #define SHINY_ZONE_STATE_INITIALIZED 1 #define SHINY_ZONE_STATE_UPDATING 2 /*---------------------------------------------------------------------------*/ typedef struct _ShinyZone { struct _ShinyZone* next; int _state; const char* name; ShinyData data; } ShinyZone; /*---------------------------------------------------------------------------*/ SHINY_INLINE void ShinyZone_init(ShinyZone *self, ShinyZone* a_prev) { self->_state = SHINY_ZONE_STATE_INITIALIZED; a_prev->next = self; } SHINY_INLINE void ShinyZone_uninit(ShinyZone *self) { self->_state = SHINY_ZONE_STATE_HIDDEN; self->next = NULL; } SHINY_API void ShinyZone_preUpdateChain(ShinyZone *first); SHINY_API void ShinyZone_updateChain(ShinyZone *first, float a_damping); SHINY_API void ShinyZone_updateChainClean(ShinyZone *first); SHINY_API void ShinyZone_resetChain(ShinyZone *first); SHINY_API ShinyZone* ShinyZone_sortChain(ShinyZone **first); SHINY_INLINE float ShinyZone_compare(ShinyZone *a, ShinyZone *b) { return a->data.selfTicks.avg - b->data.selfTicks.avg; } SHINY_API void ShinyZone_clear(ShinyZone* self); SHINY_API void ShinyZone_enumerateZones(const ShinyZone* a_zone, void (*a_func)(const ShinyZone*)); #ifdef __cplusplus } /* end of extern "C" */ template <class T> void ShinyZone_enumerateZones(const ShinyZone* a_zone, T* a_this, void (T::*a_func)(const ShinyZone*)) { (a_this->*a_func)(a_zone); if (a_zone->next) ShinyZone_enumerateZones(a_zone->next, a_this, a_func); } #endif /* end of c++ */ #endif /* if SHINY_IS_COMPILED == TRUE */ #endif /* end of include guard */ <|start_filename|>Source/CSProfiling/Shiny/ShinyVersion.h<|end_filename|> /* The MIT License Copyright (c) 2007-2010 <NAME> http://code.google.com/p/shinyprofiler/ 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. */ #ifndef SHINY_VERSION_H #define SHINY_VERSION_H /*---------------------------------------------------------------------------*/ #define SHINY_VERSION "2.6 RC1" #define SHINY_SHORTNAME "Shiny" #define SHINY_FULLNAME "Shiny Profiler" #define SHINY_COPYRIGHT "Copyright (C) 2007-2010 <NAME>" #define SHINY_DESCRIPTION "Shiny is a state of the art profiler designed to help finding bottlenecks in your project." #endif /* end of include guard */ <|start_filename|>Source/CSProfiling/Shiny/ShinyData.h<|end_filename|> /* The MIT License Copyright (c) 2007-2010 <NAME> http://code.google.com/p/shinyprofiler/ 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. */ #ifndef SHINY_DATA_H #define SHINY_DATA_H #include "ShinyPrereqs.h" #ifdef __cplusplus extern "C" { #endif /*---------------------------------------------------------------------------*/ typedef struct { uint32_t entryCount; shinytick_t selfTicks; } ShinyLastData; /*---------------------------------------------------------------------------*/ typedef struct { shinytick_t cur; float avg; } ShinyTickData; typedef struct { uint32_t cur; float avg; } ShinyCountData; typedef struct { ShinyCountData entryCount; ShinyTickData selfTicks; ShinyTickData childTicks; } ShinyData; SHINY_INLINE shinytick_t ShinyData_totalTicksCur(const ShinyData *self) { return self->selfTicks.cur + self->childTicks.cur; } SHINY_INLINE float ShinyData_totalTicksAvg(const ShinyData *self) { return self->selfTicks.avg + self->childTicks.avg; } SHINY_INLINE void ShinyData_computeAverage(ShinyData *self, float a_damping) { self->entryCount.avg = self->entryCount.cur + a_damping * (self->entryCount.avg - self->entryCount.cur); self->selfTicks.avg = self->selfTicks.cur + a_damping * (self->selfTicks.avg - self->selfTicks.cur); self->childTicks.avg = self->childTicks.cur + a_damping * (self->childTicks.avg - self->childTicks.cur); } SHINY_INLINE void ShinyData_copyAverage(ShinyData *self) { self->entryCount.avg = (float) self->entryCount.cur; self->selfTicks.avg = (float) self->selfTicks.cur; self->childTicks.avg = (float) self->childTicks.cur; } SHINY_INLINE void ShinyData_clearAll(ShinyData *self) { self->entryCount.cur = 0; self->entryCount.avg = 0; self->selfTicks.cur = 0; self->selfTicks.avg = 0; self->childTicks.cur = 0; self->childTicks.avg = 0; } SHINY_INLINE void ShinyData_clearCurrent(ShinyData *self) { self->entryCount.cur = 0; self->selfTicks.cur = 0; self->childTicks.cur = 0; } #ifdef __cplusplus } /* end of extern "C" */ #endif #endif /* end of include guard */ <|start_filename|>Source/CSProfiling/Shiny/ShinyZone.c<|end_filename|> /* The MIT License Copyright (c) 2007-2010 <NAME> http://code.google.com/p/shinyprofiler/ 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. */ #include "ShinyZone.h" #include <memory.h> #if SHINY_IS_COMPILED == TRUE /*---------------------------------------------------------------------------*/ void ShinyZone_preUpdateChain(ShinyZone *first) { ShinyZone* zone = first; while (zone) { ShinyData_clearCurrent(&(zone->data)); zone = zone->next; } } /*---------------------------------------------------------------------------*/ void ShinyZone_updateChain(ShinyZone *first, float a_damping) { ShinyZone* zone = first; do { ShinyData_computeAverage(&(zone->data), a_damping); zone = zone->next; } while (zone); } /*---------------------------------------------------------------------------*/ void ShinyZone_updateChainClean(ShinyZone *first) { ShinyZone* zone = first; do { ShinyData_copyAverage(&(zone->data)); zone = zone->next; } while (zone); } /*---------------------------------------------------------------------------*/ void ShinyZone_resetChain(ShinyZone *first) { ShinyZone* zone = first, *temp; do { zone->_state = SHINY_ZONE_STATE_HIDDEN; temp = zone->next; zone->next = NULL; zone = temp; } while (zone); } /*---------------------------------------------------------------------------*/ /* A Linked-List Memory Sort by <NAME> <EMAIL> http://www.alumni.caltech.edu/~pje/ Modified by <NAME> */ ShinyZone* ShinyZone_sortChain(ShinyZone **first) /* return ptr to last zone */ { ShinyZone *p = *first; unsigned base; unsigned long block_size; struct tape { ShinyZone *first, *last; unsigned long count; } tape[4]; /* Distribute the records alternately to tape[0] and tape[1]. */ tape[0].count = tape[1].count = 0L; tape[0].first = NULL; base = 0; while (p != NULL) { ShinyZone *next = p->next; p->next = tape[base].first; tape[base].first = p; tape[base].count++; p = next; base ^= 1; } /* If the list is empty or contains only a single record, then */ /* tape[1].count == 0L and this part is vacuous. */ for (base = 0, block_size = 1L; tape[base+1].count != 0L; base ^= 2, block_size <<= 1) { int dest; struct tape *tape0, *tape1; tape0 = tape + base; tape1 = tape + base + 1; dest = base ^ 2; tape[dest].count = tape[dest+1].count = 0; for (; tape0->count != 0; dest ^= 1) { unsigned long n0, n1; struct tape *output_tape = tape + dest; n0 = n1 = block_size; while (1) { ShinyZone *chosen_record; struct tape *chosen_tape; if (n0 == 0 || tape0->count == 0) { if (n1 == 0 || tape1->count == 0) break; chosen_tape = tape1; n1--; } else if (n1 == 0 || tape1->count == 0) { chosen_tape = tape0; n0--; } else if (ShinyZone_compare(tape1->first, tape0->first) > 0) { chosen_tape = tape1; n1--; } else { chosen_tape = tape0; n0--; } chosen_tape->count--; chosen_record = chosen_tape->first; chosen_tape->first = chosen_record->next; if (output_tape->count == 0) output_tape->first = chosen_record; else output_tape->last->next = chosen_record; output_tape->last = chosen_record; output_tape->count++; } } } if (tape[base].count > 1L) { ShinyZone* last = tape[base].last; *first = tape[base].first; last->next = NULL; return last; } else { return NULL; } } /*---------------------------------------------------------------------------*/ void ShinyZone_clear(ShinyZone* self) { memset(self, 0, sizeof(ShinyZone)); } /*---------------------------------------------------------------------------*/ void ShinyZone_enumerateZones(const ShinyZone* a_zone, void (*a_func)(const ShinyZone*)) { a_func(a_zone); if (a_zone->next) ShinyZone_enumerateZones(a_zone->next, a_func); } #endif
angelahnicole/ChilliSource_ParticleOpt
<|start_filename|>Framework/IJSVG/IJSVG/Source/Rendering/IJSVGRendering.h<|end_filename|> // // IJSVGRendering.h // IJSVGExample // // Created by <NAME> on 14/03/2019. // Copyright © 2019 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> typedef CGFloat (^IJSVGRenderingBackingScaleFactorHelper)(void); typedef NS_ENUM(NSInteger, IJSVGRenderQuality) { kIJSVGRenderQualityFullResolution, // slowest to render kIJSVGRenderQualityOptimized, // best of both worlds kIJSVGRenderQualityLow // fast rendering }; @interface IJSVGRendering : NSObject @end <|start_filename|>Framework/IJSVG/IJSVG/Source/Layers/IJSVGPatternLayer.h<|end_filename|> // // IJSVGPatternLayer.h // IJSVGExample // // Created by <NAME> on 07/01/2017. // Copyright © 2017 <NAME>. All rights reserved. // #import "IJSVGLayer.h" #import "IJSVGPattern.h" #import <QuartzCore/QuartzCore.h> @interface IJSVGPatternLayer : IJSVGLayer @property (nonatomic, retain) IJSVGLayer* pattern; @property (nonatomic, retain) IJSVGPattern* patternNode; @end <|start_filename|>Framework/IJSVG/IJSVG/Source/Exporter/IJSVGExporterPathInstruction.h<|end_filename|> // // IJSVGExporterPathInstruction.h // IconJar // // Created by <NAME> on 08/01/2017. // Copyright © 2017 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN typedef struct { char instruction; NSArray<NSString*>* params; } IJSVGExporterPathInstructionCommand; typedef struct { CGPoint center; CGFloat radius; } IJSVGExporterPathInstructionCircle; @interface IJSVGExporterPathInstruction : NSObject { @private NSInteger _dataCount; CGFloat* _data; CGFloat* _base; CGFloat* _coords; } @property (nonatomic, assign) char instruction; void IJSVGExporterPathInstructionRoundData(CGFloat* data, NSInteger length, IJSVGFloatingPointOptions options); CGFloat IJSVGExporterPathFloatToFixed(CGFloat number, int precision); IJSVGExporterPathInstructionCommand* IJSVGExporterPathInstructionCommandCopy(IJSVGExporterPathInstructionCommand command); void IJSVGExporterPathInstructionCommandFree(IJSVGExporterPathInstructionCommand* _Nullable command); + (NSArray<IJSVGExporterPathInstruction*>*)instructionsFromPath:(CGPathRef)path floatingPointOptions:(IJSVGFloatingPointOptions)floatingPointOptions; - (id)initWithInstruction:(char)instruction dataCount:(NSInteger)floatCount; - (CGFloat*)data; - (NSInteger)dataLength; + (NSArray<IJSVGExporterPathInstruction*>*)convertInstructionsCurves:(NSArray<IJSVGExporterPathInstruction*>*)instructions floatingPointOptions:(IJSVGFloatingPointOptions)floatingPointOptions; + (void)convertInstructionsToMixedAbsoluteRelative:(NSArray<IJSVGExporterPathInstruction*>*)instructions floatingPointOptions:(IJSVGFloatingPointOptions)floatingPointOptions; + (void)convertInstructionsDataToRounded:(NSArray<IJSVGExporterPathInstruction*>*)instructions floatingPointOptions:(IJSVGFloatingPointOptions)floatingPointOptions; + (void)convertInstructionsToRelativeCoordinates:(NSArray<IJSVGExporterPathInstruction*>*)instructions floatingPointOptions:(IJSVGFloatingPointOptions)floatingPointOptions; + (NSString*)pathStringFromInstructions:(NSArray<IJSVGExporterPathInstruction*>*)instructions floatingPointOptions:(IJSVGFloatingPointOptions)floatingPointOptions; + (NSString*)pathStringWithInstructionSet:(NSArray<NSValue*>*)instructionSets floatingPointOptions:(IJSVGFloatingPointOptions)floatingPointOptions; @end NS_ASSUME_NONNULL_END static NSInteger const kIJSVGExporterPathInstructionFloatPrecision = 3; static CGFloat const kIJSVGExporterPathInstructionErrorThreshold = 1e-2; #define IJ_SVG_EXPORT_ROUND(value) IJSVGExporterPathFloatToFixed(value, kIJSVGExporterPathInstructionFloatPrecision) <|start_filename|>Framework/IJSVG/IJSVG/Source/Parsing/IJSVGCommandParser.h<|end_filename|> // // IJSVGCommandParser.h // IJSVG // // Created by <NAME> on 23/12/2019. // Copyright © 2019 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> #include <xlocale.h> NS_ASSUME_NONNULL_BEGIN typedef NS_ENUM(NSUInteger, IJSVGPathDataSequence) { kIJSVGPathDataSequenceTypeFloat, kIJSVGPathDataSequenceTypeFlag }; static NSUInteger const IJSVG_STREAM_FLOAT_BLOCK_SIZE = 50; static NSUInteger const IJSVG_STREAM_CHAR_BLOCK_SIZE = 20; typedef struct { CGFloat* floatBuffer; NSInteger floatCount; char* charBuffer; NSInteger charCount; } IJSVGPathDataStream; @interface IJSVGCommandParser : NSObject IJSVGPathDataStream* IJSVGPathDataStreamCreateDefault(void); IJSVGPathDataStream* IJSVGPathDataStreamCreate(NSUInteger floatCount, NSUInteger charCount); void IJSVGPathDataStreamRelease(IJSVGPathDataStream* buffer); IJSVGPathDataSequence* IJSVGPathDataSequenceCreateWithType(IJSVGPathDataSequence type, NSInteger length); CGFloat* _Nullable IJSVGParsePathDataStreamSequence(const char* commandChars, NSInteger commandCharLength, IJSVGPathDataStream* dataStream, IJSVGPathDataSequence* _Nullable sequence, NSInteger commandLength, NSInteger* _Nullable commandsFound); @end NS_ASSUME_NONNULL_END <|start_filename|>Framework/IJSVG/IJSVG/Source/Utils/IJSVGTransaction.h<|end_filename|> // // IJSVGTransaction.h // IconJar // // Created by <NAME> on 11/01/2017. // Copyright © 2017 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> #import <QuartzCore/QuartzCore.h> BOOL IJSVGIsMainThread(void); BOOL IJSVGBeginTransaction(void); void IJSVGEndTransaction(void); <|start_filename|>Framework/IJSVG/IJSVG/Source/Additions/NSImage+IJSVGAdditions.h<|end_filename|> // // NSImage+IJSVGAdditions.h // IJSVG // // Created by <NAME> on 07/06/2020. // Copyright © 2020 <NAME>. All rights reserved. // #import <AppKit/AppKit.h> #import <Cocoa/Cocoa.h> IJSVG* IJSVGGetFromNSImage(NSImage* image); @interface NSImage (IJSVGAdditions) + (NSImage*)SVGImageNamed:(NSString*)imageName; @end <|start_filename|>Framework/IJSVG/IJSVG/Source/Additions/IJSVGStringAdditions.h<|end_filename|> // // IJSVGStringAdditions.h // IconJar // // Created by <NAME> on 07/06/2019. // Copyright © 2019 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> @interface NSString (IJSVGAdditions) - (NSArray<NSString*>*)ijsvg_componentsSeparatedByChars:(const char*)aChar; - (BOOL)ijsvg_isNumeric; - (BOOL)ijsvg_containsAlpha; - (NSArray*)ijsvg_componentsSplitByWhiteSpace; - (BOOL)ijsvg_isHexString; @end <|start_filename|>Framework/IJSVG/IJSVG/Source/Core/IJSVGError.h<|end_filename|> // // IJSVGError.h // IJSVGExample // // Created by <NAME> on 16/09/2015. // Copyright © 2015 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> static NSString* const IJSVGErrorDomain = @"IJSVGErrorDomain"; NS_ENUM(NSInteger){ IJSVGErrorReadingFile, IJSVGErrorParsingFile, IJSVGErrorParsingSVG, IJSVGErrorDrawing, IJSVGErrorInvalidViewBox };
lemonmojo/IJSVG
<|start_filename|>app/easytest_jmeter/BeanShellPreProcessorDemo.java<|end_filename|> import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import com.xx.x.util.*; import org.apache.jmeter.protocol.http.sampler.*; import org.apache.jmeter.samplers.*; import org.apache.jmeter.config.*; import org.apache.jmeter.protocol.http.sampler.*; import org.apache.jmeter.protocol.http.util.*; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; import com.doctor.commons.*; try { //自定义变量 //读取配置.设置头信息和公共信息 Properties properties = new Properties(); String fileName = ${configFile}+""; FileInputStream inputStream = new FileInputStream(fileName); properties.load(inputStream); String accountId = properties.getProperty("accountId"); String sign = properties.getProperty("sign"); String accessKey = properties.getProperty("accessKey"); String token = properties.getProperty("token"); vars.put("accountId",accountId); vars.put("sign",sign); vars.put("accessKey",accessKey); vars.put("token",token); if (inputStream != null) { inputStream.close(); } String deviceId = ${deviceId}+""; String secretKey = ${secretKey}+""; //请求体重置加密 Arguments arguments = sampler.getArguments(); Argument arg = arguments.getArgument(0); String body = arg.getValue(); log.info("PreProcessor==========================================="+ body); JSONObject parseObject = JSON.parseObject(body); log.info("====********************************************************************"+ parseObject); String data = parseObject.getString("data"); if(data !=null){ log.info("====********************************************************************"+ data); //加密 String encryptData = AESUtis.appAESEncrypt(data, deviceId, secretKey); log.info("encryptData====********************************************************************"+ encryptData); JSONObject jsonObject = new JSONObject(); jsonObject.put("data", encryptData); String postData = jsonObject.toJSONString(); log.info("postData====**************************************postData******************************"+ postData); //设置新post 数据 arg.setValue(postData); } } catch (Exception ex) { log.info("Script execution failed===========================================", ex); } <|start_filename|>app/easytest_jmeter/BeanShellPostProcessorDemo.java<|end_filename|> import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import com.xx.x.util.*; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; import com.doctor.commons.*; try { //先取自定义变量,等用到的时候,再取说找不到定义 String secretKey = ${secretKey}+""; String deviceId = ${deviceId}+""; //服务器返回的公共配置属性保存 String fileName = ${configFile}+""; log.info("====*fileName*******************************************************************"+ fileName); //对返回的json数据处理 String response_data = prev.getResponseDataAsString(); JSONObject parseObject = JSON.parseObject(response_data); log.info("====********************************************************************"+ parseObject); String data = parseObject.getString("data"); //这是加密的数据处理 if (data != null) { log.info("====PostProcessor********************************************************************"+ data); //解密 String reqDencryptJSON = AESUtis.appAESDencrypt(data, deviceId,secretKey ); log.info("===PostProcessor**********************************responseBody*****************************"+ reqDencryptJSON); //解密的数据写回返回body中 prev.setResponseData(reqDencryptJSON.getBytes("UTF-8")); //取用户属性保存,以便以后用到 JSONObject resultJson= JSON.parseObject(reqDencryptJSON); JSONObject result = resultJson.getJSONObject("result"); if (result != null) { log.info("===PostProcessor*********************************result *******===************" ); String accessKey = result.getString("accessKey"); if (accessKey != null) { String accountId = result.getString("accountId"); String token = result.getString("token"); //配置.设置头信息和公共信息 String sign = MD5Utils.md5To32LowerCaseHexString( secretKey + accountId+ deviceId + secretKey); //文件读取放到这里, 文件内容会被重写,而不是追加模式,所以不能实际保存内容的地方申明FileOutputStream Properties properties = new Properties(); FileOutputStream outputStream = new FileOutputStream(fileName); properties.setProperty("accountId",accountId); properties.setProperty("accessKey",accessKey); properties.setProperty("sign",sign); properties.setProperty("token",token); properties.store(outputStream, "");// log.info("===PostProcessor**********************************properties.store*******===************" ); //资源释放 if (outputStream != null) { outputStream.close(); } } } } } catch (Exception ex) { log.info("Script execution failed================PostProcessor=========================", ex); }
ibmcuijunluke/easypython
<|start_filename|>Chapter13/webapp/templates/macros.html<|end_filename|> {% macro render_pagination(pagination, endpoint) %} <nav aria-label="Page navigation example"> <ul class="pagination"> {% if pagination.has_prev %} <li class="page-item"> <a class="page-link" href="{{ url_for('blog.home', page=pagination.prev().page) }}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> <span class="sr-only">Previous</span> </a> </li> {% endif %} {% for page in pagination.iter_pages() %} {% if page %} {% if page != pagination.page %} <li class="page-item"> <a class="page-link" href="{{ url_for(endpoint, page=page) }}">{{ page }}</a> </li> {% else %} <li class="page-item active"> <a class="page-link" href="">{{ page }}</a> </li> {% endif %} {% else %} <li class="page-item"> <a class="page-link">…</a> <li> {% endif %} {% endfor %} {% if pagination.has_next %} <li class="page-item"> <a class="page-link" href="{{ url_for('blog.home', page=pagination.next().page) }}" aria-label="Next"> <span aria-hidden="true">&raquo;</span> <span class="sr-only">Next</span> </a> </li> {% endif %} </ul> </nav> {% endmacro %} {% macro render_posts(posts, pagination=True) %} {% if pagination %} {% set _posts = posts.items %} {% else %} {% set _posts = posts %} {% endif %} {% for post in _posts %} <div > <h1> <a class="text-dark" href="{{ url_for('blog.post', post_id=post.id) }}">{{ post.title }}</a> </h1> </div> <div class="row"> <div class="col"> {{ post.text | truncate(500) | safe }} <a href="{{ url_for('blog.post', post_id=post.id) }}">{{_('Read More')}}</a> </div> </div> {% endfor %} {% endmacro %} <|start_filename|>Chapter01/Dockerfile<|end_filename|> FROM python:3.6.5 WORKDIR /app ADD . /app RUN pip install -r requirements.txt EXPOSE 5000 CMD ["python", "main.py"] <|start_filename|>Chapter13/deploy/Jenkins/Dockerfile<|end_filename|> FROM jenkinsci/blueocean USER root RUN apk add build-base python3-dev mariadb-dev libffi-dev EXPOSE 8080 <|start_filename|>Chapter03/templates/rightbody.html<|end_filename|> <div class="row"> <div class="col"> <h5>Recent Posts</h5> </div> </div> <ul class="list-group"> {% for post in recent %} <li class="list-group-item"> <a href="{{ url_for('post', post_id=post.id) }}">{{ post.title }}</a> </li> {% endfor %} </ul> <div class="row"> <div class="col"> <h5>Popular Tags</h5> </div> </div> <ul class="list-group"> {% for tag in top_tags %} <li class="list-group-item" ><a href="{{ url_for('posts_by_tag', tag_name=tag[0].title) }}">{{ tag[0].title }}</a> </li> {% endfor %} </ul> <|start_filename|>Chapter13/webapp/templates/admin/second_page.html<|end_filename|> {% extends 'admin/master.html' %} {% block body %} This is the second page! <a href="{{ url_for('.index') }}">Link</a> {% endblock %} <|start_filename|>Chapter09/Dockerfile<|end_filename|> FROM rabbitmq:3-management ENV RABBITMQ_ERLANG_COOKIE "SWQOKODSQALRPCLNMEQG" ENV RABBITMQ_DEFAULT_USER "rabbitmq" ENV RABBITMQ_DEFAULT_PASS "<PASSWORD>" ENV RABBITMQ_DEFAULT_VHOST "/" <|start_filename|>Chapter13/webapp/templates/admin/custom.html<|end_filename|> {% extends 'admin/master.html' %} {% block body %} This is the custom view! <a href="{{ url_for('.second_page') }}">Link</a> {% endblock %} <|start_filename|>Chapter09/webapp/templates/navbar.html<|end_filename|> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="{{url_for('blog.home')}}">Home <span class="sr-only">(current)</span></a> </li> {% if current_user.is_authenticated and current_user.has_role('poster') %} <li class="nav-item"> <a class="nav-link" href="{{url_for('blog.new_post')}}">New Post<span class="sr-only">(current)</span></a> </li> {% endif %} </ul> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link" href="{{url_for('blog.home')}}"></a> </li> {% if current_user.is_authenticated %} <li class="nav-item"> <a class="nav-link" href="#user"> <i class="fa fa-fw fa-sign-out"></i>{{ current_user }}</a> </li> <li class="nav-item"> <a class="nav-link" href="{{url_for('auth.logout')}}"> <i class="fa fa-fw fa-sign-out"></i>Logout</a> </li> {% else %} <li class="nav-item"> <a class="nav-link" href="{{url_for('auth.login')}}"> <i class="fa fa-fw fa-sign-in"></i>Login</a> </li> <li class="nav-item"> <a class="nav-link" href="{{url_for('auth.register')}}"> <i class="fa fa-fw fa-sign-in"></i>Register</a> </li> {% endif %} </ul> </div> </nav>
jayakumardhananjayan/pythonwebtut
<|start_filename|>plugins/pick-a-color-master/build/1.1.3/js/pick-a-color-1.1.3.js<|end_filename|> /* * Pick-a-Color JS v1.1.3 * Copyright 2013 <NAME> and Broadstreet Ads * https://github.com/lauren/pick-a-color/blob/master/LICENSE */ ;(function ($) { "use strict"; $.fn.pickAColor = function (options) { // capabilities var supportsTouch = 'ontouchstart' in window, smallScreen = (parseInt($(window).width(),10) < 767) ? true : false, supportsLocalStorage = 'localStorage' in window && window.localStorage !== null && typeof JSON === 'object', // don't use LS if JSON is not available (IE, ahem) isIE = /*@cc_on!@*/false, // OH NOES! myCookies = document.cookie, tenYearsInMilliseconds = 315360000000, // shut up I need it for the cookie startEvent = supportsTouch ? "touchstart.pickAColor" : "mousedown.pickAColor", moveEvent = supportsTouch ? "touchmove.pickAColor" : "mousemove.pickAColor", endEvent = supportsTouch ? "touchend.pickAColor" : "mouseup.pickAColor", clickEvent = supportsTouch ? "touchend.pickAColor" : "click.pickAColor", dragEvent = "dragging.pickAColor", endDragEvent = "endDrag.pickAColor"; // settings var settings = $.extend( {}, { showSpectrum : true, showSavedColors : true, saveColorsPerElement : false, fadeMenuToggle : true, showAdvanced : true, showBasicColors : true, showHexInput : true, basicColors : { white : 'fff', red : 'f00', orange : 'f60', yellow : 'ff0', green : '008000', blue : '00f', purple : '800080', black : '000' } }, options); // override showBasicColors if it and showAdvanced are both false if (!settings.showAdvanced && !settings.showBasicColors) { settings.showBasicColors = true; } var useTabs = (settings.showSavedColors && settings.showAdvanced) || (settings.showBasicColors && settings.showSavedColors) || (settings.showBasicColors && settings.showAdvanced); // so much markup var markupBeforeInput = function () { var $div = $("<div>").addClass("input-prepend input-append pick-a-color-markup"); if (settings.showHexInput) { $div = $div.append($("<span>").addClass("hex-pound").text("#")); } return $div; }; var markupAfterInput = function () { var $markup = $("<div>").addClass("btn-group"), $dropdownButton = $("<button type='button'>").addClass("btn color-dropdown dropdown-toggle"), $dropdownColorPreview = $("<span>").addClass("color-preview current-color"), $dropdownCaret = $("<span>").addClass("caret"), $dropdownContainer = $("<div>").addClass("color-menu dropdown-menu"); if (!settings.showHexInput) { $dropdownButton.addClass("no-hex"); $dropdownContainer.addClass("no-hex"); } $markup.append($dropdownButton.append($dropdownColorPreview).append($dropdownCaret)); if (!useTabs && !settings.showSpectrum) { $dropdownContainer.addClass("small"); } if (useTabs) { var $tabContainer = $("<div>").addClass("color-menu-tabs"); if (settings.showBasicColors) { $tabContainer.append($("<span>").addClass("basicColors-tab tab tab-active"). append($("<a>").text("Basic Colors"))); } if (settings.showSavedColors) { settings.showBasicColors ? $tabContainer.append($("<span>"). addClass("savedColors-tab tab").append($("<a>").text("Saved Colors"))) : $tabContainer.append($("<span>").addClass("savedColors-tab tab tab-active"). append($("<a>").text("Saved Colors"))); } if (settings.showAdvanced) { $tabContainer.append($("<span>").addClass("advanced-tab tab"). append($("<a>").text("Advanced"))); } $dropdownContainer.append($tabContainer); } if (settings.showBasicColors) { var $basicColors = $("<div>").addClass("basicColors-content active-content"); if (settings.showSpectrum) { $basicColors.append($("<h6>").addClass("color-menu-instructions"). text("Tap spectrum or drag band to change color")); } var $listContainer = $("<ul>").addClass("basic-colors-list"); $.each(settings.basicColors, function (index,value) { var $thisColor = $("<li>").addClass("color-item"), $thisLink = $("<a>").addClass(index + " color-link"), $colorPreview = $("<span>").addClass("color-preview " + index), $colorLabel = $("<span>").addClass("color-label").text(index); $thisLink.append($colorPreview, $colorLabel); $colorPreview.append(); if (value[0] !== '#') { value = '#'+value; } $colorPreview.css('background-color', value); if (settings.showSpectrum) { var $thisSpectrum = $("<span>").addClass("color-box spectrum-" + index); if (isIE) { $.each([0,1], function (i) { if (value !== "fff" && index !== "000") $thisSpectrum.append($("<span>").addClass(index + "-spectrum-" + i + " ie-spectrum")); }); } var $thisHighlightBand = $("<span>").addClass("highlight-band"); $.each([0,1,2], function () { $thisHighlightBand.append($("<span>").addClass("highlight-band-stripe")); }); $thisLink.append($thisSpectrum.append($thisHighlightBand)); } $listContainer.append($thisColor.append($thisLink)); }); $dropdownContainer.append($basicColors.append($listContainer)); } if (settings.showSavedColors) { var activeClass = settings.showBasicColors ? 'inactive-content' : 'active-content', $savedColors = $("<div>").addClass("savedColors-content").addClass(activeClass); $savedColors.append($("<p>").addClass("saved-colors-instructions"). text("Type in a color or use the spectrums to lighten or darken an existing color.")); $dropdownContainer.append($savedColors); } if (settings.showAdvanced) { var activeClass = settings.showBasicColors || settings.showSavedColors ? 'inactive-content' : 'active-content'; var $advanced = $("<div>").addClass("advanced-content").addClass(activeClass). append($("<h6>").addClass("advanced-instructions").text("Tap spectrum or drag band to change color")), $advancedList = $("<ul>").addClass("advanced-list"), $hueItem = $("<li>").addClass("hue-item"), $hueContent = $("<span>").addClass("hue-text"). text("Hue: ").append($("<span>").addClass("hue-value").text("0")); var $hueSpectrum = $("<span>").addClass("color-box spectrum-hue"); if (isIE) { $.each([0,1,2,3,4,5,6], function (i) { $hueSpectrum.append($("<span>").addClass("hue-spectrum-" + i + " ie-spectrum hue")); }); } var $hueHighlightBand = $("<span>").addClass("highlight-band"); $.each([0,1,2], function () { $hueHighlightBand.append($("<span>").addClass("highlight-band-stripe")); }); $advancedList.append($hueItem.append($hueContent).append($hueSpectrum.append($hueHighlightBand))); var $lightnessItem = $("<li>").addClass("lightness-item"), $lightnessSpectrum = $("<span>").addClass("color-box spectrum-lightness"), $lightnessContent = $("<span>").addClass("lightness-text"). text("Lightness: ").append($("<span>").addClass("lightness-value").text("50%")); if (isIE) { $.each([0,1], function (i) { $lightnessSpectrum.append($("<span>").addClass("lightness-spectrum-" + i + " ie-spectrum")); }); } var $lightnessHighlightBand = $("<span>").addClass("highlight-band"); $.each([0,1,2], function () { $lightnessHighlightBand.append($("<span>").addClass("highlight-band-stripe")); }); $advancedList.append($lightnessItem. append($lightnessContent).append($lightnessSpectrum.append($lightnessHighlightBand))); var $saturationItem = $("<li>").addClass("saturation-item"), $saturationSpectrum = $("<span>").addClass("color-box spectrum-saturation"); if (isIE) { $.each([0,1], function (i) { $saturationSpectrum.append($("<span>").addClass("saturation-spectrum-" + i + " ie-spectrum")); }); } var $saturationHighlightBand = $("<span>").addClass("highlight-band"); $.each([0,1,2], function () { $saturationHighlightBand.append($("<span>").addClass("highlight-band-stripe")); }); var $saturationContent = $("<span>").addClass("saturation-text"). text("Saturation: ").append($("<span>").addClass("saturation-value").text("100%")); $advancedList.append($saturationItem.append($saturationContent).append($saturationSpectrum. append($saturationHighlightBand))); var $previewItem = $("<li>").addClass("preview-item").append($("<span>"). addClass("preview-text").text("Preview")), $preview = $("<span>").addClass("color-preview advanced"). append("<button class='color-select btn btn-mini advanced' type='button'>Select</button>"); $advancedList.append($previewItem.append($preview)); $dropdownContainer.append($advanced.append($advancedList)); } $markup.append($dropdownContainer); return $markup; }; var myColorVars = {}; var myStyleVars = { rowsInDropdown : 8, maxColsInDropdown : 2 }; if (settings.showSavedColors) { // if we're saving colors... var allSavedColors = []; // make an array for all saved colors if (supportsLocalStorage && localStorage.allSavedColors) { // look for them in LS allSavedColors = JSON.parse(localStorage.allSavedColors); // if there's a saved_colors cookie... } else if (myCookies.match("pickAColorSavedColors-allSavedColors=")) { var theseCookies = myCookies.split(";"); // split cookies into an array... $.each(theseCookies, function (index) { // find the savedColors cookie! if (theseCookies[index].match("pickAColorSavedColors-allSavedColors=")) { allSavedColors = theseCookies[index].split("=")[1].split(","); } }); } } // methods var methods = { initialize: function () { var $this_el = $(this), $myInitializer = $this_el.parent().parent(), myId = $myInitializer.context.id; // get the default color from the content or data attribute myColorVars.defaultColor = $this_el.text() === "" ? "000" : $this_el.text(); myColorVars.typedColor = myColorVars.defaultColor; $this_el.html(function (){ return markupBeforeInput().append(function () { var inputType = settings.showHexInput ? 'text' : 'hidden'; return $('<input id="appendedPrependedDropdownButton" type="'+ inputType +'" value="' + myColorVars.defaultColor + '" name="' + myId + '"/>').addClass("color-text-input"); }).append(markupAfterInput()); }); }, updatePreview: function ($this_el) { myColorVars.typedColor = tinycolor($this_el.val()).toHex(); $this_el.siblings(".btn-group").find(".current-color").css("background-color", "#" + myColorVars.typedColor); }, // must be called with apply and an arguments array like [{thisEvent}] pressPreviewButton: function () { var thisEvent = arguments[0].thisEvent; thisEvent.stopPropagation(); methods.toggleDropdown(thisEvent.target); }, openDropdown: function (button,menu) { $(".color-menu").each(function () { // check all the other color menus... var $thisEl = $(this); if ($thisEl.css("display") === "block") { // if one is open, // find its color preview button var thisColorPreviewButton = $thisEl.parents(".btn-group"); methods.closeDropdown(thisColorPreviewButton,$thisEl); // close it } }); if (settings.fadeMenuToggle && !supportsTouch) { //fades look terrible in mobile $(menu).fadeIn("fast"); } else { $(menu).show(); } $(button).addClass("open"); }, closeDropdown: function (button,menu) { if (settings.fadeMenuToggle && !supportsTouch) { //fades look terrible in mobile $(menu).fadeOut("fast"); } else { $(menu).css("display","none"); } $(button).removeClass("open"); }, // can only be called with apply. requires an arguments array like: // [{button, menu}] closeDropdownIfOpen: function () { var button = arguments[0].button, menu = arguments[0].menu; if (menu.css("display") === "block") { methods.closeDropdown(button,menu); } }, toggleDropdown: function (element) { var $container = $(element).parents(".pick-a-color-markup"), $button = $container.find(".btn-group"), $menu = $container.find(".color-menu"); if ($menu.css("display") === "none") { methods.openDropdown($button,$menu); } else { methods.closeDropdown($button,$menu); } }, tabbable: function () { var $this_el = $(this), $myContainer = $this_el.parents(".pick-a-color-markup"); $this_el.click(function () { var $this_el = $(this), // interpret the associated content class from the tab class and get that content div contentClass = $this_el.attr("class").split(" ")[0].split("-")[0] + "-content", myContent = $this_el.parents(".dropdown-menu").find("." + contentClass); if (!$this_el.hasClass("tab-active")) { // make all active tabs inactive $myContainer.find(".tab-active").removeClass("tab-active"); // toggle visibility of active content $myContainer.find(".active-content"). removeClass("active-content").addClass("inactive-content"); $this_el.addClass("tab-active"); // make current tab and content active $(myContent).addClass("active-content").removeClass("inactive-content"); } }); }, // takes a color and the current position of the color band, // returns the value by which the color should be multiplied to // get the color currently being highlighted by the band getColorMultiplier: function (spectrumType,position,tab) { // position of the color band as a percentage of the width of the color box var spectrumWidth = (tab === "basic") ? parseInt($(".color-box").first().width(),10) : parseInt($(".advanced-list").find(".color-box").first().width(),10); if (spectrumWidth === 0) { // in case the width isn't set correctly if (tab === "basic") { spectrumWidth = supportsTouch ? 160 : 200; } else { spectrumWidth = supportsTouch ? 160 : 300; } } var halfSpectrumWidth = spectrumWidth / 2, percentOfBox = position / spectrumWidth; // for spectrums that lighten and darken, recalculate percent of box relative // to the half of spectrum the highlight band is currently in if (spectrumType === "bidirectional") { return (percentOfBox <= 0.5) ? (1 - (position / halfSpectrumWidth)) / 2 : -((position - halfSpectrumWidth) / halfSpectrumWidth) / 2 // now that we're treating each half as an individual spectrum, both are darkenRight } else { return (spectrumType === "darkenRight") ? -(percentOfBox / 2) : (percentOfBox / 2); } }, // modifyHSLLightness based on ligten/darken in LESS // https://github.com/cloudhead/less.js/blob/master/dist/less-1.3.3.js#L1763 modifyHSLLightness: function (HSL,multiplier) { var hsl = HSL; hsl.l += multiplier; hsl.l = Math.min(Math.max(0,hsl.l),1); return tinycolor(hsl).toHslString(); }, // defines the area within which an element can be moved getMoveableArea: function ($element) { var dimensions = {}, $elParent = $element.parent(), myWidth = $element.outerWidth(), parentWidth = $elParent.width(), // don't include borders for parent width parentLocation = $elParent.offset(); dimensions.minX = parentLocation.left; dimensions.maxX = parentWidth - myWidth; //subtract myWidth to avoid pushing out of parent return dimensions; }, moveHighlightBand: function ($highlightBand, moveableArea, e) { var hbWidth = $(".highlight-band").first().outerWidth(), threeFourthsHBWidth = hbWidth * 0.75, mouseX = supportsTouch ? e.originalEvent.pageX : e.pageX, // find the mouse! // mouse position relative to width of highlight-band newPosition = mouseX - moveableArea.minX - threeFourthsHBWidth; // don't move beyond moveable area newPosition = Math.max(0,(Math.min(newPosition,moveableArea.maxX))); $highlightBand.css("position", "absolute"); $highlightBand.css("left", newPosition); }, horizontallyDraggable: function () { $(this).on(startEvent, function (event) { event.preventDefault(); var $this_el = $(event.delegateTarget); $this_el.css("cursor","-webkit-grabbing"); $this_el.css("cursor","-moz-grabbing"); var dimensions = methods.getMoveableArea($this_el); $(document).on(moveEvent, function (e) { $this_el.trigger(dragEvent); methods.moveHighlightBand($this_el, dimensions, e); }).on(endEvent, function(event) { $(document).off(moveEvent); // for desktop $(document).off(dragEvent); $this_el.css("cursor","-webkit-grab"); $this_el.css("cursor","-moz-grab"); $this_el.trigger(endDragEvent); $(document).off(endEvent); }); }).on(endEvent, function(event) { event.stopPropagation(); $(document).off(moveEvent); // for mobile $(document).off(dragEvent); }); }, modifyHighlightBand: function ($highlightBand,colorMultiplier,spectrumType) { var darkGrayHSL = { h: 0, s:0, l: 0.05 }, bwMidHSL = { h: 0, s:0, l: 0.5 }, // change to color of band is opposite of change to color of spectrum hbColorMultiplier = -colorMultiplier, hbsColorMultiplier = hbColorMultiplier * 10, // needs to be either black or white $hbStripes = $highlightBand.find(".highlight-band-stripe"), newBandColor = (spectrumType === "lightenRight") ? methods.modifyHSLLightness(bwMidHSL,hbColorMultiplier) : methods.modifyHSLLightness(darkGrayHSL,hbColorMultiplier); $highlightBand.css("border-color", newBandColor); $hbStripes.css("background-color", newBandColor); }, // must be called with apply and expects an arguments array like // [{type: "basic"}] or [{type: "advanced", hsl: {h,s,l}}] calculateHighlightedColor: function () { var $thisEl = $(this), hbWidth = $(".highlight-band").first().outerWidth(), halfHBWidth = hbWidth / 2, tab = arguments[0].type; if (tab === "basic") { // get the class of the parent color box and slice off "spectrum" var $this_parent = $thisEl.parent(), colorName = $this_parent.attr("class").split("-")[2], colorHex = settings.basicColors[colorName], colorHsl = tinycolor(colorHex).toHsl(); switch(colorHex) { case "fff": var spectrumType = "darkenRight"; break; case "000": var spectrumType = "lightenRight"; break; default: var spectrumType = "bidirectional"; } } else { // re-set current L value to 0.5 because the color multiplier ligtens // and darkens against the baseline value var colorHsl = {"h": arguments[0].hsl.h, "l": 0.5, "s": arguments[0].hsl.s}, currentHue = arguments[0].hsl.h, currentSaturation = arguments[0].hsl.s, spectrumType = "bidirectional", $advancedContainer = $thisEl.parents(".advanced-list"), $advancedPreview = $advancedContainer.find(".color-preview"), $hueSpectrum = $advancedContainer.find(".spectrum-hue"), $saturationSpectrum = $advancedContainer.find(".spectrum-saturation"), $lightnessValue = $advancedContainer.find(".lightness-value"); } // midpoint of the current left position of the color band var highlightBandLocation = parseInt($thisEl.css("left"),10) + halfHBWidth, colorMultiplier = methods.getColorMultiplier(spectrumType,highlightBandLocation,tab), highlightedColor = methods.modifyHSLLightness(colorHsl,colorMultiplier), highlightedHex = "#" + tinycolor(highlightedColor).toHex(), highlightedLightnessString = highlightedColor.split("(")[1].split(")")[0].split(",")[2], highlightedLightness = (parseInt(highlightedLightnessString.split("%")[0])) / 100; if (tab === "basic") { $this_parent.siblings(".color-preview").css("background-color",highlightedHex); // replace the color label with a 'select' button $this_parent.prev('.color-label').replaceWith( '<button class="color-select btn btn-mini" type="button">Select</button>'); if (spectrumType !== "darkenRight") { methods.modifyHighlightBand($thisEl,colorMultiplier,spectrumType); } } else { $advancedPreview.css("background-color",highlightedHex); $lightnessValue.text(highlightedLightnessString); methods.updateSaturationStyles($saturationSpectrum,currentHue,highlightedLightness); methods.updateHueStyles($hueSpectrum,currentSaturation,highlightedLightness); methods.modifyHighlightBand($(".advanced-content .highlight-band"),colorMultiplier,spectrumType); } return (tab === "basic") ? tinycolor(highlightedColor).toHex() : highlightedLightness; }, updateSavedColorPreview: function (elements) { $.each(elements, function (index) { var $this_el = $(elements[index]), thisColor = $this_el.attr("class"); $this_el.find(".color-preview").css("background-color",thisColor); }); }, updateSavedColorMarkup: function ($savedColorsContent,mySavedColors) { mySavedColors = mySavedColors ? mySavedColors : allSavedColors; if (settings.showSavedColors && mySavedColors.length > 0) { if (!settings.saveColorsPerElement) { $savedColorsContent = $(".savedColors-content"); mySavedColors = allSavedColors; } var maxSavedColors = myStyleVars.rowsInDropdown * myStyleVars.maxColsInDropdown; mySavedColors = mySavedColors.slice(0,maxSavedColors); var $col0 = $("<ul>").addClass("saved-color-col 0"), $col1 = $("<ul>").addClass("saved-color-col 1"); $.each(mySavedColors, function (index,value) { var $this_li = $("<li>").addClass("color-item"), $this_link = $("<a>").addClass(value); $this_link.append($("<span>").addClass("color-preview")); $this_link.append($("<span>").addClass("color-label").text(value)); $this_li.append($this_link); if (index % 2 === 0) { $col0.append($this_li); } else { $col1.append($this_li); } }); $savedColorsContent.html($col0); $savedColorsContent.append($col1); var savedColorLinks = $($savedColorsContent).find("a"); methods.updateSavedColorPreview(savedColorLinks); } }, setSavedColorsCookie: function (savedColors,savedColorsDataAttr) { var now = new Date(), expiresOn = new Date(now.getTime() + tenYearsInMilliseconds); expiresOn = expiresOn.toGMTString(); if (typeof savedColorsDataAttr === "undefined") { document.cookie = "pickAColorSavedColors-allSavedColors=" + savedColors + ";expires=" + expiresOn; } else { document.cookie = "pickAColorSavedColors-" + savedColorsDataAttr + "=" + savedColors + "; expires=" + expiresOn; } }, saveColorsToLocalStorage: function (savedColors,savedColorsDataAttr) { if (supportsLocalStorage) { // if there is no data attribute, save to allSavedColors if (typeof savedColorsDataAttr === "undefined") { try { localStorage.allSavedColors = JSON.stringify(savedColors); } catch(e) { localStorage.clear(); } } else { // otherwise save to a data attr-specific item try { localStorage["pickAColorSavedColors-" + savedColorsDataAttr] = JSON.stringify(savedColors); } catch(e) { localStorage.clear(); } } } else { methods.setSavedColorsCookie(savedColors,savedColorsDataAttr); } }, removeFromArray: function (array, item) { if ($.inArray(item,array) !== -1) { // make sure it's in there array.splice($.inArray(item,array),1); } }, updateSavedColors: function (color,savedColors,savedColorsDataAttr) { methods.removeFromArray(savedColors,color); savedColors.unshift(color); methods.saveColorsToLocalStorage(savedColors,savedColorsDataAttr); }, // when settings.saveColorsPerElement, colors are saved to both mySavedColors and // allSavedColors so they will be avail to color pickers with no savedColorsDataAttr addToSavedColors: function (color,mySavedColorsInfo,$mySavedColorsContent) { if (settings.showSavedColors) { // make sure we're saving colors if (color[0] != "#") { color = "#" + color; } methods.updateSavedColors(color,allSavedColors); if (settings.saveColorsPerElement) { // if we're saving colors per element... var mySavedColors = mySavedColorsInfo.colors, dataAttr = mySavedColorsInfo.dataAttr; methods.updateSavedColors(color,mySavedColors,dataAttr); methods.updateSavedColorMarkup($mySavedColorsContent,mySavedColors); } else { // if not saving per element, update markup with allSavedColors methods.updateSavedColorMarkup($mySavedColorsContent,allSavedColors); } } }, // handles selecting a color from the basic menu of colors. // must be called with apply and relies on an arguments array like: // [{els, savedColorsInfo}] selectFromBasicColors: function () { var selectedColor = $(this).find("span:first").css("background-color"); selectedColor = tinycolor(selectedColor).toHex(); var myElements = arguments[0].els, mySavedColorsInfo = arguments[0].savedColorsInfo; $(myElements.colorTextInput).val(selectedColor); methods.updatePreview(myElements.colorTextInput); methods.addToSavedColors(selectedColor,mySavedColorsInfo,myElements.savedColorsContent); methods.closeDropdown(myElements.colorPreviewButton,myElements.colorMenu); // close the dropdown }, // handles user clicking or tapping on spectrum to select a color. // must be called with apply and relies on an arguments array like: // [{thisEvent, savedColorsInfo, els, mostRecentClick}] tapSpectrum: function () { var thisEvent = arguments[0].thisEvent, mySavedColorsInfo = arguments[0].savedColorsInfo, myElements = arguments[0].els, mostRecentClick = arguments[0].mostRecentClick; thisEvent.stopPropagation(); // stop this click from closing the dropdown var $highlightBand = $(this).find(".highlight-band"), dimensions = methods.getMoveableArea($highlightBand); supportsTouch ? methods.moveHighlightBand($highlightBand, dimensions, mostRecentClick) : methods.moveHighlightBand($highlightBand, dimensions, thisEvent); var highlightedColor = methods.calculateHighlightedColor.apply($highlightBand, [{type: "basic"}]); methods.addToSavedColors(highlightedColor,mySavedColorsInfo,myElements.savedColorsContent); // update touch instructions myElements.touchInstructions.html("Press 'select' to choose this color"); }, // bind to mousedown/touchstart, execute provied function if the top of the // window has not moved when there is a mouseup/touchend // must be called with apply and an arguments array like: // [{thisFunction, theseArguments}] executeUnlessScrolled: function () { var thisFunction = arguments[0].thisFunction, theseArguments = arguments[0].theseArguments, windowTopPosition, mostRecentClick; $(this).on(startEvent, function (e) { windowTopPosition = $(window).scrollTop(); // save to see if user is scrolling in mobile mostRecentClick = e; }).on(clickEvent, function (event) { var distance = windowTopPosition - $(window).scrollTop(); if (supportsTouch && (Math.abs(distance) > 0)) { return false; } else { theseArguments.thisEvent = event; //add the click event to the arguments object theseArguments.mostRecentClick = mostRecentClick; //add start event to the arguments object thisFunction.apply($(this), [theseArguments]); } }); }, updateSaturationStyles: function (spectrum, hue, lightness) { var lightnessString = (lightness * 100).toString() + "%", start = "#" + tinycolor("hsl(" + hue + ",0%," + lightnessString).toHex(), mid = "#" + tinycolor("hsl(" + hue + ",50%," + lightnessString).toHex(), end = "#" + tinycolor("hsl(" + hue + ",100%," + lightnessString).toHex(), fullSpectrumString = "", standard = $.each(["-webkit-linear-gradient","-o-linear-gradient","linear-gradient"], function(index,value) { fullSpectrumString += "background-image: " + value + "(left, " + start + " 0%, " + mid + " 50%, " + end + " 100%);"; }), ieSpectrum0 = "progid:DXImageTransform.Microsoft.gradient(startColorstr='" + start + "', endColorstr='" + mid + "', GradientType=1)", ieSpectrum1 = "progid:DXImageTransform.Microsoft.gradient(startColorstr='" + mid + "', endColorstr='" + end + "', GradientType=1)"; fullSpectrumString = "background-image: -moz-linear-gradient(left center, " + start + " 0%, " + mid + " 50%, " + end + " 100%);" + "background-image: -webkit-gradient(linear, left top, right top," + "color-stop(0, " + start + ")," + "color-stop(0.5, " + mid + ")," + "color-stop(1, " + end + "));" + fullSpectrumString; if (isIE) { var $spectrum0 = $(spectrum).find(".saturation-spectrum-0"); var $spectrum1 = $(spectrum).find(".saturation-spectrum-1"); $spectrum0.css("filter",ieSpectrum0); $spectrum1.css("filter",ieSpectrum1); } else { spectrum.attr("style",fullSpectrumString); } }, updateLightnessStyles: function (spectrum, hue, saturation) { var saturationString = (saturation * 100).toString() + "%", start = "#" + tinycolor("hsl(" + hue + "," + saturationString + ",100%)").toHex(), mid = "#" + tinycolor("hsl(" + hue + "," + saturationString + ",50%)").toHex(), end = "#" + tinycolor("hsl(" + hue + "," + saturationString + ",0%)").toHex(), fullSpectrumString = "", standard = $.each(["-webkit-linear-gradient","-o-linear-gradient"], function(index, value) { fullSpectrumString += "background-image: " + value + "(left, " + start + " 0%, " + mid + " 50%, " + end + " 100%);"; }), ieSpectrum0 = "progid:DXImageTransform.Microsoft.gradient(startColorstr='" + start + "', endColorstr='" + mid + "', GradientType=1)", ieSpectrum1 = "progid:DXImageTransform.Microsoft.gradient(startColorstr='" + mid + "', endColorstr='" + end + "', GradientType=1)"; fullSpectrumString = "background-image: -moz-linear-gradient(left center, " + start + " 0%, " + mid + " 50%, " + end + " 100%); " + "background-image: linear-gradient(to right, " + start + " 0%, " + mid + " 50%, " + end + " 100%); " + "background-image: -webkit-gradient(linear, left top, right top," + " color-stop(0, " + start + ")," + " color-stop(0.5, " + mid + ")," + " color-stop(1, " + end + ")); " + fullSpectrumString; if (isIE) { var $spectrum0 = $(spectrum).find(".lightness-spectrum-0"); var $spectrum1 = $(spectrum).find(".lightness-spectrum-1"); $spectrum0.css("filter",ieSpectrum0); $spectrum1.css("filter",ieSpectrum1); } else { spectrum.attr("style",fullSpectrumString); } }, updateHueStyles: function (spectrum, saturation, lightness) { var saturationString = (saturation * 100).toString() + "%", lightnessString = (lightness * 100).toString() + "%", color1 = "#" + tinycolor("hsl(0," + saturationString + "," + lightnessString + ")").toHex(), color2 = "#" + tinycolor("hsl(60," + saturationString + "," + lightnessString + ")").toHex(), color3 = "#" + tinycolor("hsl(120," + saturationString + "," + lightnessString + ")").toHex(), color4 = "#" + tinycolor("hsl(180," + saturationString + "," + lightnessString + ")").toHex(), color5 = "#" + tinycolor("hsl(240," + saturationString + "," + lightnessString + ")").toHex(), color6 = "#" + tinycolor("hsl(300," + saturationString + "," + lightnessString + ")").toHex(), color7 = "#" + tinycolor("hsl(0," + saturationString + "," + lightnessString + ")").toHex(), ieSpectrum0 = "progid:DXImageTransform.Microsoft.gradient(startColorstr='" + color1 + "', endColorstr='" + color2 + "', GradientType=1)", ieSpectrum1 = "progid:DXImageTransform.Microsoft.gradient(startColorstr='" + color2 + "', endColorstr='" + color3 + "', GradientType=1)", ieSpectrum2 = "progid:DXImageTransform.Microsoft.gradient(startColorstr='" + color3 + "', endColorstr='" + color4 + "', GradientType=1)", ieSpectrum3 = "progid:DXImageTransform.Microsoft.gradient(startColorstr='" + color4 + "', endColorstr='" + color5 + "', GradientType=1)", ieSpectrum4 = "progid:DXImageTransform.Microsoft.gradient(startColorstr='" + color5 + "', endColorstr='" + color6 + "', GradientType=1)", ieSpectrum5 = "progid:DXImageTransform.Microsoft.gradient(startColorstr='" + color6 + "', endColorstr='" + color7 + "', GradientType=1)", fullSpectrumString = "", standard = $.each(["-webkit-linear-gradient","-o-linear-gradient","linear-gradient"], function(index,value) { fullSpectrumString += "background-image: " + value + "(left, " + color1 + " 0%, " + color2 + " 17%, " + color3 + " 24%, " + color4 + " 51%, " + color5 + " 68%, " + color6 + " 85%, " + color7 + " 100%);"; }); fullSpectrumString += "background-image: -webkit-gradient(linear, left top, right top," + "color-stop(0%, " + color1 + ")," + "color-stop(17%, " + color2 + ")," + "color-stop(34%, " + color3 + ")," + "color-stop(51%, " + color4 + ")," + "color-stop(68%, " + color5 + ")," + "color-stop(85%, " + color6 + ")," + "color-stop(100%, " + color7 + "));" + "background-image: -moz-linear-gradient(left center, " + color1 + " 0%, " + color2 + " 17%, " + color3 + " 24%, " + color4 + " 51%, " + color5 + " 68%, " + color6 + " 85%, " + color7 + " 100%);"; if (isIE) { var $spectrum0 = $(spectrum).find(".hue-spectrum-0"), $spectrum1 = $(spectrum).find(".hue-spectrum-1"), $spectrum2 = $(spectrum).find(".hue-spectrum-2"), $spectrum3 = $(spectrum).find(".hue-spectrum-3"), $spectrum4 = $(spectrum).find(".hue-spectrum-4"), $spectrum5 = $(spectrum).find(".hue-spectrum-5"); $spectrum0.css("filter",ieSpectrum0); $spectrum1.css("filter",ieSpectrum1); $spectrum2.css("filter",ieSpectrum2); $spectrum3.css("filter",ieSpectrum3); $spectrum4.css("filter",ieSpectrum4); $spectrum5.css("filter",ieSpectrum5); } else { spectrum.attr("style",fullSpectrumString); } }, // takes the position of a highlight band on the hue spectrum and finds highlighted hue // and updates the background of the lightness and saturation spectrums // relies on apply and an arguments array like [{h, s, l}] getHighlightedHue: function () { var $thisEl = $(this), hbWidth = $thisEl.outerWidth(), halfHBWidth = hbWidth / 2, position = parseInt($thisEl.css("left"),10) + halfHBWidth, $advancedContainer = $thisEl.parents(".advanced-list"), $advancedPreview = $advancedContainer.find(".color-preview"), $lightnessSpectrum = $advancedContainer.find(".spectrum-lightness"), $saturationSpectrum = $advancedContainer.find(".spectrum-saturation"), spectrumWidth = parseInt($advancedContainer.find(".color-box").first().width(),10), $hueValue = $advancedContainer.find(".hue-value"), currentLightness = arguments[0].l, currentSaturation = arguments[0].s, saturationString = (currentSaturation * 100).toString() + "%", lightnessString = (currentLightness * 100).toString() + "%"; if (spectrumWidth === 0) { // in case the width isn't set correctly spectrumWidth = supportsTouch ? 160 : 300; } var hue = Math.floor((position/spectrumWidth) * 360), color = "hsl(" + hue + "," + saturationString + "," + lightnessString + ")"; color = "#" + tinycolor(color).toHex(); $advancedPreview.css("background-color",color); $hueValue.text(hue); methods.updateLightnessStyles($lightnessSpectrum,hue,currentSaturation); methods.updateSaturationStyles($saturationSpectrum,hue,currentLightness); return hue; }, // relies on apply and an arguments array like [{h, s, l}] getHighlightedSaturation: function () { var $thisEl = $(this), hbWidth = $thisEl.outerWidth(), halfHBWidth = hbWidth / 2, position = parseInt($thisEl.css("left"),10) + halfHBWidth, $advancedContainer = $thisEl.parents(".advanced-list"), $advancedPreview = $advancedContainer.find(".color-preview"), $lightnessSpectrum = $advancedContainer.find(".spectrum-lightness"), $hueSpectrum = $advancedContainer.find(".spectrum-hue"), $saturationValue = $advancedContainer.find(".saturation-value"), spectrumWidth = parseInt($advancedContainer.find(".color-box").first().width(),10), currentLightness = arguments[0].l, lightnessString = (currentLightness * 100).toString() + "%", currentHue = arguments[0].h; if (spectrumWidth === 0) { // in case the width isn't set correctly spectrumWidth = supportsTouch ? 160 : 300; } var saturation = position/spectrumWidth, saturationString = Math.round((saturation * 100)).toString() + "%", color = "hsl(" + currentHue + "," + saturationString + "," + lightnessString + ")"; color = "#" + tinycolor(color).toHex(); $advancedPreview.css("background-color",color); $saturationValue.text(saturationString); methods.updateLightnessStyles($lightnessSpectrum,currentHue,saturation); methods.updateHueStyles($hueSpectrum,saturation,currentLightness); return saturation; }, updateAdvancedInstructions: function (instructionsEl) { instructionsEl.html("Press the color preview to choose this color"); } }; return this.each(function () { methods.initialize.apply(this); // commonly used DOM elements for each color picker var myElements = { thisEl: $(this), colorTextInput: $(this).find("input"), colorMenuLinks: $(this).find(".color-menu li a"), colorPreviewButton: $(this).find(".btn-group"), colorMenu: $(this).find(".color-menu"), colorSpectrums: $(this).find(".color-box"), basicSpectrums: $(this).find(".basicColors-content .color-box"), touchInstructions: $(this).find(".color-menu-instructions"), advancedInstructions: $(this).find(".advanced-instructions"), highlightBands: $(this).find(".highlight-band"), basicHighlightBands: $(this).find(".basicColors-content .highlight-band") }; var mostRecentClick, // for storing click events when needed windowTopPosition; // for storing the position of the top of the window when needed if (useTabs) { myElements.tabs = myElements.thisEl.find(".tab"); } if (settings.showSavedColors) { myElements.savedColorsContent = myElements.thisEl.find(".savedColors-content"); if (settings.saveColorsPerElement) { // when saving colors for each color picker... var mySavedColorsInfo = { colors: [], dataObj: $(this).data(), } $.each(mySavedColorsInfo.dataObj, function (key) { mySavedColorsInfo.dataAttr = key; }); // get this picker's colors from local storage if possible if (supportsLocalStorage && localStorage["pickAColorSavedColors-" + mySavedColorsInfo.dataAttr]) { mySavedColorsInfo.colors = JSON.parse(localStorage["pickAColorSavedColors-" + mySavedColorsInfo.dataAttr]); // otherwise, get them from cookies } else if (myCookies.match("pickAColorSavedColors-" + mySavedColorsInfo.dataAttr)) { var theseCookies = myCookies.split(";"); // an array of cookies... for (var i=0; i < theseCookies.length; i++) { if (theseCookies[i].match(mySavedColorsInfo.dataAttr)) { mySavedColorsInfo.colors = theseCookies[i].split("=")[1].split(","); } }; } else { // if no data-attr specific colors are in local storage OR cookies... mySavedColorsInfo.colors = allSavedColors; // use mySavedColors } } } if (settings.showAdvanced) { var advancedStatus = { h: 0, s: 1, l: 0.5 }; myElements.advancedSpectrums = myElements.thisEl.find(".advanced-list").find(".color-box"); myElements.advancedHighlightBands = myElements.thisEl.find(".advanced-list").find(".highlight-band"); myElements.hueSpectrum = myElements.thisEl.find(".spectrum-hue"); myElements.lightnessSpectrum = myElements.thisEl.find(".spectrum-lightness"); myElements.saturationSpectrum = myElements.thisEl.find(".spectrum-saturation"); myElements.hueHighlightBand = myElements.thisEl.find(".spectrum-hue .highlight-band"); myElements.lightnessHighlightBand = myElements.thisEl.find(".spectrum-lightness .highlight-band"); myElements.saturationHighlightBand = myElements.thisEl.find(".spectrum-saturation .highlight-band"); myElements.advancedPreview = myElements.thisEl.find(".advanced-content .color-preview"); } // add the default color to saved colors methods.addToSavedColors(myColorVars.defaultColor,mySavedColorsInfo,myElements.savedColorsContent); methods.updatePreview(myElements.colorTextInput); //input field focus: clear content // input field blur: update preview, restore previous content if no value entered myElements.colorTextInput.focus(function () { var $thisEl = $(this); myColorVars.typedColor = $thisEl.val(); // update with the current $thisEl.val(""); //clear the field on focus methods.toggleDropdown(myElements.colorPreviewButton,myElements.ColorMenu); }).blur(function () { var $thisEl = $(this); myColorVars.newValue = $thisEl.val(); // on blur, check the field's value // if the field is empty, put the original value back in the field if (myColorVars.newValue.match(/^\s+$|^$/)) { $thisEl.val(myColorVars.typedColor); } else { // otherwise... myColorVars.newValue = tinycolor(myColorVars.newValue).toHex(); // convert to hex $thisEl.val(myColorVars.newValue); // put the new value in the field // save to saved colors methods.addToSavedColors(myColorVars.newValue,mySavedColorsInfo,myElements.savedColorsContent); } methods.updatePreview($thisEl); // update preview }); // toggle visibility of dropdown menu when you click or press the preview button methods.executeUnlessScrolled.apply(myElements.colorPreviewButton, [{"thisFunction": methods.pressPreviewButton, "theseArguments" : {}}]); // any touch or click outside of a dropdown should close all dropdowns methods.executeUnlessScrolled.apply($(document), [{"thisFunction": methods.closeDropdownIfOpen, "theseArguments": {"button": myElements.colorPreviewButton, "menu": myElements.colorMenu}}]); // prevent click/touchend to color-menu or color-text input from closing dropdown myElements.colorMenu.on(clickEvent, function (e) { e.stopPropagation(); }); myElements.colorTextInput.on(clickEvent, function(e) { e.stopPropagation(); }); // update field and close menu when selecting from basic dropdown methods.executeUnlessScrolled.apply(myElements.colorMenuLinks, [{"thisFunction": methods.selectFromBasicColors, "theseArguments": {"els": myElements, "savedColorsInfo": mySavedColorsInfo}}]); if (useTabs) { // make tabs tabbable methods.tabbable.apply(myElements.tabs); } if (settings.showSpectrum || settings.showAdvanced) { methods.horizontallyDraggable.apply(myElements.highlightBands); } // for using the light/dark spectrums if (settings.showSpectrum) { // move the highlight band when you click on a spectrum methods.executeUnlessScrolled.apply(myElements.basicSpectrums, [{"thisFunction": methods.tapSpectrum, "theseArguments": {"savedColorsInfo": mySavedColorsInfo, "els": myElements}}]); $(myElements.basicHighlightBands).on(dragEvent,function (event) { var $thisEl = event.target methods.calculateHighlightedColor.apply(this, [{type: "basic"}]); }).on(endDragEvent, function (event) { var $thisEl = event.delegateTarget; var finalColor = methods.calculateHighlightedColor.apply($thisEl, [{type: "basic"}]); methods.addToSavedColors(finalColor,mySavedColorsInfo,myElements.savedColorsContent); }); } if (settings.showAdvanced) { // for dragging advanced sliders $(myElements.hueHighlightBand).on(dragEvent, function(event) { advancedStatus.h = methods.getHighlightedHue.apply(this, [advancedStatus]); }); $(myElements.lightnessHighlightBand).on(dragEvent, function() { methods.calculateHighlightedColor.apply(this, [{"type": "advanced", "hsl": advancedStatus}]); }).on(endEvent, function () { advancedStatus.l = methods.calculateHighlightedColor.apply(this, [{"type": "advanced", "hsl": advancedStatus}]); }); $(myElements.saturationHighlightBand).on(dragEvent, function() { methods.getHighlightedSaturation.apply(this, [advancedStatus]); }).on(endDragEvent, function () { advancedStatus.s = methods.getHighlightedSaturation.apply(this, [advancedStatus]); }); $(myElements.advancedHighlightBand).on(endDragEvent, function () { methods.updateAdvancedInstructions(myElements.advancedInstructions); }) // for clicking/tapping advanced sliders $(myElements.lightnessSpectrum).click( function (event) { event.stopPropagation(); // stop this click from closing the dropdown var $highlightBand = $(this).find(".highlight-band"), dimensions = methods.getMoveableArea($highlightBand); methods.moveHighlightBand($highlightBand, dimensions, event); advancedStatus.l = methods.calculateHighlightedColor.apply($highlightBand, [{"type": "advanced", "hsl": advancedStatus}]); }); $(myElements.hueSpectrum).click( function (event) { event.stopPropagation(); // stop this click from closing the dropdown var $highlightBand = $(this).find(".highlight-band"), dimensions = methods.getMoveableArea($highlightBand); methods.moveHighlightBand($highlightBand, dimensions, event); advancedStatus.h = methods.getHighlightedHue.apply($highlightBand, [advancedStatus]); }); $(myElements.saturationSpectrum).click( function (event) { event.stopPropagation(); // stop this click from closing the dropdown var $highlightBand = $(this).find(".highlight-band"), dimensions = methods.getMoveableArea($highlightBand); methods.moveHighlightBand($highlightBand, dimensions, event); advancedStatus.s = methods.getHighlightedSaturation.apply($highlightBand, [advancedStatus]); }); $(myElements.advancedSpectrums).click( function () { methods.updateAdvancedInstructions(myElements.advancedInstructions); }) //for clicking advanced color preview $(myElements.advancedPreview).click( function () { var selectedColor = tinycolor($(this).css("background-color")).toHex(); $(myElements.colorTextInput).val(selectedColor); methods.updatePreview(myElements.colorTextInput); methods.addToSavedColors(selectedColor,mySavedColorsInfo,myElements.savedColorsContent); methods.closeDropdown(myElements.colorPreviewButton,myElements.colorMenu); // close the dropdown }) } // for using saved colors if (settings.showSavedColors) { // make the links in saved colors work $(myElements.savedColorsContent).click( function (event) { var $thisEl = $(event.target); // make sure click happened on a link or span if ($thisEl.is("SPAN") || $thisEl.is("A")) { //grab the color the link's class or span's parent link's class var selectedColor = $thisEl.is("SPAN") ? $thisEl.parent().attr("class").split("#")[1] : $thisEl.attr("class").split("#")[1]; $(myElements.colorTextInput).val(selectedColor); methods.updatePreview(myElements.colorTextInput); methods.closeDropdown(myElements.colorPreviewButton,myElements.colorMenu); methods.addToSavedColors(selectedColor,mySavedColorsInfo,myElements.savedColorsContent); } }); // update saved color markup with content from localStorage or cookies, if available if (!settings.saveColorsPerElement) { methods.updateSavedColorMarkup(myElements.savedColorsContent,allSavedColors); } else if (settings.saveColorsPerElement) { methods.updateSavedColorMarkup(myElements.savedColorsContent,mySavedColorsInfo.colors); } } }); }; })(jQuery); <|start_filename|>plugins/pick-a-color-master/Gruntfile.js<|end_filename|> module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), uglify: { options: { banner: '/*! Pick-a-Color v<%= pkg.version %> | Copyright 2013 <NAME> and Broadstreet Ads https://github.com/lauren/pick-a-color/blob/master/LICENSE | <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n' }, my_target: { files: { 'build/<%= pkg.version %>/js/<%= pkg.name %>-<%= pkg.version %>.min.js': ['src/js/<%= pkg.name %>.js'], 'docs/build/js/<%= pkg.name %>.min.js': ['src/js/<%= pkg.name %>.js'] } } }, less: { production: { options: { compress: true, paths: ["src/less/css"] }, files: { "build/<%= pkg.version %>/css/<%= pkg.name %>-<%= pkg.version %>.min.css": "src/less/<%= pkg.name %>.less", "docs/build/css/<%= pkg.name %>.min.css": "src/less/<%= pkg.name %>.less" } } }, watch: { js: { files: ['src/js/*.js', 'Gruntfile.js'], tasks: ['jshint', 'uglify'], }, less: { files: ['src/less/*.less', 'src/less/bootstrap-src/*.less'], tasks: ['less'], } }, jshint: { all: ['Gruntfile.js', 'src/*/*.js'], options: { laxbreak: true, force: true } } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-jshint'); };
Romain64290/memotri
<|start_filename|>CYPasswordViewDemo/CYPasswordViewDemo/ViewController.h<|end_filename|> // // ViewController.h // CYPasswordViewDemo // // Created by cheny on 15/10/8. // Copyright © 2015年 zhssit. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
asparagusfern/payWindow
<|start_filename|>Makefile<|end_filename|> # ##################################################################### # FSE - Makefile # Copyright (C) <NAME> 2015 - present # GPL v2 License # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # You can contact the author at : # - Public forum froup : https://groups.google.com/forum/#!forum/lz4c # ##################################################################### # This is just a launcher for the Makefile within `programs` directory # ##################################################################### PROGDIR?= programs .PHONY: default default: fse check .PHONY: fse # only progdir knows if fse must be rebuilt or not fse: $(MAKE) -C $(PROGDIR) $@ cp $(PROGDIR)/fse . .PHONY: check check: fse $(MAKE) -C $(PROGDIR) $@ .PHONY: all test clean all test clean: $(MAKE) -C $(PROGDIR) $@ .PHONY: max13test max13test: clean @echo ---- test FSE_MAX_MEMORY_USAGE = 13 ---- CPPFLAGS="-DFSE_MAX_MEMORY_USAGE=13" $(MAKE) check .PHONY: gpptest gpptest: clean @echo ---- test g++ compilation ---- $(MAKE) -C $(PROGDIR) all CC=g++ CFLAGS="-O3 -Wall -Wextra -Wundef -Wshadow -Wcast-align -Wcast-qual -Werror" .PHONY: armtest armtest: clean @echo ---- test ARM compilation ---- CFLAGS="-O2 -Werror" $(MAKE) -C $(PROGDIR) all CC=arm-linux-gnueabi-gcc .PHONY: clangtest clangtest: clean @echo ---- test clang compilation ---- CFLAGS="-O3 -Werror -Wconversion -Wno-sign-conversion" CC=clang $(MAKE) -C $(PROGDIR) all .PHONY: clangpptest clangpptest: clean @echo ---- test clang++ compilation ---- $(MAKE) -C $(PROGDIR) all CC=clang++ CFLAGS="-O3 -Wall -Wextra -Wundef -Wshadow -Wcast-align -Wcast-qual -x c++ -Werror" .PHONY: staticAnalyze staticAnalyze: clean @echo ---- static analyzer - scan-build ---- scan-build --status-bugs -v $(MAKE) -C $(PROGDIR) all CFLAGS=-g # does not work well; too many false positives .PHONY: sanitize sanitize: clean @echo ---- check undefined behavior and address overflows ---- CC=clang CFLAGS="-g -O2 -fsanitize=undefined -fsanitize=address -fno-omit-frame-pointer" $(MAKE) -C $(PROGDIR) test FSETEST="-i5000" FSEU16TEST=-i2000 # CC=clang CFLAGS="-g -O3 -fsanitize=undefined -fsanitize=address" $(MAKE) -C $(PROGDIR) test32 FSETEST="-i5000" FSEU16TEST=-i2000 # sanitizer for 32-bits not correctly shipped with clang 3.8, which is used in travisCI
BeeBreeze/FiniteStateEntropy
<|start_filename|>azure-vote/Dockerfile<|end_filename|> FROM tiangolo/uwsgi-nginx-flask:python3.6 RUN pip install redis ADD /azure-vote /app WORKDIR /app ENV REDIS redisbackend.testapp EXPOSE 80
jeffqev/k8s-service-fabric-containers
<|start_filename|>Makefile<|end_filename|> .PHONY: all \ build \ build-release \ dist \ clean \ install \ setup ifeq ($(shell $(CC) -dM -E -x c /dev/null | grep -c __clang__), 1) CFLAGS = -DSQLITE_DISABLE_INTRINSIC endif PACKAGE := $(shell cargo read-manifest | jq -r .name) VERSION := $(shell cargo read-manifest | jq -r .version) TARGET := $(shell rustc -Vv | awk '/host/ { print $$2 }') all: build dist: build-release mkdir -p dist/ tar -C target/release -czvf dist/$(PACKAGE)-$(VERSION)-$(TARGET).tar.gz $(PACKAGE) build: CFLAGS=$(CFLAGS) cargo build build-release: CFLAGS=$(CFLAGS) cargo build --release clean: cargo clean $(RM) -r dist/ install: cargo install --path . setup: cargo install --no-default-features --features sqlite diesel_cli
ssedrick/duiker
<|start_filename|>cli/vendor/github.com/equinox-io/equinox/sdk_ctx.go<|end_filename|> // +build go1.7 package equinox import ( "context" ) // CheckContext is like Check but includes a context. func CheckContext(ctx context.Context, appID string, opts Options) (Response, error) { var req, err = checkRequest(appID, &opts) if err != nil { return Response{}, err } return doCheckRequest(opts, req.WithContext(ctx)) } // ApplyContext is like Apply but includes a context. func (r Response) ApplyContext(ctx context.Context) error { var req, opts, err = r.applyRequest() if err != nil { return err } return r.applyUpdate(req.WithContext(ctx), opts) } <|start_filename|>sdks/go/vendor/github.com/jfbus/httprs/httprs.go<|end_filename|> /* Package httprs provides a ReadSeeker for http.Response.Body. Usage : resp, err := http.Get(url) rs := httprs.NewHttpReadSeeker(resp) defer rs.Close() io.ReadFull(rs, buf) // reads the first bytes from the response body rs.Seek(1024, 0) // moves the position, but does no range request io.ReadFull(rs, buf) // does a range request and reads from the response body If you want use a specific http.Client for additional range requests : rs := httprs.NewHttpReadSeeker(resp, client) */ package httprs import ( "context" "errors" "fmt" "io" "io/ioutil" "net/http" "github.com/mitchellh/copystructure" ) const shortSeekBytes = 1024 // A HttpReadSeeker reads from a http.Response.Body. It can Seek // by doing range requests. type HttpReadSeeker struct { c *http.Client req *http.Request res *http.Response ctx context.Context r io.ReadCloser pos int64 canSeek bool Requests int } var _ io.ReadCloser = (*HttpReadSeeker)(nil) var _ io.Seeker = (*HttpReadSeeker)(nil) var ( // ErrNoContentLength is returned by Seek when the initial http response did not include a Content-Length header ErrNoContentLength = errors.New("Content-Length was not set") // ErrRangeRequestsNotSupported is returned by Seek and Read // when the remote server does not allow range requests (Accept-Ranges was not set) ErrRangeRequestsNotSupported = errors.New("Range requests are not supported by the remote server") // ErrInvalidRange is returned by Read when trying to read past the end of the file ErrInvalidRange = errors.New("Invalid range") // ErrContentHasChanged is returned by Read when the content has changed since the first request ErrContentHasChanged = errors.New("Content has changed since first request") ) // NewHttpReadSeeker returns a HttpReadSeeker, using the http.Response and, optionaly, the http.Client // that needs to be used for future range requests. If no http.Client is given, http.DefaultClient will // be used. // // res.Request will be reused for range requests, headers may be added/removed func NewHttpReadSeeker(res *http.Response, client ...*http.Client) *HttpReadSeeker { r := &HttpReadSeeker{ req: res.Request, ctx: res.Request.Context(), res: res, r: res.Body, canSeek: (res.Header.Get("Accept-Ranges") == "bytes"), } if len(client) > 0 { r.c = client[0] } else { r.c = http.DefaultClient } return r } // Clone clones the reader to enable parallel downloads of ranges func (r *HttpReadSeeker) Clone() (*HttpReadSeeker, error) { req, err := copystructure.Copy(r.req) if err != nil { return nil, err } return &HttpReadSeeker{ req: req.(*http.Request), res: r.res, r: nil, canSeek: r.canSeek, c: r.c, }, nil } // Read reads from the response body. It does a range request if Seek was called before. // // May return ErrRangeRequestsNotSupported, ErrInvalidRange or ErrContentHasChanged func (r *HttpReadSeeker) Read(p []byte) (n int, err error) { if r.r == nil { err = r.rangeRequest() } if r.r != nil { n, err = r.r.Read(p) r.pos += int64(n) } return } // ReadAt reads from the response body starting at offset off. // // May return ErrRangeRequestsNotSupported, ErrInvalidRange or ErrContentHasChanged func (r *HttpReadSeeker) ReadAt(p []byte, off int64) (n int, err error) { var nn int r.Seek(off, 0) for n < len(p) && err == nil { nn, err = r.Read(p[n:]) n += nn } return } // Close closes the response body func (r *HttpReadSeeker) Close() error { if r.r != nil { return r.r.Close() } return nil } // Seek moves the reader position to a new offset. // // It does not send http requests, allowing for multiple seeks without overhead. // The http request will be sent by the next Read call. // // May return ErrNoContentLength or ErrRangeRequestsNotSupported func (r *HttpReadSeeker) Seek(offset int64, whence int) (int64, error) { if !r.canSeek { return 0, ErrRangeRequestsNotSupported } var err error switch whence { case 0: case 1: offset += r.pos case 2: if r.res.ContentLength <= 0 { return 0, ErrNoContentLength } offset = r.res.ContentLength - offset } if r.r != nil { // Try to read, which is cheaper than doing a request if r.pos < offset && offset-r.pos <= shortSeekBytes { _, err := io.CopyN(ioutil.Discard, r, offset-r.pos) if err != nil { return 0, err } } if r.pos != offset { err = r.r.Close() r.r = nil } } r.pos = offset return r.pos, err } func cloneHeader(h http.Header) http.Header { h2 := make(http.Header, len(h)) for k, vv := range h { vv2 := make([]string, len(vv)) copy(vv2, vv) h2[k] = vv2 } return h2 } func (r *HttpReadSeeker) newRequest() *http.Request { newreq := r.req.WithContext(r.ctx) // includes shallow copies of maps, but okay if r.req.ContentLength == 0 { newreq.Body = nil // Issue 16036: nil Body for http.Transport retries } newreq.Header = cloneHeader(r.req.Header) return newreq } func (r *HttpReadSeeker) rangeRequest() error { r.req = r.newRequest() r.req.Header.Set("Range", fmt.Sprintf("bytes=%d-", r.pos)) etag, last := r.res.Header.Get("ETag"), r.res.Header.Get("Last-Modified") switch { case last != "": r.req.Header.Set("If-Range", last) case etag != "": r.req.Header.Set("If-Range", etag) } r.Requests++ res, err := r.c.Do(r.req) if err != nil { return err } switch res.StatusCode { case http.StatusRequestedRangeNotSatisfiable: return ErrInvalidRange case http.StatusOK: // some servers return 200 OK for bytes=0- if r.pos > 0 || (etag != "" && etag != res.Header.Get("ETag")) { return ErrContentHasChanged } fallthrough case http.StatusPartialContent: r.r = res.Body return nil } return ErrRangeRequestsNotSupported } <|start_filename|>cli/vendor/github.com/jawher/mow.cli/Makefile<|end_filename|> test: go test ./... test-cover: go list -f '{{if len .TestGoFiles}}"go test -coverprofile={{.Dir}}/.coverprofile {{.ImportPath}}"{{end}}' ./... | xargs -L 1 sh -c gover goveralls -coverprofile=gover.coverprofile -service=travis-ci check: readmecheck bin/golangci-lint run doc: autoreadme -f readmecheck: sed '$ d' README.md > README.original.md autoreadme -f sed '$ d' README.md > README.generated.md diff README.generated.md README.original.md setup: go get golang.org/x/tools/cmd/cover go get github.com/mattn/goveralls go get github.com/modocache/gover go get github.com/divan/autoreadme curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s v1.16.0 .PHONY: test check lint vet fmtcheck ineffassign readmecheck
s-pace/opctl
<|start_filename|>lib/shopix_web/views/layout_view.ex<|end_filename|> defmodule ShopixWeb.LayoutView do use ShopixWeb, :view end <|start_filename|>priv/repo/migrations/20170708183203_create_line_items_table.exs<|end_filename|> defmodule Shopix.Repo.Migrations.CreateLineItemsTable do use Ecto.Migration def change do create table(:line_items) do add :order_id, references(:orders) add :product_id, references(:products) add :quantity, :integer timestamps() end end end <|start_filename|>priv/repo/migrations/20190506204544_remove_instagram_auth_from_users.exs<|end_filename|> defmodule Shopix.Repo.Migrations.RemoveInstagramAuthFromUsers do use Ecto.Migration def change do alter table(:admin_users) do remove :instagram_auth end end end <|start_filename|>lib/shopix_web/views/front/page_view.ex<|end_filename|> defmodule ShopixWeb.Front.PageView do use ShopixWeb, :view end <|start_filename|>test/createurs/admin/admin_page_test.exs<|end_filename|> defmodule Shopix.Admin.AdminPageTest do use Shopix.DataCase, async: true alias Shopix.Admin alias Shopix.Schema.Page @valid_attrs %{ key: "faq", name_translations: %{"fr" => "Foire aux questions", "en" => "Frequently asked questions"}, content_translations: %{ "fr" => "Comment faire ci, faire ça...", "en" => "How to do this and that..." } } @update_attrs %{ key: "new_faq", name_translations: %{ "fr" => "Foire aux nouvelles questions", "en" => "Frequently asked new questions" }, content_translations: %{ "fr" => "Comment faire ci, faire ça, lalala...", "en" => "How to do this and that and this again..." } } @invalid_attrs %{key: ""} test "list_pages/1 returns all pages paginated" do page = insert(:page) assert %{entries: pages} = Admin.list_pages(%{}) assert pages == [page] end test "get_page!/1 returns the page with given id" do page = insert(:page) assert Admin.get_page!(page.id) == page end test "create_page/1 with valid data creates a page" do assert {:ok, %Page{} = page} = Admin.create_page(@valid_attrs) assert page.key == "faq" assert page.name_translations["fr"] == "Foire aux questions" assert page.name_translations["en"] == "Frequently asked questions" assert page.content_translations["fr"] == "Comment faire ci, faire ça..." assert page.content_translations["en"] == "How to do this and that..." assert page.slug_translations["fr"] == "foire-aux-questions" assert page.slug_translations["en"] == "frequently-asked-questions" end test "create_page/1 with invalid data returns error changeset" do assert {:error, %Ecto.Changeset{}} = Admin.create_page(@invalid_attrs) end test "update_page/2 with valid data updates the page" do page = insert(:page) assert {:ok, page} = Admin.update_page(page, @update_attrs) assert %Page{} = page assert page.key == "new_faq" assert page.name_translations["fr"] == "Foire aux nouvelles questions" assert page.name_translations["en"] == "Frequently asked new questions" assert page.content_translations["fr"] == "Comment faire ci, faire ça, lalala..." assert page.content_translations["en"] == "How to do this and that and this again..." assert page.slug_translations["fr"] == "foire-aux-nouvelles-questions" assert page.slug_translations["en"] == "frequently-asked-new-questions" end test "update_page/2 with invalid data returns error changeset" do page = insert(:page) assert {:error, %Ecto.Changeset{}} = Admin.update_page(page, @invalid_attrs) assert Admin.get_page!(page.id) == page end test "delete_page/1 deletes the page" do page = insert(:page) assert {:ok, %Page{}} = Admin.delete_page(page) assert_raise Ecto.NoResultsError, fn -> Admin.get_page!(page.id) end end test "change_page/1 returns a page changeset" do page = insert(:page) assert %Ecto.Changeset{} = Admin.change_page(page) end end <|start_filename|>priv/repo/migrations/20170711003244_create_unique_index_products_properties.exs<|end_filename|> defmodule Shopix.Repo.Migrations.CreateUniqueIndexProductsProperties do use Ecto.Migration def change do create unique_index(:products_properties, [:product_id, :property_id], name: :product_property_index) end end <|start_filename|>lib/shopix/front/line_item.ex<|end_filename|> defmodule Shopix.Front.LineItem do import Ecto.Changeset alias Shopix.Schema.LineItem def changeset(%LineItem{} = line_item, attrs) do line_item |> cast(attrs, [:quantity, :product_id]) |> validate_required([:quantity, :product_id]) end end <|start_filename|>lib/shopix_web/views/front/product_view.ex<|end_filename|> defmodule ShopixWeb.Front.ProductView do use ShopixWeb, :view def product_property_for(product, key) do Enum.find(product.product_properties, fn product_property -> product_property.property.key == key end) end def in_groups([], _), do: [] def in_groups(enum, number_of_groups) do size = round(Enum.count(enum) / number_of_groups) Enum.chunk_every(enum, size, size, []) end def properties_prefixed_by(product_properties, prefix) do Enum.filter(product_properties, fn product_property -> String.starts_with?(product_property.property.key, prefix) end) end end <|start_filename|>lib/shopix/admin/translation.ex<|end_filename|> defmodule Shopix.Admin.Translation do import Ecto.Changeset alias Shopix.Schema.Translation use Shopix.TranslationFields, translated_fields: ~w(value) def changeset(%Translation{} = translation, attrs) do translation |> cast(attrs, [:key] ++ localized_fields()) |> validate_required([:key]) |> validate_format(:key, ~r/\A[0-9a-zA-Z_\.]{3,}\z/) |> unique_constraint(:key) end end <|start_filename|>lib/shopix_web/controllers/api/cart_controller.ex<|end_filename|> defmodule ShopixWeb.Api.CartController do use ShopixWeb, :controller alias Shopix.Front def show(conn, %{"id" => id}) do order = Front.get_order(id, conn.assigns.global_config) render(conn, "show.json", order: order, locale: conn.assigns.current_locale) end def add(conn, %{"product_id" => product_id} = params) do order = if params["order_id"], do: Front.get_order(params["order_id"], conn.assigns.global_config), else: nil product = Front.get_product!(product_id) order = Front.create_or_add_order_with_product!(order, product, conn.assigns.global_config) order = Front.get_order(order.id, conn.assigns.global_config) render(conn, "show.json", order: order, locale: conn.assigns.current_locale) end def line_item_decrease(conn, %{"line_item_id" => line_item_id, "order_id" => order_id}) do Front.order_line_item_decrease!( Front.get_order(order_id, conn.assigns.global_config), line_item_id ) order = Front.get_order(order_id, conn.assigns.global_config) render(conn, "show.json", order: order, locale: conn.assigns.current_locale) end def line_item_increase(conn, %{"line_item_id" => line_item_id, "order_id" => order_id}) do Front.order_line_item_increase!( Front.get_order(order_id, conn.assigns.global_config), line_item_id ) order = Front.get_order(order_id, conn.assigns.global_config) render(conn, "show.json", order: order, locale: conn.assigns.current_locale) end def line_item_delete(conn, %{"line_item_id" => line_item_id, "order_id" => order_id}) do Front.order_line_item_delete!( Front.get_order(order_id, conn.assigns.global_config), line_item_id ) order = Front.get_order(order_id, conn.assigns.global_config) render(conn, "show.json", order: order, locale: conn.assigns.current_locale) end end <|start_filename|>test/createurs_web/plugs/locale_test.exs<|end_filename|> defmodule ShopixWeb.Plug.LocaleTest do use ShopixWeb.ConnCase, async: true alias ShopixWeb.Plug.Locale test "call/2 with no locale in conn sets default locale" do conn = build_conn() |> Plug.Conn.assign(:global_config, %{default_locale: "en", available_locales: ["en", "fr"]}) |> Locale.call(%{}) assert conn.status != 302 assert conn.assigns[:current_locale] == "en" end test "call/2 with valid locale specified in conn sets the locale" do conn = build_conn(:get, "/", %{"locale" => "fr"}) |> Plug.Conn.assign(:global_config, %{available_locales: ["en", "fr"]}) |> Locale.call(%{}) assert conn.status != 302 assert conn.assigns[:current_locale] == "fr" end test "call/2 with invalid locale specified in conn redirects" do conn = build_conn(:get, "/", %{"locale" => "es"}) |> Plug.Conn.assign(:global_config, %{available_locales: ["en", "fr"]}) |> Locale.call(%{}) assert conn.status == 302 end end <|start_filename|>lib/shopix_web/controllers/front/product_controller.ex<|end_filename|> defmodule ShopixWeb.Front.ProductController do use ShopixWeb, :controller alias Shopix.Front plug ShopixWeb.Plug.Translations def show(conn, %{"id" => id}) do product = Front.get_product_by_slug!(id, conn.assigns.current_locale) render(conn, "show.html", product: product, previous_product: Front.previous_product(product), next_product: Front.next_product(product), related_products: Front.get_related_products(product.id) ) end def index(conn, _params) do products = Front.list_products() render(conn, "index.html", products: products) end end <|start_filename|>priv/repo/migrations/20190504162842_add_fields_to_global_config.exs<|end_filename|> defmodule Shopix.Repo.Migrations.AddFieldsToGlobalConfig do use Ecto.Migration def change do alter table(:global_config) do add :shipping_cost_default_amount, :integer, default: 0 add :upload_provider_public_key, :string end end end <|start_filename|>lib/shopix_web/views/admin/product_view.ex<|end_filename|> defmodule ShopixWeb.Admin.ProductView do use ShopixWeb, :view def many_association_to_json(data, fields_to_take) do map = if Ecto.assoc_loaded?(data) do data |> Enum.map(&Map.take(&1, fields_to_take)) else [] end Jason.encode!(map) end def many_to_json(data, fields_to_take) do map = data |> Enum.map(&Map.take(&1, fields_to_take)) Jason.encode!(map) end end <|start_filename|>lib/shopix_web/controllers/front/home_controller.ex<|end_filename|> defmodule ShopixWeb.Front.HomeController do use ShopixWeb, :controller alias Shopix.Front import ShopixWeb.TranslationHelpers plug ShopixWeb.Plug.Translations def index(%{assigns: %{global_config: %{shop_opened: true}}} = conn, _params) do render(conn, "index.html") end def index(conn, _params) do conn |> put_status(:not_found) |> render(ShopixWeb.ErrorView, "404.html", layout: false) end def shop(conn, _params) do product = Front.first_product() conn |> redirect( to: product_path( conn, :show, conn.assigns.current_locale, t_slug(product, conn.assigns.current_locale) ) ) end end <|start_filename|>lib/shopix_web/views/api/page_view.ex<|end_filename|> defmodule ShopixWeb.Api.PageView do use ShopixWeb, :view def render("show.json", %{page: page, locale: locale}) do %{ page: page_json(page, locale), locale: locale } end def page_json(page, locale) do %{ id: page.id, slug: t_field(page, :slug, locale), content: t_field(page, :content, locale), image_url: image_url(page) } end end <|start_filename|>lib/shopix_web/views/admin/user_view.ex<|end_filename|> defmodule ShopixWeb.Admin.UserView do use ShopixWeb, :view end <|start_filename|>lib/shopix/front/translation.ex<|end_filename|> defmodule Shopix.Front.Translation do import Ecto.Changeset alias Shopix.Schema.{Translation} def changeset_create_key(key) do change(%Translation{}, %{key: key}) |> unique_constraint(:key) end end <|start_filename|>lib/shopix_web/controllers/admin/global_config_controller.ex<|end_filename|> defmodule ShopixWeb.Admin.GlobalConfigController do use ShopixWeb, :controller alias Shopix.Admin alias Ecto.Changeset def show(conn, _params) do changeset = Admin.change_global_config(conn.assigns.global_config) render(conn, "show.html", global_config: conn.assigns.global_config, changeset: changeset ) end def update(conn, %{"global_config" => global_config_params}) do case Admin.update_global_config(conn.assigns.global_config, global_config_params) do {:ok, _} -> conn |> put_flash(:info, "Global configuration updated successfully.") |> redirect(to: admin_global_config_path(conn, :show)) {:error, %Changeset{} = changeset} -> render(conn, "show.html", global_config: conn.assigns.global_config, changeset: changeset ) end end end <|start_filename|>lib/shopix_web/auth_error_handler.ex<|end_filename|> defmodule ShopixWeb.AuthErrorHandler do import Phoenix.Controller alias ShopixWeb.Router.Helpers, as: Routes def auth_error(conn, {_type, _reason}, _opts) do conn |> put_flash(:error, "Authentication required") |> redirect(to: Routes.admin_session_path(conn, :new)) end end <|start_filename|>lib/shopix/admin/product_property.ex<|end_filename|> defmodule Shopix.Admin.ProductProperty do import Ecto.Changeset use Shopix.TranslationFields, translated_fields: ~w(value) alias Shopix.Schema.ProductProperty def changeset(%ProductProperty{} = product_property, attrs) do product_property |> cast(attrs, [:product_id, :property_id] ++ localized_fields()) |> validate_required([:property_id]) |> unique_constraint(:property_id, name: :product_property_index) end end <|start_filename|>lib/shopix_web/views/api/cart_view.ex<|end_filename|> defmodule ShopixWeb.Api.CartView do use ShopixWeb, :view alias ShopixWeb.Api.ProductView def render("show.json", %{order: order, locale: locale}) do %{ order: order_json(order, locale) } end def order_json(order, locale) do %{ id: order.id, total_quantity: order.total_quantity, line_items: Enum.map(order.line_items, &line_item_json(&1, locale)), price_items: order.price_items, total_price: order.total_price, completed_at: order.completed_at } end def line_item_json(line_item, locale) do %{ id: line_item.id, quantity: line_item.quantity, product: ProductView.related_product_json(line_item.product, locale) } end end <|start_filename|>test/createurs_web/controllers/admin/home_controller_test.exs<|end_filename|> defmodule ShopixWeb.Admin.HomeControllerTest do use ShopixWeb.ConnCase, async: true test "index/2 responds with the dashboard" do conn = guardian_login(insert(:user)) |> get(admin_home_path(build_conn(), :index)) assert html_response(conn, 200) assert conn.resp_body =~ "Dashboard" end end <|start_filename|>lib/shopix/admin/user.ex<|end_filename|> defmodule Shopix.Admin.User do import Ecto.Changeset alias Comeonin.Bcrypt alias Shopix.Schema.User def registration_changeset(%User{} = user, attrs) do user |> cast(attrs, [:email, :password]) |> validate_required([:email, :password]) |> put_encrypted_password() |> unique_constraint(:email) end def changeset(%User{} = user, attrs) do user |> cast(attrs, [:email, :password]) |> validate_required([:email]) |> put_encrypted_password() |> unique_constraint(:email) end def valid_password?(%User{encrypted_password: encrypted_password}, password) do Bcrypt.checkpw(password, encrypted_password) end defp put_encrypted_password( %Ecto.Changeset{valid?: true, changes: %{password: password}} = changeset ) do changeset |> put_change(:encrypted_password, encrypt_password(password)) |> put_change(:password, nil) end defp put_encrypted_password(%Ecto.Changeset{} = changeset), do: changeset defp encrypt_password(password) do Bcrypt.hashpwsalt(password) end end <|start_filename|>lib/shopix_web/views/admin/property_view.ex<|end_filename|> defmodule ShopixWeb.Admin.PropertyView do use ShopixWeb, :view end <|start_filename|>lib/shopix_web/admin_guardian_pipeline.ex<|end_filename|> defmodule ShopixWeb.AdminGuardianPipeline do use Guardian.Plug.Pipeline, otp_app: :shopix, module: Shopix.Guardian, error_handler: ShopixWeb.AuthErrorHandler, key: :admin plug Guardian.Plug.VerifySession plug Guardian.Plug.EnsureAuthenticated plug Guardian.Plug.LoadResource end <|start_filename|>test/createurs/admin/user_test.exs<|end_filename|> defmodule Shopix.Admin.UserTest do use ExUnit.Case, async: true alias Shopix.Admin alias Shopix.Schema.User alias Comeonin.Bcrypt describe "registration_changeset/2" do test "returns a changeset" do assert %Ecto.Changeset{} = Admin.User.registration_changeset(%User{}, %{}) end test "validates requirements" do changeset = Admin.User.registration_changeset(%User{}, %{}) assert changeset.valid? == false assert {_, [validation: :required]} = changeset.errors[:email] assert {_, [validation: :required]} = changeset.errors[:password] end test "sets the encrypted password" do changeset = Admin.User.registration_changeset(%User{}, %{ email: "<EMAIL>", password: "<PASSWORD>" }) assert changeset.valid? == true assert changeset.changes |> Map.has_key?(:encrypted_password) == true end end describe "changeset/2" do test "returns a changeset" do assert %Ecto.Changeset{} = Admin.User.changeset(%User{}, %{}) end test "validates requirements" do changeset = Admin.User.changeset(%User{}, %{}) assert changeset.valid? == false assert {_, [validation: :required]} = changeset.errors[:email] assert changeset.errors[:password] == nil end test "does not change the encrypted password if there is no change to it" do changeset = Admin.User.changeset(%User{}, %{email: "<EMAIL>", password: ""}) assert changeset.valid? == true assert changeset.changes |> Map.has_key?(:email) == true assert changeset.changes |> Map.has_key?(:encrypted_password) == false end test "changes the encrypted password if there a change to it" do changeset = Admin.User.changeset(%User{}, %{email: "<EMAIL>", password: "<PASSWORD>"}) assert changeset.valid? == true assert changeset.changes |> Map.has_key?(:email) == true assert changeset.changes |> Map.has_key?(:encrypted_password) == true end end describe "valid_password?/2" do test "returns true if the given user has the given password" do user = %User{encrypted_password: <PASSWORD>("<PASSWORD>")} assert Admin.User.valid_password?(user, "<PASSWORD>") == true assert Admin.User.valid_password?(user, "<PASSWORD>") == false assert Admin.User.valid_password?(user, "") == false end end end <|start_filename|>test/createurs/admin/translation_test.exs<|end_filename|> defmodule Shopix.Admin.TranslationTest do use ExUnit.Case, async: true alias Shopix.Admin alias Shopix.Schema.Translation describe "changeset/2" do test "returns a changeset" do assert %Ecto.Changeset{} = Admin.Translation.changeset(%Translation{}, %{}) end test "validates requirements" do changeset = Admin.Translation.changeset(%Translation{}, %{}) assert changeset.valid? == false assert {_, [validation: :required]} = changeset.errors[:key] end end end <|start_filename|>priv/repo/seeds.exs<|end_filename|> # Script for populating the database. You can run it as: # # mix run priv/repo/seeds.exs # # Inside the script, you can read and write to any of your # repositories directly: # # Shopix.Repo.insert!(%Shopix.SomeSchema{}) # # We recommend using the bang functions (`insert!`, `update!` # and so on) as they will fail if something goes wrong. alias Shopix.Schema.{User, GlobalConfig} alias Shopix.{Repo, Admin} user = Admin.User.changeset(%User{}, %{ email: System.get_env("ADMIN_EMAIL"), password: System.<PASSWORD>_<PASSWORD>("ADMIN_PASSWORD") }) Repo.insert!(user) global_config = Admin.GlobalConfig.changeset(%GlobalConfig{}, %{}) Repo.insert!(global_config) <|start_filename|>priv/repo/migrations/20170718120051_alter_product_properties_references.exs<|end_filename|> defmodule Shopix.Repo.Migrations.AlterProductPropertiesReferences do use Ecto.Migration def change do drop constraint(:products_properties, "products_properties_property_id_fkey") drop constraint(:products_properties, "products_properties_product_id_fkey") alter table(:products_properties) do modify :property_id, references(:properties, on_delete: :delete_all) modify :product_id, references(:products, on_delete: :delete_all) end end end <|start_filename|>lib/shopix/schema/translation.ex<|end_filename|> defmodule Shopix.Schema.Translation do use Ecto.Schema use Shopix.TranslationFields, translated_fields: ~w(value) schema "translations" do field :key, :string schema_translation_fields() timestamps() end end <|start_filename|>lib/shopix/factory.ex<|end_filename|> defmodule Shopix.Factory do # with Ecto use ExMachina.Ecto, repo: Shopix.Repo alias Shopix.Schema def user_factory do %Schema.User{ email: sequence(:email, &"<EMAIL>"), password: "<PASSWORD>", encrypted_password: <PASSWORD>("<PASSWORD>") } end def product_factory do %Schema.Product{ price: 1000, sku: sequence(:sku, &"sku-#{&1}"), name_translations: %{"en" => "My great product", "fr" => "Mon super produit"}, description_translations: %{ "en" => "Cool description of my great product", "fr" => "Ceci est un super produit" }, slug_translations: %{"en" => "my-great-product", "fr" => "mon-super-produit"} } end def property_factory do %Schema.Property{ key: "width", name_translations: %{"en" => "Width", "fr" => "Largeur"} } end def line_item_factory do %Schema.LineItem{ product: build(:product), quantity: 3 } end def order_factory do %Schema.Order{ email: sequence(:email, &"<EMAIL>"), first_name: "Nicolas", last_name: "Blanco", company_name: "Shopix", address_1: "159 rue de Charonne", address_2: nil, zip_code: "75011", city: "Paris", country_state: nil, country_code: "FR", phone: "+33673730284", vat_percentage: Decimal.new(20), completed_at: NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second), shipping_cost_amount: 10, line_items: [build(:line_item)] } end def translation_factory do %Schema.Translation{ key: sequence(:translation_key, &"foobar.foo-#{&1}"), value_translations: %{"en" => "Hello world", "fr" => "Salut le monde"} } end def page_factory do %Schema.Page{ key: sequence(:page_key, &"about-#{&1}"), content_translations: %{ "fr" => "A propos de nous... Nous sommes les meilleurs ;)", "en" => "About us... We are the best ;)" }, name_translations: %{"fr" => "A propos", "en" => "About"}, slug_translations: %{"fr" => "a-propos", "en" => "about"} } end def group_factory do %Schema.Group{ key: sequence(:page_key, &"group-#{&1}") } end def global_config_factory do %Schema.GlobalConfig{} end end <|start_filename|>lib/shopix_web/router.ex<|end_filename|> defmodule ShopixWeb.Router do use ShopixWeb, :router use Plug.ErrorHandler use Sentry.Plug pipeline :browser do plug :accepts, ["html"] plug :fetch_session plug :fetch_flash plug :protect_from_forgery plug :put_secure_browser_headers end pipeline :admin_auth do plug ShopixWeb.AdminGuardianPipeline plug ShopixWeb.Plug.CurrentUser plug ShopixWeb.Plug.GlobalConfig plug ShopixWeb.Plug.AdminLocale end pipeline :front do plug ShopixWeb.Plug.GlobalConfig plug ShopixWeb.Plug.Locale plug ShopixWeb.Plug.CurrentOrder plug :put_layout, {ShopixWeb.LayoutView, :front} end pipeline :api do plug :accepts, ["json"] plug ShopixWeb.Plug.GlobalConfig plug ShopixWeb.Plug.Locale end if Mix.env() == :dev do forward "/sent_emails", Bamboo.SentEmailViewerPlug end scope "/api", ShopixWeb.Api, as: :api do pipe_through :api resources "/shop", ShopController, only: [:show], singleton: true end scope "/api/:locale", ShopixWeb.Api, as: :api do pipe_through :api resources "/products", ProductController, only: [:index, :show] resources "/pages", PageController, only: [:show] resources "/cart", CartController, only: [:show] post "/cart/add", CartController, :add put "/cart/line_item_decrease", CartController, :line_item_decrease put "/cart/line_item_increase", CartController, :line_item_increase delete "/cart/line_item_delete", CartController, :line_item_delete put "/checkout/validate_payment", CheckoutController, :validate_payment end scope "/admin", ShopixWeb.Admin, as: :admin do pipe_through [:browser, :admin_auth] resources "/products", ProductController resources "/groups", GroupController resources "/properties", PropertyController resources "/users", UserController resources "/translations", TranslationController resources "/orders", OrderController resources "/pages", PageController resources "/global_config", GlobalConfigController, only: [:show, :update], singleton: true get "/session/logout", SessionController, :delete get "/auth/:provider", SessionController, :request get "/auth/:provider/callback", SessionController, :callback get "/", HomeController, :index end scope "/session", ShopixWeb.Admin, as: :admin do pipe_through :browser resources "/", SessionController, only: [:new, :create], singleton: true end scope "/:locale", ShopixWeb.Front do pipe_through [:browser, :front] resources "/products", ProductController, only: [:show, :index] resources "/pages", PageController, only: [:show] resources "/cart", CartController, only: [:show], singleton: true post "/cart/add", CartController, :add put "/cart/line_item_decrease", CartController, :line_item_decrease put "/cart/line_item_increase", CartController, :line_item_increase delete "/cart/line_item_delete", CartController, :line_item_delete get "/shop", HomeController, :shop get "/checkout/address", CheckoutController, :address put "/checkout/validate_address", CheckoutController, :validate_address get "/checkout/payment", CheckoutController, :payment put "/checkout/validate_payment", CheckoutController, :validate_payment get "/checkout/complete", CheckoutController, :complete get "/", HomeController, :index end scope "/", ShopixWeb.Front do pipe_through [:browser, :front] get "/", HomeController, :index end end <|start_filename|>lib/shopix_web/views/front/cart_view.ex<|end_filename|> defmodule ShopixWeb.Front.CartView do use ShopixWeb, :view end <|start_filename|>lib/shopix_web/views/front/checkout_view.ex<|end_filename|> defmodule ShopixWeb.Front.CheckoutView do use ShopixWeb, :view end <|start_filename|>test/createurs_web/controllers/admin/product_controller_test.exs<|end_filename|> defmodule ShopixWeb.Admin.ProductControllerTest do use ShopixWeb.ConnCase, async: true @valid_attrs %{ price: "42,00 €", sku: "FOO-BAR", name_fr: "Magnifique produit", name_en: "Great product", description_fr: "Super produit, achetez-le !", description_en: "Wonderful product, buy it!" } @update_attrs %{ price: "50,00 €", sku: "FOO-BAR-2", name_fr: "Magnifique super produit", name_en: "Great and cool product", description_fr: "Super top produit, achetez-le !", description_en: "Wonderful product, buy it for sure!" } @invalid_attrs %{price: nil, sku: nil} test "index/2 responds with the products" do insert(:product, sku: "FOO-BAR") conn = guardian_login(insert(:user)) |> get(admin_product_path(build_conn(), :index)) assert html_response(conn, 200) assert conn.resp_body =~ "FOO-BAR" end test "new/2 responds with a form for a new product" do conn = guardian_login(insert(:user)) |> get(admin_product_path(build_conn(), :new)) assert html_response(conn, 200) assert conn.resp_body =~ "New product" end test "create/2 with valid attributes redirects and sets flash" do conn = guardian_login(insert(:user)) |> post(admin_product_path(build_conn(), :create), %{"product" => @valid_attrs}) assert html_response(conn, 302) assert get_flash(conn, :info) =~ "successfully" end test "create/2 with invalid attributes renders form" do conn = guardian_login(insert(:user)) |> post(admin_product_path(build_conn(), :create), %{"product" => @invalid_attrs}) assert html_response(conn, 200) assert conn.resp_body =~ "New product" end test "edit/2 responds with the edition of the product" do product = insert(:product) conn = guardian_login(insert(:user)) |> get(admin_product_path(build_conn(), :edit, product.id)) assert html_response(conn, 200) assert conn.resp_body =~ "Edit product" end test "update/2 with valid attributes redirects and sets flash" do product = insert(:product) conn = guardian_login(insert(:user)) |> put(admin_product_path(build_conn(), :update, product.id), %{"product" => @update_attrs}) assert html_response(conn, 302) assert get_flash(conn, :info) =~ "successfully" end test "update/2 with invalid attributes renders form" do product = insert(:product) conn = guardian_login(insert(:user)) |> put(admin_product_path(build_conn(), :update, product.id), %{"product" => @invalid_attrs}) assert html_response(conn, 200) assert conn.resp_body =~ "Edit product" end test "delete/2 redirects and sets flash" do product = insert(:product) conn = guardian_login(insert(:user)) |> delete(admin_product_path(build_conn(), :update, product.id)) assert html_response(conn, 302) assert get_flash(conn, :info) =~ "successfully" end end <|start_filename|>priv/repo/migrations/20170914192809_create_products_groups.exs<|end_filename|> defmodule Shopix.Repo.Migrations.CreateProductsGroups do use Ecto.Migration def change do create table(:groups) do add :key, :string timestamps() end create table(:products_groups) do add :product_id, references(:products, on_delete: :delete_all) add :group_id, references(:groups, on_delete: :delete_all) end create unique_index(:groups, [:key]) end end <|start_filename|>priv/repo/migrations/20170725113416_adds_edit_html_only_to_pages.exs<|end_filename|> defmodule Shopix.Repo.Migrations.AddsEditHtmlOnlyToPages do use Ecto.Migration def change do alter table(:pages) do add :edit_html_only, :boolean, default: false end end end <|start_filename|>test/createurs_web/plugs/current_user_test.exs<|end_filename|> defmodule ShopixWeb.Plug.CurrentUserTest do use ShopixWeb.ConnCase, async: true alias ShopixWeb.Plug.CurrentUser test "call/2 when no user is logged sets current_user to nil" do conn = build_conn() |> CurrentUser.call(%{}) assert conn.assigns.current_user == nil end test "call/2 when a user is logged sets the current_user" do user = insert(:user) conn = guardian_login(user) |> bypass_through(ShopixWeb.Router, [:browser, :admin_auth]) |> get("/") |> CurrentUser.call(%{}) assert conn.assigns.current_user.id == user.id end end <|start_filename|>lib/shopix_web/plugs/global_config.ex<|end_filename|> defmodule ShopixWeb.Plug.GlobalConfig do import Plug.Conn def init(opts), do: opts def call(conn, _opts) do global_config = Shopix.Schema.GlobalConfig |> Ecto.Query.first() |> Shopix.Repo.one!() conn |> assign(:global_config, global_config) end end <|start_filename|>lib/shopix_web/views/email_view.ex<|end_filename|> defmodule ShopixWeb.EmailView do use ShopixWeb, :view end <|start_filename|>test/createurs/admin/admin_property_test.exs<|end_filename|> defmodule Shopix.Admin.AdminPropertyTest do use Shopix.DataCase, async: true alias Shopix.Admin alias Shopix.Schema.Property @valid_attrs %{key: "foo-bar", name_translations: %{"fr" => "Hauteur", "en" => "Height"}} @update_attrs %{key: "new-foo-bar", name_translations: %{"fr" => "Longueur", "en" => "Length"}} @invalid_attrs %{key: ""} test "list_properties/0 returns all properties" do property = insert(:property) properties = Admin.list_properties() assert properties == [property] end test "list_properties/1 returns all properties paginated" do property = insert(:property) assert %{entries: properties} = Admin.list_properties(%{}) assert properties == [property] end test "get_property!/1 returns the property with given id" do property = insert(:property) assert Admin.get_property!(property.id) == property end test "create_property/1 with valid data creates a property" do assert {:ok, %Property{} = property} = Admin.create_property(@valid_attrs) assert property.key == "foo-bar" assert property.name_translations["fr"] == "Hauteur" assert property.name_translations["en"] == "Height" end test "create_property/1 with invalid data returns error changeset" do assert {:error, %Ecto.Changeset{}} = Admin.create_property(@invalid_attrs) end test "update_property/2 with valid data updates the property" do property = insert(:property) assert {:ok, property} = Admin.update_property(property, @update_attrs) assert %Property{} = property assert property.key == "new-foo-bar" assert property.name_translations["fr"] == "Longueur" assert property.name_translations["en"] == "Length" end test "update_property/2 with invalid data returns error changeset" do property = insert(:property) assert {:error, %Ecto.Changeset{}} = Admin.update_property(property, @invalid_attrs) assert Admin.get_property!(property.id) == property end test "delete_property/1 deletes the property" do property = insert(:property) assert {:ok, %Property{}} = Admin.delete_property(property) assert_raise Ecto.NoResultsError, fn -> Admin.get_property!(property.id) end end test "change_property/1 returns a property changeset" do property = insert(:property) assert %Ecto.Changeset{} = Admin.change_property(property) end end <|start_filename|>lib/shopix_web/views/admin/group_view.ex<|end_filename|> defmodule ShopixWeb.Admin.GroupView do use ShopixWeb, :view end <|start_filename|>test/createurs_web/emails_test.exs<|end_filename|> defmodule ShopixWeb.EmailsTest do use Shopix.DataCase, async: true alias ShopixWeb.Email alias Shopix.Front test "order_complete_email/1" do order = insert(:order) order = Front.get_order(order.id) email = Email.order_complete_email(order, "en", build(:global_config)) assert email.to == order.email assert email.html_body =~ "30,00 €" end end <|start_filename|>priv/repo/migrations/20170713151901_rename_orders_first_name.exs<|end_filename|> defmodule Shopix.Repo.Migrations.RenameOrdersFirstName do use Ecto.Migration def change do rename table(:orders), :fist_name, to: :first_name end end <|start_filename|>test/createurs/front/line_item_test.exs<|end_filename|> defmodule Shopix.Front.LineItemTest do use ExUnit.Case, async: true alias Shopix.Front alias Shopix.Schema.LineItem describe "changeset/2" do test "returns a changeset" do assert %Ecto.Changeset{} = Front.LineItem.changeset(%LineItem{}, %{}) end test "validates requirements" do changeset = Front.LineItem.changeset(%LineItem{}, %{quantity: ""}) assert changeset.valid? == false assert {_, [validation: :required]} = changeset.errors[:product_id] end end end <|start_filename|>lib/shopix_web/controllers/admin/property_controller.ex<|end_filename|> defmodule ShopixWeb.Admin.PropertyController do use ShopixWeb, :controller alias Shopix.Schema.Property alias Shopix.Admin def index(conn, params) do page = Admin.list_properties(params) render(conn, "index.html", properties: page.entries, page: page ) end def new(conn, _params) do changeset = Admin.change_property(%Property{}) render(conn, "new.html", changeset: changeset) end def create(conn, %{"property" => property_params}) do case Admin.create_property(property_params) do {:ok, _} -> conn |> put_flash(:info, "Property created successfully.") |> redirect(to: admin_property_path(conn, :index)) {:error, %Ecto.Changeset{} = changeset} -> render(conn, "new.html", changeset: changeset) end end def edit(conn, %{"id" => id}) do property = Admin.get_property!(id) changeset = Admin.change_property(property) render(conn, "edit.html", property: property, changeset: changeset) end def update(conn, %{"id" => id, "property" => property_params}) do property = Admin.get_property!(id) case Admin.update_property(property, property_params) do {:ok, _} -> conn |> put_flash(:info, "Property updated successfully.") |> redirect( to: admin_property_path(conn, :index, options_reject_nil(page: conn.params["page"])) ) {:error, %Ecto.Changeset{} = changeset} -> render(conn, "edit.html", property: property, changeset: changeset) end end def delete(conn, %{"id" => id}) do property = Admin.get_property!(id) {:ok, _property} = Admin.delete_property(property) conn |> put_flash(:info, "Property deleted successfully.") |> redirect(to: admin_property_path(conn, :index)) end end <|start_filename|>lib/shopix/schema/user.ex<|end_filename|> defmodule Shopix.Schema.User do use Ecto.Schema schema "admin_users" do field :email, :string field :encrypted_password, :string field :password, :string, virtual: true timestamps() end end <|start_filename|>lib/shopix/schema/line_item.ex<|end_filename|> defmodule Shopix.Schema.LineItem do use Ecto.Schema import Ecto.Changeset alias Shopix.Schema.{LineItem, Order, Product} schema "line_items" do belongs_to :order, Order belongs_to :product, Product field :quantity, :integer, default: 1 field :product_price_cache, Money.Ecto.Type field :product_sku_cache, :string field :product_price, Money.Ecto.Type, virtual: true field :product_sku, :string, virtual: true field :total_price, Money.Ecto.Type, virtual: true timestamps() end def changeset_cache(%LineItem{} = line_item) do line_item |> change() |> put_change(:product_price_cache, line_item.product.price) |> put_change(:product_sku_cache, line_item.product.sku) end def compute_properties(%LineItem{} = line_item) do %{ line_item | total_price: total_price(line_item), product_price: product_price(line_item), product_sku: product_sku(line_item) } end def increase_quantity(line_item) do line_item |> change(quantity: line_item.quantity + 1) end def decrease_quantity(line_item) do line_item |> change(quantity: line_item.quantity - 1) end def product_price(%LineItem{product_price_cache: nil} = line_item), do: line_item.product.price def product_price(%LineItem{product_price_cache: product_price_cache}), do: product_price_cache def product_sku(%LineItem{product_sku_cache: nil} = line_item), do: line_item.product.sku def product_sku(%LineItem{product_sku_cache: product_sku_cache}), do: product_sku_cache def total_price(%LineItem{} = line_item) do line_item |> product_price |> Money.multiply(line_item.quantity) end end <|start_filename|>test/createurs/admin/admin_product_test.exs<|end_filename|> defmodule Shopix.Admin.AdminProductTest do use Shopix.DataCase, async: true alias Shopix.Admin alias Shopix.Schema.Product @valid_attrs %{ price: "42,00 €", sku: "FOO-BAR", name_translations: %{"fr" => "Magnifique produit", "en" => "Great product"}, description_translations: %{ "fr" => "Super produit, achetez-le !", "en" => "Wonderful product, buy it!" } } @update_attrs %{ price: "50,00 €", sku: "FOO-BAR-2", name_translations: %{"fr" => "Magnifique super produit", "en" => "Great and cool product"}, description_translations: %{ "fr" => "Super top produit, achetez-le !", "en" => "Wonderful product, buy it for sure!" } } @invalid_attrs %{price: nil, sku: nil} test "list_products/1 returns all products" do product = insert(:product) assert %{entries: products} = Admin.list_products() assert products == [product] end test "get_product!/1 returns the product with given id" do product = insert(:product) product_get = Admin.get_product!(product.id) assert product_get.id == product.id end test "create_product/1 with valid data creates a product" do assert {:ok, %Product{} = product} = Admin.create_product(@valid_attrs) assert product.sku == "FOO-BAR" assert product.price.amount == 4200 assert product.name_translations["fr"] == "Magnifique produit" assert product.name_translations["en"] == "Great product" assert product.slug_translations["fr"] == "magnifique-produit" assert product.slug_translations["en"] == "great-product" assert product.description_translations["fr"] == "Super produit, achetez-le !" assert product.description_translations["en"] == "Wonderful product, buy it!" end test "create_product/1 with invalid data returns error changeset" do assert {:error, %Ecto.Changeset{}} = Admin.create_product(@invalid_attrs) end test "update_product/2 with valid data updates the product" do product = insert(:product) assert {:ok, product} = Admin.update_product(product, @update_attrs) assert %Product{} = product assert product.sku == "FOO-BAR-2" assert product.price.amount == 5000 assert product.name_translations["fr"] == "Magnifique super produit" assert product.name_translations["en"] == "Great and cool product" assert product.slug_translations["fr"] == "magnifique-super-produit" assert product.slug_translations["en"] == "great-and-cool-product" assert product.description_translations["fr"] == "Super top produit, achetez-le !" assert product.description_translations["en"] == "Wonderful product, buy it for sure!" end test "update_product/2 with invalid data returns error changeset" do product = insert(:product) assert {:error, %Ecto.Changeset{}} = Admin.update_product(product, @invalid_attrs) product_get = Admin.get_product!(product.id) assert product_get.sku == product.sku end test "delete_product/1 deletes the product" do product = insert(:product) assert {:ok, %Product{}} = Admin.delete_product(product) assert_raise Ecto.NoResultsError, fn -> Admin.get_product!(product.id) end end test "change_product/1 returns a product changeset" do product = insert(:product) assert %Ecto.Changeset{} = Admin.change_product(product) end end <|start_filename|>lib/shopix/vat_calculator.ex<|end_filename|> defmodule Shopix.VatCalculator do def ati_to_et(vat_percentage, amount) when is_integer(amount) do divider = vat_percentage |> Decimal.div(Decimal.new(100)) |> Decimal.add(Decimal.new(1)) result = Decimal.new(amount) |> Decimal.div(divider) result |> Decimal.round() |> Decimal.to_integer() end def vat_amount(vat_percentage, amount) when is_integer(amount) do amount - ati_to_et(vat_percentage, amount) end end <|start_filename|>priv/repo/migrations/20170720181046_alter_orders_add_shipping_cost_column.exs<|end_filename|> defmodule Shopix.Repo.Migrations.AlterOrdersAddShippingCostColumn do use Ecto.Migration def change do alter table(:orders) do add :shipping_cost_amount, :integer end end end <|start_filename|>test/createurs/admin/admin_order_test.exs<|end_filename|> defmodule Shopix.Admin.AdminOrderTest do use Shopix.DataCase, async: true alias Shopix.Admin test "list_orders/1 returns all orders completed paginated" do order = insert(:order) assert %{entries: orders} = Admin.list_orders(%{}) assert Enum.count(orders) == 1 assert (orders |> Enum.at(0)).id == order.id end test "get_order!/1 returns the order with given id" do order = insert(:order) order_get = Admin.get_order!(order.id) assert order_get.id == order.id end end <|start_filename|>assets/css/admin/app.css<|end_filename|> /* This file is for your main application css. */ .image-preview-multiple ._list { padding-top: 20px; } .image-preview-multiple ._item { padding: 0 0 10px; display: inline-block; text-align: center; vertical-align: top; width: 100px; word-break: break-word; font-size: 12px; line-height: normal; } .image-preview-multiple ._item img { display: block; width: 80px; height: 80px; padding: 0 10px 6px; } .small-margin-top { margin-top: 8px; } img.langs { cursor: pointer; padding-left: 0.2em; padding-right: 0.2em; } img.langs.active { border: 2px solid gray; } <|start_filename|>lib/shopix/front/front.ex<|end_filename|> defmodule Shopix.Front do import Ecto.Query, warn: false alias Shopix.Repo alias Shopix.Front alias Shopix.Schema.{Order, Page, Product, LineItem, Translation} def list_products(params \\ %{}) do from(p in Product, where: p.displayed == true) |> filter_by_group(params["filter"]) |> Repo.paginate(params) end def filter_by_group(query, nil), do: query def filter_by_group(query, group_key) do from q in query, join: g in assoc(q, :groups), where: g.key == ^group_key end def get_related_products(id) do from(p in Product, where: p.id != ^id, limit: 4) |> Repo.all() end def get_product_by_slug!(slug, locale) do query = from p in Product, where: fragment("?->>?", p.slug_translations, ^locale) == ^slug, preload: [product_properties: :property] query |> first |> Repo.one!() end def get_page_by_slug!(slug, locale) do from(p in Page, where: fragment("?->>?", p.slug_translations, ^locale) == ^slug ) |> first |> Repo.one!() end def get_product!(id) do Product |> preload(product_properties: :property) |> Repo.get!(id) end def get_translations(translation_key) do from(t in Translation, where: like(t.key, ^"#{translation_key}.%") or like(t.key, ^"front.layout.%") ) |> Repo.all() end def get_order(id, config \\ %{}) do case Repo.get(Order, id) do %Order{} = order -> order |> Repo.preload(line_items: {from(l in LineItem, order_by: l.inserted_at), :product}) |> Order.compute_line_items() |> Order.compute_properties(config) nil -> nil end end def change_order(%Order{} = order) do order |> Front.Order.changeset(%{}) end def order_validate_payment(%Order{} = order, global_config) do order |> Front.Order.changeset_payment(global_config) |> Repo.update() end def order_validate_address(%Order{} = order, attrs) do order |> Front.Order.changeset_address(attrs) |> Repo.update() end def get_line_item!(order_id, line_item_id) do query = from li in LineItem, where: li.order_id == ^order_id and li.id == ^line_item_id query |> Repo.one!() end def order_line_item_decrease!(%Order{id: order_id}, line_item_id) do line_item = get_line_item!(order_id, line_item_id) line_item |> LineItem.decrease_quantity() |> Repo.update!() end def order_line_item_increase!(%Order{id: order_id}, line_item_id) do line_item = get_line_item!(order_id, line_item_id) line_item |> LineItem.increase_quantity() |> Repo.update!() end def order_line_item_delete!(%Order{id: order_id}, line_item_id) do line_item = get_line_item!(order_id, line_item_id) line_item |> Repo.delete!() end def create_or_add_order_with_product!(%Order{} = order, %Product{} = product, _), do: add_product_to_order!(order, product) def create_or_add_order_with_product!(nil, %Product{} = product, config), do: create_order_with_product!(product, config) def create_order_with_product!(%Product{} = product, config) do case %Order{} |> Front.Order.changeset(%{line_items: [%{product_id: product.id, quantity: 1}]}) |> Repo.insert() do {:ok, order} -> get_order(order.id, config) end end def add_product_to_order!(%Order{} = order, %Product{} = product) do line_item = case Enum.find(order.line_items, fn li -> li.product_id == product.id end) do nil -> order |> Ecto.build_assoc(:line_items, product_id: product.id) |> Front.LineItem.changeset(%{}) line_item -> LineItem.increase_quantity(line_item) end Repo.insert_or_update!(line_item) order end def first_product do Product |> first |> Repo.one!() end def previous_product(%Product{id: product_id}) do query = from p in Product, where: p.id < ^product_id query |> last |> Repo.one() end def next_product(%Product{id: product_id}) do query = from p in Product, where: p.id > ^product_id query |> first |> Repo.one() end end <|start_filename|>test/createurs/admin/admin_user_test.exs<|end_filename|> defmodule Shopix.Admin.AdminUserTest do use Shopix.DataCase, async: true alias Shopix.Admin alias Shopix.Schema.User @valid_attrs %{email: "<EMAIL>", password: "<PASSWORD>"} @update_attrs %{email: "<EMAIL>", password: "<PASSWORD>"} @invalid_attrs %{email: nil, password: nil} test "list_users/1 returns all users" do user = insert(:user) assert %{entries: users} = Admin.list_users() assert Enum.count(users) == 1 assert (users |> Enum.at(0)).id == user.id end test "get_user!/1 returns the user with given id" do user = insert(:user) user_get = Admin.get_user!(user.id) assert user.id == user_get.id end test "create_user/1 with valid data creates a user" do assert {:ok, %User{} = user} = Admin.create_user(@valid_attrs) assert user.email == "<EMAIL>" assert user.encrypted_password |> String.length() > 10 end test "create_user/1 with invalid data returns error changeset" do assert {:error, %Ecto.Changeset{}} = Admin.create_user(@invalid_attrs) end test "update_user/2 with valid data updates the user" do user = insert(:user) previous_encrypted_password = user.encrypted_password assert {:ok, user} = Admin.update_user(user, @update_attrs) assert %User{} = user assert user.email == "<EMAIL>" assert user.encrypted_password != previous_encrypted_password end test "update_user/2 with invalid data returns error changeset" do user = insert(:user) assert {:error, %Ecto.Changeset{}} = Admin.update_user(user, @invalid_attrs) user_get = Admin.get_user!(user.id) assert user_get.email == user.email end test "delete_user/1 deletes the user" do user = insert(:user) assert {:ok, %User{}} = Admin.delete_user(user) assert_raise Ecto.NoResultsError, fn -> Admin.get_user!(user.id) end end test "change_user/1 returns a user changeset" do user = insert(:user) assert %Ecto.Changeset{} = Admin.change_user(user) end test "find_and_confirm_password/1 with valid data checks validity of password and returns user" do user = insert(:user, %{email: "<EMAIL>"}) assert {:ok, user_returned} = Admin.find_and_confirm_password(%{"email" => "<EMAIL>", "password" => "<PASSWORD>"}) assert user.id == user_returned.id end test "find_and_confirm_password/1 with invalid data returns an error" do insert(:user, %{email: "<EMAIL>"}) assert {:error, :invalid_credentials} = Admin.find_and_confirm_password(%{"email" => "<EMAIL>", "password" => "<PASSWORD>"}) assert {:error, :invalid_params} = Admin.find_and_confirm_password(nil) end end <|start_filename|>lib/shopix/admin/page.ex<|end_filename|> defmodule Shopix.Admin.Page do alias Shopix.Schema.Page import Ecto.Changeset use Shopix.TranslationFields, slug: :name, translated_fields: ~w(name content slug) def changeset(%Page{} = page, attrs) do page |> cast(attrs, [:key, :images_group_url, :edit_html_only] ++ localized_fields()) |> change_slugs() |> validate_required([:key]) |> validate_format(:key, ~r/\A[a-z0-9\-_]{3,}\z/) |> unique_constraint(:key) end end <|start_filename|>config/test.exs<|end_filename|> use Mix.Config # We don't run a server during test. If one is required, # you can enable the server option below. config :shopix, ShopixWeb.Endpoint, http: [port: 4001], server: false # Print only warnings and errors during test config :logger, level: :warn config :shopix, shipping_cost_amount: "1000", uploadcare_public_key: "<KEY>", create_translations_on_front: false if System.get_env("DATABASE_POSTGRESQL_USERNAME") do # Configure your database config :shopix, Shopix.Repo, adapter: Ecto.Adapters.Postgres, database: "shopix_test", hostname: "localhost", username: System.get_env("DATABASE_POSTGRESQL_USERNAME"), password: <PASSWORD>("<PASSWORD>"), pool: Ecto.Adapters.SQL.Sandbox else # Configure your database config :shopix, Shopix.Repo, adapter: Ecto.Adapters.Postgres, database: "shopix_test", hostname: "localhost", pool: Ecto.Adapters.SQL.Sandbox end config :bcrypt_elixir, :log_rounds, 4 config :shopix, Shopix.Mailer, adapter: Bamboo.TestAdapter <|start_filename|>lib/shopix/schema/product_property.ex<|end_filename|> defmodule Shopix.Schema.ProductProperty do use Ecto.Schema import Ecto.Changeset use Shopix.TranslationFields, translated_fields: ~w(value) alias Shopix.Schema.{Property, Product} schema "products_properties" do belongs_to :product, Product belongs_to :property, Property schema_translation_fields() timestamps() end end <|start_filename|>priv/repo/migrations/20170718225155_alter_table_line_items_constraint_product_id_nulify.exs<|end_filename|> defmodule Shopix.Repo.Migrations.AlterTableLineItemsConstraintProductIdNulify do use Ecto.Migration def change do drop constraint(:line_items, "line_items_product_id_fkey") alter table(:line_items) do modify :product_id, references(:products, on_delete: :nilify_all) end end end <|start_filename|>lib/shopix_web/controllers/admin/page_controller.ex<|end_filename|> defmodule ShopixWeb.Admin.PageController do use ShopixWeb, :controller alias Shopix.Schema.Page alias Shopix.Admin def index(conn, params) do page = Admin.list_pages(params) render(conn, "index.html", pages: page.entries, page: page ) end def new(conn, _params) do changeset = Admin.change_page(%Page{}) render(conn, "new.html", changeset: changeset) end def create(conn, %{"page" => page_params}) do case Admin.create_page(page_params) do {:ok, _} -> conn |> put_flash(:info, "Page created successfully.") |> redirect(to: admin_page_path(conn, :index)) {:error, %Ecto.Changeset{} = changeset} -> render(conn, "new.html", changeset: changeset) end end def edit(conn, %{"id" => id}) do page = Admin.get_page!(id) changeset = Admin.change_page(page) render(conn, "edit.html", page: page, changeset: changeset) end def update(conn, %{"id" => id, "page" => page_params}) do page = Admin.get_page!(id) case Admin.update_page(page, page_params) do {:ok, _} -> conn |> put_flash(:info, "Page updated successfully.") |> redirect( to: admin_page_path(conn, :index, options_reject_nil(page: conn.params["return_page"])) ) {:error, %Ecto.Changeset{} = changeset} -> render(conn, "edit.html", page: page, changeset: changeset) end end def delete(conn, %{"id" => id}) do page = Admin.get_page!(id) {:ok, _page} = Admin.delete_page(page) conn |> put_flash(:info, "Page deleted successfully.") |> redirect(to: admin_page_path(conn, :index)) end end <|start_filename|>test/createurs_web/controllers/admin/session_controller_test.exs<|end_filename|> defmodule ShopixWeb.Admin.SessionControllerTest do use ShopixWeb.ConnCase, async: true test "new/2 renders login form" do conn = build_conn() |> get(admin_session_path(build_conn(), :new)) assert html_response(conn, 200) assert conn.resp_body =~ "Sign In" end test "create/2 with valid credentials redirects and sets flash" do user = insert(:user) conn = build_conn() |> post( admin_session_path(build_conn(), :create), %{"credentials" => %{"email" => user.email, "password" => "<PASSWORD>"}} ) assert html_response(conn, 302) assert get_flash(conn, :info) =~ "successfully" end test "create/2 with invalid credentials renders the form" do user = insert(:user) conn = build_conn() |> post( admin_session_path(build_conn(), :create), %{"credentials" => %{"email" => user.email, "password" => "<PASSWORD>"}} ) assert html_response(conn, 200) assert conn.resp_body =~ "Sign In" end test "delete/2 redirects and sets flash" do conn = guardian_login(insert(:user)) |> get(admin_session_path(build_conn(), :delete)) assert html_response(conn, 302) assert get_flash(conn, :info) =~ "successfully" end test "unauthenticated/2 redirects and sets flash" do conn = build_conn() |> get(admin_home_path(build_conn(), :index)) assert html_response(conn, 302) assert get_flash(conn, :error) =~ "required" end end <|start_filename|>priv/repo/migrations/20170629192530_create_admin_product.exs<|end_filename|> defmodule Shopix.Repo.Migrations.CreateShopix.Admin.Product do use Ecto.Migration def change do create table(:products) do add :sku, :string add :price, :decimal, precision: 10, scale: 2 add :name_translations, :map add :description_translations, :map add :slug_translations, :map timestamps() end end end <|start_filename|>lib/shopix_web/controllers/admin/user_controller.ex<|end_filename|> defmodule ShopixWeb.Admin.UserController do use ShopixWeb, :controller alias Shopix.Schema.User alias Shopix.Admin alias Ecto.Changeset def index(conn, params) do page = Admin.list_users(params) render(conn, "index.html", users: page.entries, page: page ) end def new(conn, _params) do changeset = Admin.change_user(%User{}) render(conn, "new.html", changeset: changeset) end def create(conn, %{"user" => user_params}) do case Admin.create_user(user_params) do {:ok, _} -> conn |> put_flash(:info, "User created successfully.") |> redirect(to: admin_user_path(conn, :index)) {:error, %Changeset{} = changeset} -> render(conn, "new.html", changeset: changeset) end end def edit(conn, %{"id" => id}) do user = Admin.get_user!(id) changeset = Admin.change_user(user) render(conn, "edit.html", user: user, changeset: changeset) end def update(conn, %{"id" => id, "user" => user_params}) do user = Admin.get_user!(id) case Admin.update_user(user, user_params) do {:ok, _} -> conn |> put_flash(:info, "User updated successfully.") |> redirect( to: admin_user_path(conn, :index, options_reject_nil(page: conn.params["page"])) ) {:error, %Changeset{} = changeset} -> render(conn, "edit.html", user: user, changeset: changeset) end end def delete(conn, %{"id" => id}) do user = Admin.get_user!(id) {:ok, _user} = Admin.delete_user(user) conn |> put_flash(:info, "User deleted successfully.") |> redirect(to: admin_user_path(conn, :index)) end end <|start_filename|>lib/shopix_web/controllers/admin/group_controller.ex<|end_filename|> defmodule ShopixWeb.Admin.GroupController do use ShopixWeb, :controller alias Shopix.Schema.Group alias Shopix.Admin alias Ecto.Changeset def index(conn, params) do page = Admin.list_groups(params) render(conn, "index.html", groups: page.entries, page: page ) end def new(conn, _params) do changeset = Admin.change_group(%Group{}) render(conn, "new.html", changeset: changeset) end def create(conn, %{"group" => group_params}) do case Admin.create_group(group_params) do {:ok, _} -> conn |> put_flash(:info, "Group created successfully.") |> redirect(to: admin_group_path(conn, :index)) {:error, %Changeset{} = changeset} -> render(conn, "new.html", changeset: changeset) end end def edit(conn, %{"id" => id}) do group = Admin.get_group!(id) changeset = Admin.change_group(group) render(conn, "edit.html", group: group, changeset: changeset ) end def update(conn, %{"id" => id, "group" => group_params}) do group = Admin.get_group!(id) case Admin.update_group(group, group_params) do {:ok, _} -> conn |> put_flash(:info, "Group updated successfully.") |> redirect( to: admin_group_path(conn, :index, options_reject_nil(page: conn.params["page"])) ) {:error, %Changeset{} = changeset} -> render(conn, "edit.html", group: group, changeset: changeset ) end end def delete(conn, %{"id" => id}) do group = Admin.get_group!(id) {:ok, _group} = Admin.delete_group(group) conn |> put_flash(:info, "Group deleted successfully.") |> redirect(to: admin_group_path(conn, :index)) end end <|start_filename|>lib/shopix_web/views/string_helpers.ex<|end_filename|> defmodule ShopixWeb.StringHelpers do import Phoenix.HTML def to_json(data) do data |> Jason.encode!() |> raw end def options_reject_nil(options) do options |> Enum.reject(&is_nil(elem(&1, 1))) end def truncate(text, opts \\ []) do max_length = opts[:max_length] || 50 omission = opts[:omission] || "..." cond do not String.valid?(text) -> text String.length(text) < max_length -> text true -> length_with_omission = max_length - String.length(omission) "#{String.slice(text, 0, length_with_omission)}#{omission}" end end end <|start_filename|>lib/shopix_web/controllers/admin/order_controller.ex<|end_filename|> defmodule ShopixWeb.Admin.OrderController do use ShopixWeb, :controller alias Shopix.Admin def index(conn, params) do page = Admin.list_orders(params) render(conn, "index.html", orders: page.entries, page: page ) end def show(conn, %{"id" => id}) do order = Admin.get_order!(id) render(conn, "show.html", order: order) end end <|start_filename|>lib/shopix/front/order.ex<|end_filename|> defmodule Shopix.Front.Order do import Ecto.Changeset alias Shopix.Front alias Shopix.Schema.{Order, LineItem} def changeset(%Order{} = order, attrs) do order |> cast(attrs, []) |> cast_assoc(:line_items, with: &Front.LineItem.changeset/2) end def changeset_address(%Order{} = order, attrs) do order |> cast(attrs, [ :email, :first_name, :last_name, :company_name, :address_1, :address_2, :zip_code, :city, :country_state, :country_code, :phone ]) |> validate_required([ :email, :first_name, :last_name, :address_1, :zip_code, :city, :country_code, :phone ]) |> validate_format(:email, ~r/@/) end def changeset_payment(%Order{} = order, %{ vat_percentage: vat_percentage, shipping_cost_default_amount: shipping_cost_default_amount }) do order |> change() |> put_assoc(:line_items, Enum.map(order.line_items, &LineItem.changeset_cache(&1))) |> put_change(:completed_at, NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second)) |> put_change( :shipping_cost_amount, Shopix.ShippingCostCalculator.shipping_cost_for(order, shipping_cost_default_amount) ) |> put_change(:vat_percentage, vat_percentage) end end <|start_filename|>priv/repo/migrations/20170705131856_add_images_group_url_to_users.exs<|end_filename|> defmodule Shopix.Repo.Migrations.AddImagesGroupUrlToUsers do use Ecto.Migration def change do alter table(:products) do add :images_group_url, :string end end end <|start_filename|>priv/repo/migrations/20170713235328_rename_orders_state_to_country_state.exs<|end_filename|> defmodule Shopix.Repo.Migrations.RenameOrdersStateToCountryState do use Ecto.Migration def change do rename table(:orders), :state, to: :country_state end end <|start_filename|>lib/shopix_web/views/api/product_view.ex<|end_filename|> defmodule ShopixWeb.Api.ProductView do use ShopixWeb, :view def render("index.json", %{products: products, locale: locale, page: page}) do %{ products: Enum.map(products, &related_product_json(&1, locale)), locale: locale, page_size: page.page_size, total_pages: page.total_pages } end def render("show.json", %{ product: product, related_products: related_products, locale: locale, previous_product: previous_product, next_product: next_product }) do %{ product: product_json(product, locale), related_products: Enum.map(related_products, &related_product_json(&1, locale)), previous_product: related_product_json(previous_product, locale), next_product: related_product_json(next_product, locale), locale: locale } end def product_json(product, locale) do %{ id: product.id, sku: product.sku, price: product.price, name: product.name_translations[locale], description: product.description_translations[locale], properties: Enum.map(product.product_properties, &product_property_json(&1, locale)), images: images_with_index(product), slug: t_field(product, :slug, locale) } end def related_product_json(nil, _), do: nil def related_product_json(product, locale) do %{ id: product.id, slug: t_field(product, :slug, locale), thumb_url: thumb_url(product), name: product.name_translations[locale], price: product.price } end def product_property_json(product_property, locale) do %{ key: product_property.property.key, name: t_field(product_property.property, :name, locale), value: t_field(product_property, :value, locale) } end end <|start_filename|>lib/shopix_web/views/admin/global_config_view.ex<|end_filename|> defmodule ShopixWeb.Admin.GlobalConfigView do use ShopixWeb, :view end <|start_filename|>lib/shopix/shipping_cost_calculator.ex<|end_filename|> defmodule Shopix.ShippingCostCalculator do alias Shopix.Schema.Order def shipping_cost_amount(shipping_cost_default_amount) do Money.new(shipping_cost_default_amount) end def shipping_cost_for(%Order{} = _order, shipping_cost_default_amount), do: shipping_cost_amount(shipping_cost_default_amount) end <|start_filename|>lib/shopix_web/plugs/current_user.ex<|end_filename|> defmodule ShopixWeb.Plug.CurrentUser do import Plug.Conn alias Shopix.Guardian def init(opts), do: opts def call(conn, _opts) do current_user = Guardian.Plug.current_resource(conn, key: :admin) conn |> assign(:current_user, current_user) end end <|start_filename|>.iex.exs<|end_filename|> import Ecto.Query alias Decimal, as: D alias Ecto.Changeset alias Shopix.{Repo, Admin, Schema, Front, Mailer} alias ShopixWeb.Email use Timex <|start_filename|>test/createurs_web/controllers/admin/translation_controller_test.exs<|end_filename|> defmodule ShopixWeb.Admin.TranslationControllerTest do use ShopixWeb.ConnCase, async: true @valid_attrs %{key: "foo_bar", value_fr: "Bonjour", value_en: "Hello"} @update_attrs %{key: "new_foo_bar", value_fr: "Salut", value_en: "Hi"} @invalid_attrs %{key: ""} test "index/2 responds with the translations" do insert(:translation, key: "foo-bar") conn = guardian_login(insert(:user)) |> get(admin_translation_path(build_conn(), :index)) assert html_response(conn, 200) assert conn.resp_body =~ "foo-bar" end test "new/2 responds with a form for a new translation" do conn = guardian_login(insert(:user)) |> get(admin_translation_path(build_conn(), :new)) assert html_response(conn, 200) assert conn.resp_body =~ "New translation" end test "create/2 with valid attributes redirects and sets flash" do conn = guardian_login(insert(:user)) |> post(admin_translation_path(build_conn(), :create), %{"translation" => @valid_attrs}) assert html_response(conn, 302) assert get_flash(conn, :info) =~ "successfully" end test "create/2 with invalid attributes renders form" do conn = guardian_login(insert(:user)) |> post(admin_translation_path(build_conn(), :create), %{"translation" => @invalid_attrs}) assert html_response(conn, 200) assert conn.resp_body =~ "New translation" end test "edit/2 responds with the edition of the translation" do translation = insert(:translation) conn = guardian_login(insert(:user)) |> get(admin_translation_path(build_conn(), :edit, translation.id)) assert html_response(conn, 200) assert conn.resp_body =~ "Edit translation" end test "update/2 with valid attributes redirects and sets flash" do translation = insert(:translation) conn = guardian_login(insert(:user)) |> put(admin_translation_path(build_conn(), :update, translation.id), %{ "translation" => @update_attrs }) assert html_response(conn, 302) assert get_flash(conn, :info) =~ "successfully" end test "update/2 with invalid attributes renders form" do translation = insert(:translation) conn = guardian_login(insert(:user)) |> put(admin_translation_path(build_conn(), :update, translation.id), %{ "translation" => @invalid_attrs }) assert html_response(conn, 200) assert conn.resp_body =~ "Edit translation" end test "delete/2 redirects and sets flash" do translation = insert(:translation) conn = guardian_login(insert(:user)) |> delete(admin_translation_path(build_conn(), :update, translation.id)) assert html_response(conn, 302) assert get_flash(conn, :info) =~ "successfully" end end <|start_filename|>lib/shopix_web/views/admin/session_view.ex<|end_filename|> defmodule ShopixWeb.Admin.SessionView do use ShopixWeb, :view end <|start_filename|>lib/shopix_web/views/admin/order_view.ex<|end_filename|> defmodule ShopixWeb.Admin.OrderView do use ShopixWeb, :view end <|start_filename|>test/createurs_web/controllers/admin/property_controller_test.exs<|end_filename|> defmodule ShopixWeb.Admin.PropertyControllerTest do use ShopixWeb.ConnCase, async: true @valid_attrs %{key: "foo-bar", name_fr: "Hauteur", name_en: "Height"} @update_attrs %{key: "new-foo-bar", name_fr: "Longueur", name_en: "Length"} @invalid_attrs %{key: ""} test "index/2 responds with the propertys" do insert(:property, key: "foo-bar") conn = guardian_login(insert(:user)) |> get(admin_property_path(build_conn(), :index)) assert html_response(conn, 200) assert conn.resp_body =~ "foo-bar" end test "new/2 responds with a form for a new property" do conn = guardian_login(insert(:user)) |> get(admin_property_path(build_conn(), :new)) assert html_response(conn, 200) assert conn.resp_body =~ "New property" end test "create/2 with valid attributes redirects and sets flash" do conn = guardian_login(insert(:user)) |> post(admin_property_path(build_conn(), :create), %{"property" => @valid_attrs}) assert html_response(conn, 302) assert get_flash(conn, :info) =~ "successfully" end test "create/2 with invalid attributes renders form" do conn = guardian_login(insert(:user)) |> post(admin_property_path(build_conn(), :create), %{"property" => @invalid_attrs}) assert html_response(conn, 200) assert conn.resp_body =~ "New property" end test "edit/2 responds with the edition of the property" do property = insert(:property) conn = guardian_login(insert(:user)) |> get(admin_property_path(build_conn(), :edit, property.id)) assert html_response(conn, 200) assert conn.resp_body =~ "Edit property" end test "update/2 with valid attributes redirects and sets flash" do property = insert(:property) conn = guardian_login(insert(:user)) |> put(admin_property_path(build_conn(), :update, property.id), %{ "property" => @update_attrs }) assert html_response(conn, 302) assert get_flash(conn, :info) =~ "successfully" end test "update/2 with invalid attributes renders form" do property = insert(:property) conn = guardian_login(insert(:user)) |> put(admin_property_path(build_conn(), :update, property.id), %{ "property" => @invalid_attrs }) assert html_response(conn, 200) assert conn.resp_body =~ "Edit property" end test "delete/2 redirects and sets flash" do property = insert(:property) conn = guardian_login(insert(:user)) |> delete(admin_property_path(build_conn(), :update, property.id)) assert html_response(conn, 302) assert get_flash(conn, :info) =~ "successfully" end end <|start_filename|>lib/shopix_web/plugs/locale.ex<|end_filename|> defmodule ShopixWeb.Plug.Locale do import Plug.Conn def init(opts), do: opts def call( %Plug.Conn{ params: %{"locale" => locale}, assigns: %{global_config: %{available_locales: available_locales}} } = conn, _opts ) do if locale in available_locales do conn |> assign(:current_locale, locale) else conn |> Phoenix.Controller.redirect(to: "/") |> halt() end end def call(%Plug.Conn{assigns: %{global_config: %{default_locale: default_locale}}} = conn, _opts) do conn |> assign(:current_locale, default_locale) end end <|start_filename|>lib/shopix_web/views/api/shop_view.ex<|end_filename|> defmodule ShopixWeb.Api.ShopView do use ShopixWeb, :view def render("show.json", %{global_config: global_config}) do %{ global_config: global_config_json(global_config) } end def global_config_json(global_config) do %{ default_locale: global_config.default_locale, available_locales: global_config.available_locales } end end <|start_filename|>lib/shopix/admin/property.ex<|end_filename|> defmodule Shopix.Admin.Property do import Ecto.Changeset use Shopix.TranslationFields, translated_fields: ~w(name) alias Shopix.Schema.Property def changeset(%Property{} = property, attrs) do property |> cast(attrs, [:key] ++ localized_fields()) |> validate_required([:key]) |> validate_format(:key, ~r/\A[a-z0-9\-_]{3,}\z/) |> unique_constraint(:key) end end <|start_filename|>test/createurs_web/plugs/admin_locale_test.exs<|end_filename|> defmodule ShopixWeb.Plug.AdminLocaleTest do use ShopixWeb.ConnCase, async: true alias ShopixWeb.Plug.AdminLocale test "call/2 when there is no current admin locale sets default locale" do conn = build_conn() |> bypass_through(ShopixWeb.Router, [:browser]) |> get("/") |> AdminLocale.call(%{}) assert conn.assigns.admin_current_locale == "en" end test "call/2 when there is a current admin locale sets the admin locale" do conn = build_conn() |> bypass_through(ShopixWeb.Router, [:browser]) |> get("/") |> put_session(:admin_current_locale, "fr") |> AdminLocale.call(%{}) assert conn.assigns.admin_current_locale == "fr" end end <|start_filename|>lib/shopix_web/views/front/home_view.ex<|end_filename|> defmodule ShopixWeb.Front.HomeView do use ShopixWeb, :view end <|start_filename|>lib/shopix_web/controllers/admin/session_controller.ex<|end_filename|> defmodule ShopixWeb.Admin.SessionController do use ShopixWeb, :controller plug :put_layout, "basic.html" alias Shopix.{Admin, Guardian} def new(conn, _params) do render(conn, "new.html") end def create(conn, %{"credentials" => credentials_params}) do case Admin.find_and_confirm_password(credentials_params) do {:ok, user} -> conn |> Guardian.Plug.sign_in(user, %{}, key: :admin) |> put_flash(:info, "Logged in successfully.") |> redirect(to: "/admin") {:error, _} -> render(conn, "new.html") end end def delete(conn, _params) do conn |> Guardian.Plug.sign_out(key: :admin) |> put_flash(:info, "Logged out successfully.") |> redirect(to: "/") end def unauthenticated(conn, _params) do conn |> put_flash(:error, "Authentication required.") |> redirect(to: admin_session_path(conn, :new)) end end <|start_filename|>lib/shopix_web/views/admin/page_view.ex<|end_filename|> defmodule ShopixWeb.Admin.PageView do use ShopixWeb, :view end <|start_filename|>lib/shopix/schema/global_config.ex<|end_filename|> defmodule Shopix.Schema.GlobalConfig do use Ecto.Schema schema "global_config" do field :name, :string, default: "My shop" field :vat_percentage, :decimal, default: Decimal.new(20) field :shop_opened, :boolean, default: true field :default_locale, :string, default: "en" field :available_locales, {:array, :string}, default: ["en"] field :emails_from, :string, default: "<EMAIL>" field :default_timezone, :string, default: "Europe/Paris" field :payment_gateway, :map, default: %{} field :shipping_cost_default_amount, :integer, default: 0 field :upload_provider_public_key, :string end end <|start_filename|>lib/shopix_web/plugs/admin_locale.ex<|end_filename|> defmodule ShopixWeb.Plug.AdminLocale do import Plug.Conn def init(opts), do: opts def call(conn, _opts) do locale = get_session(conn, :admin_current_locale) || "en" Gettext.put_locale(ShopixWeb.Gettext, locale) conn |> assign(:admin_current_locale, locale) end end <|start_filename|>lib/shopix_web/views/admin/translation_view.ex<|end_filename|> defmodule ShopixWeb.Admin.TranslationView do use ShopixWeb, :view end <|start_filename|>lib/shopix_web/controllers/api/product_controller.ex<|end_filename|> defmodule ShopixWeb.Api.ProductController do use ShopixWeb, :controller alias Shopix.Front def index(conn, %{"page" => _page} = params) do page = Front.list_products(params) render(conn, "index.json", products: page.entries, locale: conn.assigns.current_locale, page: page ) end def show(conn, %{"id" => id}) do product = Front.get_product_by_slug!(id, conn.assigns.current_locale) related_products = Front.get_related_products(product.id) next_product = Front.next_product(product) previous_product = Front.previous_product(product) render(conn, "show.json", product: product, locale: conn.assigns.current_locale, related_products: related_products, next_product: next_product, previous_product: previous_product ) end end <|start_filename|>priv/repo/migrations/20170712021409_alter_products_price_to_integer.exs<|end_filename|> defmodule Shopix.Repo.Migrations.AlterProductsPriceToInteger do use Ecto.Migration def change do alter table(:products) do modify :price, :integer end end end <|start_filename|>lib/shopix_web/views/translation_helpers.ex<|end_filename|> defmodule ShopixWeb.TranslationHelpers do alias Shopix.Front alias Shopix.Repo def t_field(data, field, locale) do case Map.get(data, :"#{field}_translations") do nil -> "" translations_field -> Map.get(translations_field, locale) || "" end end def root_path_unless_default_locale( %{assigns: %{global_config: %{default_locale: default_locale}}}, locale ) do if locale == default_locale, do: "/", else: "/#{locale}" end def locales_filled_on( %{assigns: %{global_config: %{available_locales: available_locales}}}, data, field ) do available_locales |> Enum.filter(fn locale -> t_field(data, field, locale) != "" end) end def t_slug(data, locale) do t_field(data, :slug, locale) end def t(conn, key, opts \\ []) def t(conn, "." <> key, _opts) do translation_key = "#{conn.assigns.translation_key}.#{key}" t(conn, translation_key) end def t(conn, key, opts) do t_result = case translate_field_or_create(conn, key) do nil -> key "" -> key result -> result end if opts[:plain], do: t_result, else: {:safe, t_result} end defp translate_field_or_create(conn, key) do if translation = translation_from_assigns(conn, key) do t_field(translation, :value, conn.assigns.current_locale) else create_translation(key) end end defp create_translation(key) do if Application.get_env(:shopix, :create_translations_on_front) do Front.Translation.changeset_create_key(key) |> Repo.insert() end nil end defp translation_from_assigns(conn, key) do conn.assigns.translations |> Enum.find(fn translation -> translation.key == key end) end end <|start_filename|>test/createurs/admin/page_test.exs<|end_filename|> defmodule Shopix.Admin.PageTest do use ExUnit.Case, async: true alias Shopix.Admin alias Shopix.Schema.Page describe "changeset/2" do test "returns a changeset" do assert %Ecto.Changeset{} = Admin.Page.changeset(%Page{}, %{}) end test "validates requirements" do changeset = Admin.Page.changeset(%Page{}, %{}) assert changeset.valid? == false assert {_, [validation: :required]} = changeset.errors[:key] end end end <|start_filename|>test/createurs/admin/admin_translation_test.exs<|end_filename|> defmodule Shopix.Admin.AdminTranslationTest do use Shopix.DataCase, async: true alias Shopix.Admin alias Shopix.Schema.Translation @valid_attrs %{key: "foo_bar", value_translations: %{"fr" => "Bonjour", "en" => "Hello"}} @update_attrs %{key: "new_foo_bar", value_translations: %{"fr" => "Salut", "en" => "Hi"}} @invalid_attrs %{key: ""} test "list_translations/1 returns all translations paginated" do translation = insert(:translation) assert %{entries: translations} = Admin.list_translations(%{}) assert translations == [translation] end test "get_translation!/1 returns the translation with given id" do translation = insert(:translation) assert Admin.get_translation!(translation.id) == translation end test "create_translation/1 with valid data creates a translation" do assert {:ok, %Translation{} = translation} = Admin.create_translation(@valid_attrs) assert translation.key == "foo_bar" assert translation.value_translations["en"] == "Hello" assert translation.value_translations["fr"] == "Bonjour" end test "create_translation/1 with invalid data returns error changeset" do assert {:error, %Ecto.Changeset{}} = Admin.create_translation(@invalid_attrs) end test "update_translation/2 with valid data updates the translation" do translation = insert(:translation) assert {:ok, translation} = Admin.update_translation(translation, @update_attrs) assert %Translation{} = translation assert translation.key == "new_foo_bar" assert translation.value_translations["en"] == "Hi" assert translation.value_translations["fr"] == "Salut" end test "update_translation/2 with invalid data returns error changeset" do translation = insert(:translation) assert {:error, %Ecto.Changeset{}} = Admin.update_translation(translation, @invalid_attrs) assert Admin.get_translation!(translation.id) == translation end test "delete_translation/1 deletes the translation" do translation = insert(:translation) assert {:ok, %Translation{}} = Admin.delete_translation(translation) assert_raise Ecto.NoResultsError, fn -> Admin.get_translation!(translation.id) end end test "change_translation/1 returns a translation changeset" do translation = insert(:translation) assert %Ecto.Changeset{} = Admin.change_translation(translation) end end <|start_filename|>test/createurs/front/order_test.exs<|end_filename|> defmodule Shopix.Front.OrderTest do use ExUnit.Case, async: true alias Shopix.Front alias Shopix.Schema.Order describe "changeset/2" do test "returns a changeset" do assert %Ecto.Changeset{} = Front.Order.changeset(%Order{}, %{}) end end describe "changeset_address/2" do test "returns a changeset" do assert %Ecto.Changeset{} = Front.Order.changeset_address(%Order{}, %{}) end test "validates requirements" do changeset = Front.Order.changeset_address(%Order{}, %{}) assert changeset.valid? == false assert {_, [validation: :required]} = changeset.errors[:email] assert {_, [validation: :required]} = changeset.errors[:first_name] assert {_, [validation: :required]} = changeset.errors[:last_name] assert {_, [validation: :required]} = changeset.errors[:address_1] assert {_, [validation: :required]} = changeset.errors[:zip_code] assert {_, [validation: :required]} = changeset.errors[:city] assert {_, [validation: :required]} = changeset.errors[:country_code] assert {_, [validation: :required]} = changeset.errors[:phone] end test "validates format" do changeset = Front.Order.changeset_address(%Order{}, %{email: "foobar"}) assert changeset.valid? == false assert {_, [validation: :format]} = changeset.errors[:email] end end end <|start_filename|>lib/shopix/translation_fields.ex<|end_filename|> defmodule Shopix.TranslationFields do @moduledoc """ Usage: defmodule Product do use Ecto.Schema import Ecto.Changeset use Shopix.TranslationFields, slug: :name, translated_fields: ~w(name description slug) schema "products" do field :price, :integer field :sku, :string field :slug, :string schema_translation_fields() timestamps() end Then for each `translated_fields` it will define one persistent field containing the translations as a map (named `fieldname_translations`). """ defmacro __using__(opts) do quote do import Ecto.Changeset import Shopix.TranslationFields @translated_fields unquote(opts[:translated_fields]) if unquote(opts[:slug]) do @slug unquote(opts[:slug]) def slugify_map(data) do data |> Enum.reject(fn {_, v} -> is_nil(v) end) |> Enum.map(fn {locale, value} -> {locale, Slugger.slugify_downcase(value)} end) |> Map.new() end def change_slugs(data) do if slug_map = get_field(data, :"#{@slug}_translations") do data |> put_change(:slug_translations, slugify_map(slug_map)) else data end end end def localized_fields do @translated_fields |> Enum.map(fn field -> :"#{field}_translations" end) end end end defmacro schema_translation_fields do quote do @translated_fields |> Enum.each(fn field -> field :"#{field}_translations", :map, default: %{} end) end end end <|start_filename|>lib/shopix/schema/group.ex<|end_filename|> defmodule Shopix.Schema.Group do use Ecto.Schema alias Shopix.Schema.Product schema "groups" do field :key, :string many_to_many :products, Product, join_through: "products_groups" timestamps() end end <|start_filename|>lib/shopix_web/controllers/api/page_controller.ex<|end_filename|> defmodule ShopixWeb.Api.PageController do use ShopixWeb, :controller alias Shopix.Front def show(conn, %{"id" => id}) do locale = conn.assigns.current_locale page = Front.get_page_by_slug!(id, locale) render(conn, "show.json", page: page, locale: locale) end end <|start_filename|>test/createurs_web/controllers/admin/user_controller_test.exs<|end_filename|> defmodule ShopixWeb.Admin.UserControllerTest do use ShopixWeb.ConnCase, async: true @valid_attrs %{email: "<EMAIL>", password: "<PASSWORD>"} @update_attrs %{email: "<EMAIL>", password: "<PASSWORD>"} @invalid_attrs %{email: nil, password: nil} test "index/2 responds with the users" do insert(:user, email: "<EMAIL>") conn = guardian_login(insert(:user)) |> get(admin_user_path(build_conn(), :index)) assert html_response(conn, 200) assert conn.resp_body =~ "<EMAIL>" end test "new/2 responds with a form for a new user" do conn = guardian_login(insert(:user)) |> get(admin_user_path(build_conn(), :new)) assert html_response(conn, 200) assert conn.resp_body =~ "New administration user" end test "create/2 with valid attributes redirects and sets flash" do conn = guardian_login(insert(:user)) |> post(admin_user_path(build_conn(), :create), %{"user" => @valid_attrs}) assert html_response(conn, 302) assert get_flash(conn, :info) =~ "successfully" end test "create/2 with invalid attributes renders form" do conn = guardian_login(insert(:user)) |> post(admin_user_path(build_conn(), :create), %{"user" => @invalid_attrs}) assert html_response(conn, 200) assert conn.resp_body =~ "New administration user" end test "edit/2 responds with the edition of the user" do user = insert(:user) conn = guardian_login(insert(:user)) |> get(admin_user_path(build_conn(), :edit, user.id)) assert html_response(conn, 200) assert conn.resp_body =~ "Edit administration user" end test "update/2 with valid attributes redirects and sets flash" do user = insert(:user) conn = guardian_login(insert(:user)) |> put(admin_user_path(build_conn(), :update, user.id), %{"user" => @update_attrs}) assert html_response(conn, 302) assert get_flash(conn, :info) =~ "successfully" end test "update/2 with invalid attributes renders form" do user = insert(:user) conn = guardian_login(insert(:user)) |> put(admin_user_path(build_conn(), :update, user.id), %{"user" => @invalid_attrs}) assert html_response(conn, 200) assert conn.resp_body =~ "Edit administration user" end test "delete/2 redirects and sets flash" do user = insert(:user) conn = guardian_login(insert(:user)) |> delete(admin_user_path(build_conn(), :update, user.id)) assert html_response(conn, 302) assert get_flash(conn, :info) =~ "successfully" end end <|start_filename|>lib/shopix_web/controllers/admin/translation_controller.ex<|end_filename|> defmodule ShopixWeb.Admin.TranslationController do use ShopixWeb, :controller alias Shopix.Schema.Translation alias Shopix.Admin def index(conn, params) do page = Admin.list_translations(params) render(conn, "index.html", translations: page.entries, page: page ) end def new(conn, _params) do changeset = Admin.change_translation(%Translation{}) render(conn, "new.html", changeset: changeset) end def create(conn, %{"translation" => translation_params}) do case Admin.create_translation(translation_params) do {:ok, _} -> conn |> put_flash(:info, "Translation created successfully.") |> redirect(to: admin_translation_path(conn, :index)) {:error, %Ecto.Changeset{} = changeset} -> render(conn, "new.html", changeset: changeset) end end def edit(conn, %{"id" => id}) do translation = Admin.get_translation!(id) changeset = Admin.change_translation(translation) render(conn, "edit.html", translation: translation, changeset: changeset) end def update(conn, %{"id" => id, "translation" => translation_params}) do translation = Admin.get_translation!(id) case Admin.update_translation(translation, translation_params) do {:ok, _} -> conn |> put_flash(:info, "Translation updated successfully.") |> redirect( to: admin_translation_path( conn, :index, options_reject_nil( to_translate: conn.params["to_translate"], page: conn.params["page"] ) ) ) {:error, %Ecto.Changeset{} = changeset} -> render(conn, "edit.html", translation: translation, changeset: changeset) end end def delete(conn, %{"id" => id}) do translation = Admin.get_translation!(id) {:ok, _translation} = Admin.delete_translation(translation) conn |> put_flash(:info, "Translation deleted successfully.") |> redirect(to: admin_translation_path(conn, :index)) end end <|start_filename|>priv/repo/migrations/20170708175006_create_orders_table.exs<|end_filename|> defmodule Shopix.Repo.Migrations.CreateOrdersTable do use Ecto.Migration def change do create table(:orders) do add :fist_name, :string add :last_name, :string add :company_name, :string add :address_1, :string add :address_2, :string add :zip_code, :string add :city, :string add :state, :string add :country_code, :string add :phone, :string add :checkout_begun_at, :naive_datetime timestamps() end end end <|start_filename|>lib/shopix/admin/product.ex<|end_filename|> defmodule Shopix.Admin.Product do import Ecto.{Changeset, Query} use Shopix.TranslationFields, slug: :name, translated_fields: ~w(name description slug) alias Shopix.Repo alias Shopix.Schema.{Product, Group} def changeset(%Product{} = product, attrs) do product |> cast(attrs, [:sku, :price, :images_group_url, :displayed] ++ localized_fields()) |> cast_assoc(:product_properties, with: &Shopix.Admin.ProductProperty.changeset/2) |> change_slugs() |> validate_required([:sku, :price]) |> update_groups(attrs) |> unique_constraint(:sku, name: :products_lower_sku_index) end def update_groups(changeset, %{"group_ids" => ""}), do: put_assoc(changeset, :groups, []) def update_groups(changeset, %{"group_ids" => group_ids}) do groups = Repo.all(from g in Group, where: g.id in ^group_ids) put_assoc(changeset, :groups, groups) end def update_groups(changeset, _), do: changeset end <|start_filename|>lib/shopix/admin/group.ex<|end_filename|> defmodule Shopix.Admin.Group do import Ecto.Changeset alias Shopix.Schema.Group def changeset(%Group{} = group, attrs) do group |> cast(attrs, [:key]) |> validate_required([:key]) |> validate_format(:key, ~r/\A[a-z0-9\-_]{3,}\z/) |> unique_constraint(:key) end end <|start_filename|>lib/shopix_web/controllers/admin/product_controller.ex<|end_filename|> defmodule ShopixWeb.Admin.ProductController do use ShopixWeb, :controller alias Shopix.Schema.{Product, Group} alias Shopix.{Admin, Repo} alias Ecto.Changeset def index(conn, params) do page = Admin.list_products(params) render(conn, "index.html", products: page.entries, page: page ) end def new(conn, _params) do changeset = Admin.change_product(%Product{}) render(conn, "new.html", changeset: changeset, properties: Admin.list_properties(), groups: Repo.all(Group), product_properties: Changeset.get_field(changeset, :product_properties) ) end def create(conn, %{"product" => product_params}) do case Admin.create_product(product_params) do {:ok, _} -> conn |> put_flash(:info, "Product created successfully.") |> redirect(to: admin_product_path(conn, :index)) {:error, %Changeset{} = changeset} -> render(conn, "new.html", changeset: changeset, properties: Admin.list_properties(), groups: Repo.all(Group), product_properties: Changeset.get_field(changeset, :product_properties) ) end end def edit(conn, %{"id" => id}) do product = Admin.get_product!(id) changeset = Admin.change_product(product) render(conn, "edit.html", product: product, changeset: changeset, properties: Admin.list_properties(), groups: Repo.all(Group), product_properties: Changeset.get_field(changeset, :product_properties) ) end def update(conn, %{"id" => id, "product" => product_params}) do product = Admin.get_product!(id) case Admin.update_product(product, product_params) do {:ok, _} -> conn |> put_flash(:info, "Product updated successfully.") |> redirect( to: admin_product_path(conn, :index, options_reject_nil(page: conn.params["page"])) ) {:error, %Changeset{} = changeset} -> render(conn, "edit.html", product: product, changeset: changeset, properties: Admin.list_properties(), groups: Repo.all(Group), product_properties: Changeset.get_field(changeset, :product_properties) ) end end def delete(conn, %{"id" => id}) do product = Admin.get_product!(id) {:ok, _product} = Admin.delete_product(product) conn |> put_flash(:info, "Product deleted successfully.") |> redirect(to: admin_product_path(conn, :index)) end end <|start_filename|>lib/shopix_web/views/date_helpers.ex<|end_filename|> defmodule ShopixWeb.DateHelpers do def datetime_format(%{default_timezone: default_timezone}, datetime) do Timex.Timezone.convert(datetime, default_timezone) |> Timex.format!("%d/%m/%Y %H:%M", :strftime) end end <|start_filename|>test/createurs/shipping_cost_calculator_test.exs<|end_filename|> defmodule Shopix.ShippingCostCalculatorTest do use ExUnit.Case, async: true alias Shopix.ShippingCostCalculator alias Shopix.Schema.Order describe "shipping_cost_amount/0" do test "returns a Money struct" do assert %Money{} = ShippingCostCalculator.shipping_cost_amount(10) end end describe "shipping_cost_for/1" do test "returns the shipping cost for a given order" do assert %Money{} = ShippingCostCalculator.shipping_cost_for(%Order{}, 10) end end end <|start_filename|>test/createurs_web/controllers/admin/group_controller_test.exs<|end_filename|> defmodule ShopixWeb.Admin.GroupControllerTest do use ShopixWeb.ConnCase, async: true @valid_attrs %{key: "yay"} @update_attrs %{key: "yay-2"} @invalid_attrs %{key: nil} test "index/2 responds with the groups" do insert(:group, key: "foo-bar") conn = guardian_login(insert(:user)) |> get(admin_group_path(build_conn(), :index)) assert html_response(conn, 200) assert conn.resp_body =~ "foo-bar" end test "new/2 responds with a form for a new group" do conn = guardian_login(insert(:user)) |> get(admin_group_path(build_conn(), :new)) assert html_response(conn, 200) assert conn.resp_body =~ "New group" end test "create/2 with valid attributes redirects and sets flash" do conn = guardian_login(insert(:user)) |> post(admin_group_path(build_conn(), :create), %{"group" => @valid_attrs}) assert html_response(conn, 302) assert get_flash(conn, :info) =~ "successfully" end test "create/2 with invalid attributes renders form" do conn = guardian_login(insert(:user)) |> post(admin_group_path(build_conn(), :create), %{"group" => @invalid_attrs}) assert html_response(conn, 200) assert conn.resp_body =~ "New group" end test "edit/2 responds with the edition of the group" do group = insert(:group) conn = guardian_login(insert(:user)) |> get(admin_group_path(build_conn(), :edit, group.id)) assert html_response(conn, 200) assert conn.resp_body =~ "Edit group" end test "update/2 with valid attributes redirects and sets flash" do group = insert(:group) conn = guardian_login(insert(:user)) |> put(admin_group_path(build_conn(), :update, group.id), %{"group" => @update_attrs}) assert html_response(conn, 302) assert get_flash(conn, :info) =~ "successfully" end test "update/2 with invalid attributes renders form" do group = insert(:group) conn = guardian_login(insert(:user)) |> put(admin_group_path(build_conn(), :update, group.id), %{"group" => @invalid_attrs}) assert html_response(conn, 200) assert conn.resp_body =~ "Edit group" end test "delete/2 redirects and sets flash" do group = insert(:group) conn = guardian_login(insert(:user)) |> delete(admin_group_path(build_conn(), :update, group.id)) assert html_response(conn, 302) assert get_flash(conn, :info) =~ "successfully" end end <|start_filename|>config/config.exs<|end_filename|> # This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. # # This configuration file is loaded before any dependency and # is restricted to this project. use Mix.Config # General application configuration config :shopix, ecto_repos: [Shopix.Repo] # Configures the endpoint config :shopix, ShopixWeb.Endpoint, url: [host: "localhost"], secret_key_base: "<KEY>", render_errors: [view: ShopixWeb.ErrorView, accepts: ~w(html json)], pubsub: [name: Shopix.PubSub, adapter: Phoenix.PubSub.PG2] config :shopix, create_translations_on_front: true # Configures Elixir's Logger config :logger, :console, format: "$time $metadata[$level] $message\n", metadata: [:request_id] config :phoenix, :template_engines, slim: PhoenixSlime.Engine, slime: PhoenixSlime.Engine config :phoenix, :json_library, Jason config :shopix, Shopix.Guardian, issuer: "shopix", secret_key: "2PsWyRBou2HTTI6iPoLm0YOuwlA0W8iEBn8/Uo1rvIuT7de9OGp9VE7a0YLra8Kw" config :bootform, gettext_backend: ShopixWeb.Gettext config :money, default_currency: :EUR, separator: " ", delimeter: ",", symbol: true, symbol_on_right: true, symbol_space: true config :scrivener_html, routes_helper: ShopixWeb.Router.Helpers, # If you use a single view style everywhere, you can configure it here. See View Styles below for more info. view_style: :bootstrap_v4 config :sentry, dsn: System.get_env("SENTRY_DSN"), enable_source_code_context: true, root_source_code_path: File.cwd!(), included_environments: ~w(production staging), environment_name: System.get_env("RELEASE_LEVEL") || "development" config :braintree, environment: :foo, merchant_id: "foobar", public_key: "foobar", private_key: "foobar" # Import environment specific config. This must remain at the bottom # of this file so it overrides the configuration defined above. import_config "#{Mix.env()}.exs" <|start_filename|>priv/repo/migrations/20170723234801_add_constraint_to_pages_and_products.exs<|end_filename|> defmodule Shopix.Repo.Migrations.AddConstraintToPagesAndProducts do use Ecto.Migration def change do create unique_index(:pages, [:key]) create unique_index(:products, ["lower(sku)"], name: :products_lower_sku_index) end end <|start_filename|>lib/shopix_web/controllers/api/shop_controller.ex<|end_filename|> defmodule ShopixWeb.Api.ShopController do use ShopixWeb, :controller def show(conn, _) do render(conn, "show.json", global_config: conn.assigns.global_config) end end <|start_filename|>test/createurs_web/controllers/admin/order_controller_test.exs<|end_filename|> defmodule ShopixWeb.Admin.OrderControllerTest do use ShopixWeb.ConnCase, async: true test "index/2 responds with the orders" do insert(:order, email: "<EMAIL>") conn = guardian_login(insert(:user)) |> get(admin_order_path(build_conn(), :index)) assert html_response(conn, 200) assert conn.resp_body =~ "<EMAIL>" end test "show/2 responds with the order" do order = insert(:order, email: "<EMAIL>") conn = guardian_login(insert(:user)) |> get(admin_order_path(build_conn(), :show, order.id)) assert html_response(conn, 200) assert conn.resp_body =~ "<EMAIL>" end end <|start_filename|>lib/shopix/schema/product.ex<|end_filename|> defmodule Shopix.Schema.Product do use Ecto.Schema use Shopix.TranslationFields, slug: :name, translated_fields: ~w(name description slug) alias Shopix.Schema.{ProductProperty, Group} schema "products" do field :price, Money.Ecto.Type field :sku, :string field :images_group_url, :string field :displayed, :boolean, default: true has_many :product_properties, ProductProperty, on_replace: :delete many_to_many :groups, Group, join_through: "products_groups", on_replace: :delete schema_translation_fields() timestamps() end end <|start_filename|>lib/shopix_web/views/admin/home_view.ex<|end_filename|> defmodule ShopixWeb.Admin.HomeView do use ShopixWeb, :view import Shopix.Admin.Statistics end <|start_filename|>lib/shopix_web/controllers/front/page_controller.ex<|end_filename|> defmodule ShopixWeb.Front.PageController do use ShopixWeb, :controller alias Shopix.Front plug ShopixWeb.Plug.Translations def show(conn, %{"id" => id}) do page = Front.get_page_by_slug!(id, conn.assigns.current_locale) template = case page.key do "contact" -> "contact.html" _ -> "show.html" end render(conn, template, page: page) end end <|start_filename|>lib/shopix/schema/order.ex<|end_filename|> defmodule Shopix.Schema.Order do use Ecto.Schema alias Shopix.Schema.{Order, LineItem} schema "orders" do has_many :line_items, LineItem, on_replace: :delete field :email, :string field :first_name, :string field :last_name, :string field :company_name, :string field :address_1, :string field :address_2, :string field :zip_code, :string field :city, :string field :country_state, :string field :country_code, :string field :phone, :string field :vat_percentage, :decimal field :completed_at, :naive_datetime field :shipping_cost_amount, Money.Ecto.Type field :total_quantity, :integer, virtual: true field :price_items, Money.Ecto.Type, virtual: true field :total_price, Money.Ecto.Type, virtual: true timestamps() end def compute_properties(%Order{} = order, config \\ %{}) do order |> compute_line_items |> compute_totals(config) end def compute_line_items(%Order{} = order) do %{order | line_items: order.line_items |> Enum.map(&LineItem.compute_properties(&1))} end def compute_totals(%Order{} = order, config) do %{ order | total_quantity: total_quantity(order), price_items: price_items(order), total_price: total_price(order, config) } end def shipping_cost_amount( %Order{shipping_cost_amount: nil} = order, shipping_cost_default_amount ) do Shopix.ShippingCostCalculator.shipping_cost_for(order, shipping_cost_default_amount) end def shipping_cost_amount(%Order{shipping_cost_amount: shipping_cost_amount}, _), do: shipping_cost_amount def total_quantity(%Order{} = order) do Enum.reduce(order.line_items, 0, fn line_item, acc -> acc + line_item.quantity end) end def price_items(%Order{} = order) do Enum.reduce(order.line_items, Money.new(0), fn line_item, acc -> Money.add(acc, line_item.total_price) end) end def total_price(%Order{} = order, config) do order |> price_items() |> Money.add(shipping_cost_amount(order, Map.get(config, :shipping_cost_default_amount))) end end <|start_filename|>lib/shopix_web/views/image_helpers.ex<|end_filename|> defmodule ShopixWeb.ImageHelpers do def image_url(data, index \\ 0) def image_url(%{images_group_url: nil}, _), do: "/img/logo.png" def image_url(%{images_group_url: images_group_url}, index) do "#{images_group_url}nth/#{index}/-/format/jpeg/image.jpg" end def thumb_url(data, index \\ 0) def thumb_url(%{images_group_url: nil}, _), do: "/img/logo.png" def thumb_url(%{images_group_url: images_group_url}, index) do "#{images_group_url}nth/#{index}/-/format/jpeg/-/preview/400x400/image.jpg" end def images_with_index(%{images_group_url: nil}) do [ %{ url: "/img/logo.png", thumb_url: "/img/logo.png", index: 0 } ] end def images_with_index(%{} = data) do case Regex.run(~r/~(\d+)\/\z/, data.images_group_url) do [_, number_of_images] -> Enum.map(0..(String.to_integer(number_of_images) - 1), fn index -> %{ url: image_url(data, index), thumb_url: thumb_url(data, index), index: index } end) nil -> nil end end end <|start_filename|>test/createurs/admin/property_test.exs<|end_filename|> defmodule Shopix.Admin.PropertyTest do use ExUnit.Case, async: true alias Shopix.Admin alias Shopix.Schema.Property describe "changeset/2" do test "returns a changeset" do assert %Ecto.Changeset{} = Admin.Property.changeset(%Property{}, %{}) end test "validates requirements" do changeset = Admin.Property.changeset(%Property{}, %{}) assert changeset.valid? == false assert {_, [validation: :required]} = changeset.errors[:key] end end end <|start_filename|>lib/shopix/admin/statistics.ex<|end_filename|> defmodule Shopix.Admin.Statistics do import Ecto.Query use Timex alias Shopix.Schema.Order alias Shopix.Schema.User alias Shopix.Repo def orders_today_count do from(o in Order, select: count(o.id), where: fragment("?::date", o.completed_at) == ^Timex.today() ) |> Repo.one() end def orders_this_week_count do from(o in Order, select: count(o.id), where: fragment("?::date", o.completed_at) >= ^(Timex.today() |> Timex.beginning_of_week()) ) |> Repo.one() end def orders_this_month_count do from(o in Order, select: count(o.id), where: fragment("?::date", o.completed_at) >= ^(Timex.today() |> Timex.beginning_of_month()) ) |> Repo.one() end def users_count do from(u in User, select: count(u.id)) |> Repo.one() end end <|start_filename|>lib/shopix_web/views/api/checkout_view.ex<|end_filename|> defmodule ShopixWeb.Api.CheckoutView do use ShopixWeb, :view alias ShopixWeb.Api.CartView def render("show.json", %{order: order, locale: locale}) do CartView.render("show.json", order: order, locale: locale) end def render("error.json", %{changeset: changeset}) do %{ errors: Ecto.Changeset.traverse_errors(changeset, &translate_error/1) } end end <|start_filename|>lib/shopix_web/email.ex<|end_filename|> defmodule ShopixWeb.Email do use Bamboo.Phoenix, view: ShopixWeb.EmailView import ShopixWeb.TranslationHelpers alias Shopix.Front alias Shopix.Schema.Order def order_complete_email(%Order{} = order, current_locale, global_config) do conn = %{ assigns: %{ translations: Front.get_translations("email.order_complete"), current_locale: current_locale } } new_email() |> to(order.email) |> from(global_config.emails_from) |> subject(t(conn, "email.order_complete.subject", plain: true)) |> render("order_complete.html", current_locale: conn.assigns.current_locale, conn: conn, order: order ) end end <|start_filename|>lib/shopix/admin/admin.ex<|end_filename|> defmodule Shopix.Admin do import Ecto.Query, warn: false alias Shopix.Repo alias Shopix.Admin alias Shopix.Schema.{Product, Group, Order, Page, User, Property, Translation, GlobalConfig} def list_products(params \\ %{}) do Product |> order_by(desc: :inserted_at) |> filter_by_group(params["group_key"]) |> Repo.paginate(params) end def filter_by_group(query, nil), do: query def filter_by_group(query, group_key) do from q in query, join: g in assoc(q, :groups), where: g.key == ^group_key end def get_product!(id) do Product |> preload([:product_properties, :groups]) |> Repo.get!(id) end def create_product(attrs \\ %{}) do %Product{} |> Admin.Product.changeset(attrs) |> Repo.insert() end def update_product(%Product{} = product, attrs) do product |> Admin.Product.changeset(attrs) |> Repo.update() end def delete_product(%Product{} = product) do Repo.delete(product) end def change_product(%Product{} = product) do product |> Admin.Product.changeset(%{}) end def list_groups(params \\ %{}) do Group |> order_by(desc: :inserted_at) |> Repo.paginate(params) end def get_group!(id) do Group |> Repo.get!(id) end def create_group(attrs \\ %{}) do %Group{} |> Admin.Group.changeset(attrs) |> Repo.insert() end def update_group(%Group{} = group, attrs) do group |> Admin.Group.changeset(attrs) |> Repo.update() end def delete_group(%Group{} = group) do Repo.delete(group) end def change_group(%Group{} = group) do group |> Admin.Group.changeset(%{}) end def list_users(params \\ %{}) do User |> order_by(desc: :inserted_at) |> Repo.paginate(params) end def get_user!(id), do: Repo.get!(User, id) def create_user(attrs \\ %{}) do %User{} |> Admin.User.changeset(attrs) |> Repo.insert() end def update_user(%User{} = user, attrs) do user |> Admin.User.changeset(attrs) |> Repo.update() end def delete_user(%User{} = user) do Repo.delete(user) end def change_user(%User{} = user) do Admin.User.changeset(user, %{}) end def find_and_confirm_password(%{"email" => email, "password" => password}) when is_binary(email) and is_binary(password) do user = Repo.get_by(User, email: email) if user && Admin.User.valid_password?(user, password) do {:ok, user} else {:error, :invalid_credentials} end end def find_and_confirm_password(_), do: {:error, :invalid_params} def list_properties(params) do Property |> order_by(desc: :inserted_at) |> Repo.paginate(params) end def list_properties() do Property |> order_by(desc: :inserted_at) |> Repo.all() end def get_property!(id) do Repo.get!(Property, id) end def create_property(attrs \\ %{}) do %Property{} |> Admin.Property.changeset(attrs) |> Repo.insert() end def update_property(%Property{} = property, attrs) do property |> Admin.Property.changeset(attrs) |> Repo.update() end def delete_property(%Property{} = property) do Repo.delete(property) end def change_property(%Property{} = property) do property |> Admin.Property.changeset(%{}) end def get_order!(id) do Order |> preload(line_items: :product) |> Repo.get!(id) |> Order.compute_properties() end def list_orders(params \\ %{}) do %{entries: orders} = page = Order |> where([o], not is_nil(o.completed_at)) |> order_by(desc: :completed_at) |> Repo.paginate(params) %{ page | entries: orders |> Repo.preload(line_items: :product) |> Enum.map(&Order.compute_properties(&1)) } end def list_translations(params \\ %{}) def list_translations(%{"to_translate" => "true"} = params) do from(t in Translation, where: t.value_translations == ^%{} or is_nil(t.value_translations)) |> order_by(desc: :inserted_at) |> Repo.paginate(params) end def list_translations(params) do Translation |> order_by(desc: :inserted_at) |> Repo.paginate(params) end def get_translation!(id), do: Repo.get!(Translation, id) def create_translation(attrs \\ %{}) do %Translation{} |> Admin.Translation.changeset(attrs) |> Repo.insert() end def update_translation(%Translation{} = translation, attrs) do translation |> Admin.Translation.changeset(attrs) |> Repo.update() end def delete_translation(%Translation{} = translation) do Repo.delete(translation) end def change_translation(%Translation{} = translation) do Admin.Translation.changeset(translation, %{}) end def list_pages(params \\ %{}) do Page |> order_by(desc: :inserted_at) |> Repo.paginate(params) end def get_page!(id), do: Repo.get!(Page, id) def create_page(attrs \\ %{}) do %Page{} |> Admin.Page.changeset(attrs) |> Repo.insert() end def update_page(%Page{} = page, attrs) do page |> Admin.Page.changeset(attrs) |> Repo.update() end def delete_page(%Page{} = page) do Repo.delete(page) end def change_page(%Page{} = page) do Admin.Page.changeset(page, %{}) end def change_global_config(%GlobalConfig{} = global_config) do Admin.GlobalConfig.changeset(global_config, %{}) end def update_global_config(%GlobalConfig{} = global_config, attrs) do global_config |> Admin.GlobalConfig.changeset(attrs) |> Repo.update() end end <|start_filename|>priv/repo/migrations/20170705231335_create_products_properties_table.exs<|end_filename|> defmodule Shopix.Repo.Migrations.CreateProductsPropertiesTable do use Ecto.Migration def change do create table(:products_properties) do add :property_id, references(:properties) add :product_id, references(:products) add :value_translations, :map timestamps() end end end <|start_filename|>lib/shopix_web/controllers/front/cart_controller.ex<|end_filename|> defmodule ShopixWeb.Front.CartController do use ShopixWeb, :controller alias Shopix.Front plug ShopixWeb.Plug.Translations def show(conn, _params) do render(conn, "show.html", order: conn.assigns.current_order) end def add(conn, %{"product_id" => product_id}) do product = Front.get_product!(product_id) order = Front.create_or_add_order_with_product!( conn.assigns.current_order, product, conn.assigns.global_config ) conn |> put_session(:order_id, order.id) |> redirect(to: cart_path(conn, :show, conn.assigns.current_locale)) end def line_item_decrease(conn, %{"line_item_id" => line_item_id}) do Front.order_line_item_decrease!(conn.assigns.current_order, line_item_id) conn |> redirect(to: cart_path(conn, :show, conn.assigns.current_locale)) end def line_item_increase(conn, %{"line_item_id" => line_item_id}) do Front.order_line_item_increase!(conn.assigns.current_order, line_item_id) conn |> redirect(to: cart_path(conn, :show, conn.assigns.current_locale)) end def line_item_delete(conn, %{"line_item_id" => line_item_id}) do Front.order_line_item_delete!(conn.assigns.current_order, line_item_id) conn |> redirect(to: cart_path(conn, :show, conn.assigns.current_locale)) end end <|start_filename|>priv/repo/migrations/20170718223953_alter_table_line_items_rename_cache_product_name.exs<|end_filename|> defmodule Shopix.Repo.Migrations.AlterTableLineItemsRenameCacheProductName do use Ecto.Migration def change do rename table(:line_items), :product_name_cache, to: :product_sku_cache end end <|start_filename|>lib/shopix/admin/global_config.ex<|end_filename|> defmodule Shopix.Admin.GlobalConfig do alias Shopix.Schema.GlobalConfig import Ecto.Changeset def changeset(%GlobalConfig{} = global_config, attrs) do global_config |> cast(attrs, [ :name, :vat_percentage, :shop_opened, :default_locale, :available_locales, :emails_from, :default_timezone, :shipping_cost_default_amount, :upload_provider_public_key ]) |> put_payment_gateway(attrs) |> validate_required([ :name, :vat_percentage, :default_locale, :available_locales, :emails_from, :default_timezone ]) end def put_payment_gateway(changeset, %{"payment_gateway" => payment_gateway_params}) do put_change(changeset, :payment_gateway, Jason.decode!(payment_gateway_params)) end def put_payment_gateway(changeset, _), do: changeset end <|start_filename|>test/createurs/vat_calculator_test.exs<|end_filename|> defmodule Shopix.VatCalculatorTest do use ExUnit.Case, async: true alias Shopix.VatCalculator describe "ati_to_et/1" do test "takes a All Tax Included price and returns an Excluded Taxes price as integer" do assert VatCalculator.ati_to_et(Decimal.from_float(20.0), 10000) == 8333 end end end <|start_filename|>lib/shopix/mailer.ex<|end_filename|> defmodule Shopix.Mailer do use Bamboo.Mailer, otp_app: :shopix end <|start_filename|>test/createurs/admin/admin_group_test.exs<|end_filename|> defmodule Shopix.Admin.AdminGroupTest do use Shopix.DataCase, async: true alias Shopix.Admin alias Shopix.Schema.Group @valid_attrs %{key: "faq"} @update_attrs %{key: "new_faq"} @invalid_attrs %{key: ""} test "list_groups/1 returns all groups paginated" do group = insert(:group) assert %{entries: groups} = Admin.list_groups(%{}) assert groups == [group] end test "get_group!/1 returns the group with given id" do group = insert(:group) assert Admin.get_group!(group.id) == group end test "create_group/1 with valid data creates a group" do assert {:ok, %Group{} = group} = Admin.create_group(@valid_attrs) assert group.key == "faq" end test "create_group/1 with invalid data returns error changeset" do assert {:error, %Ecto.Changeset{}} = Admin.create_group(@invalid_attrs) end test "update_group/2 with valid data updates the group" do group = insert(:group) assert {:ok, group} = Admin.update_group(group, @update_attrs) assert %Group{} = group assert group.key == "new_faq" end test "update_group/2 with invalid data returns error changeset" do group = insert(:group) assert {:error, %Ecto.Changeset{}} = Admin.update_group(group, @invalid_attrs) assert Admin.get_group!(group.id) == group end test "delete_group/1 deletes the group" do group = insert(:group) assert {:ok, %Group{}} = Admin.delete_group(group) assert_raise Ecto.NoResultsError, fn -> Admin.get_group!(group.id) end end test "change_group/1 returns a group changeset" do group = insert(:group) assert %Ecto.Changeset{} = Admin.change_group(group) end end <|start_filename|>priv/repo/migrations/20170827210618_add_vat_percentage_to_orders.exs<|end_filename|> defmodule Shopix.Repo.Migrations.AddVatPercentageToOrders do use Ecto.Migration def change do alter table(:orders) do add :vat_percentage, :decimal, precision: 10, scale: 2 end end end <|start_filename|>test/createurs/admin/admin_global_config_test.exs<|end_filename|> defmodule Shopix.Admin.AdminGlobalConfigTest do use Shopix.DataCase, async: true alias Shopix.Admin alias Shopix.Schema.GlobalConfig @update_attrs %{name: "My hyper cool shop"} @invalid_attrs %{name: nil} test "change_global_config/1 returns a global config changeset" do global_config = insert(:global_config) assert %Ecto.Changeset{} = Admin.change_global_config(global_config) end test "update_global_config/2 with valid data updates the global config" do global_config = insert(:global_config) assert {:ok, global_config} = Admin.update_global_config(global_config, @update_attrs) assert %GlobalConfig{} = global_config assert global_config.name == "My hyper cool shop" end test "update_global_config/2 with invalid data returns error changeset" do global_config = insert(:global_config) assert {:error, %Ecto.Changeset{}} = Admin.update_global_config(global_config, @invalid_attrs) end end <|start_filename|>lib/shopix/schema/property.ex<|end_filename|> defmodule Shopix.Schema.Property do use Ecto.Schema use Shopix.TranslationFields, translated_fields: ~w(name) schema "properties" do field :key, :string schema_translation_fields() timestamps() end end <|start_filename|>lib/shopix/guardian.ex<|end_filename|> defmodule Shopix.Guardian do use Guardian, otp_app: :shopix alias Shopix.Repo alias Shopix.Schema.User def subject_for_token(%User{} = resource, _claims) do sub = "User:#{to_string(resource.id)}" {:ok, sub} end def subject_for_token(_, _) do {:error, :reason_for_error} end def resource_from_claims(%{"sub" => "User:" <> user_id}) do resource = Repo.get(User, user_id) {:ok, resource} end def resource_from_claims(_claims) do {:error, :reason_for_error} end end <|start_filename|>lib/shopix_web/plugs/current_order.ex<|end_filename|> defmodule ShopixWeb.Plug.CurrentOrder do import Plug.Conn alias Shopix.Front def init(opts), do: opts def call(%{assigns: %{global_config: global_config}} = conn, _opts) do case get_session(conn, :order_id) do nil -> assign(conn, :current_order, nil) order_id -> assign(conn, :current_order, Front.get_order(order_id, global_config)) end end end <|start_filename|>test/createurs/admin/product_property_test.exs<|end_filename|> defmodule Shopix.Admin.ProductPropertyTest do use ExUnit.Case, async: true alias Shopix.Admin alias Shopix.Schema.ProductProperty describe "changeset/2" do test "returns a changeset" do assert %Ecto.Changeset{} = Admin.ProductProperty.changeset(%ProductProperty{}, %{}) end test "validates requirements" do changeset = Admin.ProductProperty.changeset(%ProductProperty{}, %{}) assert changeset.valid? == false assert {_, [validation: :required]} = changeset.errors[:property_id] end end end <|start_filename|>lib/shopix/release_tasks.ex<|end_filename|> defmodule Shopix.ReleaseTasks do @start_apps [ :crypto, :ssl, :postgrex, :ecto, :timex, :timex_ecto ] @myapps [ :shopix ] @repos [ Shopix.Repo ] def seed do IO.puts("Loading myapp..") # Load the code for myapp, but don't start it :ok = Application.load(:shopix) IO.puts("Starting dependencies..") # Start apps necessary for executing migrations Enum.each(@start_apps, &Application.ensure_all_started/1) # Start the Repo(s) for myapp IO.puts("Starting repos..") Enum.each(@repos, & &1.start_link(pool_size: 1)) # Run migrations Enum.each(@myapps, &run_migrations_for/1) # Run the seed script if it exists seed_script = Path.join([priv_dir(:shopix), "repo", "seeds.exs"]) if File.exists?(seed_script) do IO.puts("Running seed script..") Code.eval_file(seed_script) end # Signal shutdown IO.puts("Success!") :init.stop() end def priv_dir(app), do: "#{:code.priv_dir(app)}" defp run_migrations_for(app) do IO.puts("Running migrations for #{app}") Ecto.Migrator.run(Shopix.Repo, migrations_path(app), :up, all: true) end defp migrations_path(app), do: Path.join([priv_dir(app), "repo", "migrations"]) defp seed_path(app), do: Path.join([priv_dir(app), "repo", "seeds.exs"]) end <|start_filename|>priv/repo/migrations/20170811140706_create_global_config.exs<|end_filename|> defmodule Shopix.Repo.Migrations.CreateGlobalConfig do use Ecto.Migration def change do create table(:global_config) do add :name, :string add :vat_percentage, :decimal, precision: 10, scale: 2 add :shop_opened, :boolean add :default_locale, :string add :available_locales, {:array, :string} add :emails_from, :string add :default_timezone, :string end end end <|start_filename|>test/createurs_web/views/translation_helpers_test.exs<|end_filename|> defmodule ShopixWeb.TranslationHelpersTest do use ShopixWeb.ConnCase, async: true alias ShopixWeb.TranslationHelpers test "t_field/3 returns the translation of a field which has been translated" do data = %{value_translations: %{"en" => "foo bar", "fr" => "not"}} assert TranslationHelpers.t_field(data, :value, "en") =~ "foo bar" end test "t_field/3 returns an empty string of a field which has not been translated" do assert TranslationHelpers.t_field(%{value_translations: nil}, :value, "en") == "" assert TranslationHelpers.t_field(%{value_translations: %{"en" => nil}}, :value, "en") == "" end test "root_path_unless_default_locale/2 returns the root path if passed locale is the default locale" do assert TranslationHelpers.root_path_unless_default_locale( %{assigns: %{global_config: %{default_locale: "en"}}}, "en" ) == "/" end test "root_path_unless_default_locale/2 returns the localized path if passed locale is not the default locale" do assert TranslationHelpers.root_path_unless_default_locale( %{assigns: %{global_config: %{default_locale: "en"}}}, "fr" ) == "/fr" end test "locales_filled_on/2 returns the locales which has been set" do data = %{value_translations: %{"en" => "foo bar", "fr" => ""}} assert TranslationHelpers.locales_filled_on( %{assigns: %{global_config: %{available_locales: ["en", "fr"]}}}, data, :value ) == ["en"] end test "t_slug/2 returns the translated slug" do data = %{slug_translations: %{"en" => "the-great-foo-bar"}} assert TranslationHelpers.t_slug(data, "en") == "the-great-foo-bar" end test "t/2 returns the translation if it exists in the conn" do conn = build_conn() |> assign(:translations, [ %{key: "front.layout.title", value_translations: %{"en" => "foobar"}} ]) |> assign(:current_locale, "en") assert TranslationHelpers.t(conn, "front.layout.title") == {:safe, "foobar"} end test "t/2 returns the key if it does not exist in the conn" do conn = build_conn() |> assign(:translations, []) |> assign(:current_locale, "en") assert TranslationHelpers.t(conn, "front.layout.title") == {:safe, "front.layout.title"} end test "t/2 returns a plain translation if option :plain is passed" do conn = build_conn() |> assign(:translations, [ %{key: "front.layout.title", value_translations: %{"en" => "foobar"}} ]) |> assign(:current_locale, "en") assert TranslationHelpers.t(conn, "front.layout.title", plain: true) == "foobar" end end <|start_filename|>test/createurs/front/front_test.exs<|end_filename|> defmodule Shopix.FrontTest do use Shopix.DataCase, async: true alias Shopix.Front describe "products" do test "get_product_by_slug!/2 returns the product given a specific slug and specific locale" do product = insert(:product) product_get = Front.get_product_by_slug!("my-great-product", "en") assert product_get.id == product.id end test "get_product!/1 returns the product given a specific id" do product = insert(:product) product_get = Front.get_product!(product.id) assert product_get.id == product.id end test "first_product/0 returns the first product in the database" do product = insert(:product) insert(:product) assert Front.first_product() == product end test "previous_product/1 returns the product before the given product" do product_1 = insert(:product) product_2 = insert(:product) insert(:product) assert Front.previous_product(product_2) == product_1 end test "next_product/1 returns the product before the given product" do insert(:product) product_2 = insert(:product) product_3 = insert(:product) assert Front.next_product(product_2) == product_3 end end describe "pages" do test "get_page_by_slug!/2 returns the page given a specific slug and specific locale" do page = insert(:page) assert Front.get_page_by_slug!("a-propos", "fr") == page end end describe "translations" do test "get_translations/1 returns all the translations for a specify key with layout keys" do translation = insert(:translation) translation_layout = insert(:translation, %{key: "front.layout.name"}) assert Front.get_translations("foobar") == [translation, translation_layout] end end describe "orders" do test "get_order/1 returns the order for a specific id" do order = insert(:order) order_get = Front.get_order(order.id, %{shipping_cost_default_amount: 10}) assert order_get.id == order.id end test "get_order/1 returns nil if the specific order id is not found" do assert Front.get_order(1234, %{shipping_cost_default_amount: 10}) == nil end test "change_order/1 returns a changeset for a given order" do order = insert(:order) assert %Ecto.Changeset{} = Front.change_order(order) end test "order_validate_payment/1 updates the given order after payment" do order = insert(:order, %{completed_at: nil, shipping_cost_amount: nil}) assert {:ok, order} = Front.order_validate_payment(order, %{ vat_percentage: Decimal.new(20), shipping_cost_default_amount: 10 }) assert order.completed_at != nil assert order.shipping_cost_amount != nil end test "order_validate_address/1 updates the given order after address step when data is valid" do order = insert(:order) assert {:ok, order} = Front.order_validate_address(order, %{first_name: "Foo", last_name: "Bar"}) assert order.first_name == "Foo" assert order.last_name == "Bar" end test "order_validate_address/1 updates the given order after address step when data is invalid" do order = insert(:order) assert {:error, %Ecto.Changeset{}} = Front.order_validate_address(order, %{first_name: "", last_name: ""}) assert order.first_name == "Nicolas" assert order.last_name == "Blanco" end test "create_or_add_order_with_product!/2 with an existing order creates a line_item" do order = insert(:order) product = insert(:product) Front.create_or_add_order_with_product!(order, product, %{shipping_cost_default_amount: 10}) order = Front.get_order(order.id, %{shipping_cost_default_amount: 10}) assert order.line_items |> Enum.count() == 2 assert (order.line_items |> Enum.at(1)).quantity == 1 end test "create_or_add_order_with_product!/2 with no order creates an order and a line_item" do product = insert(:product) order = Front.create_or_add_order_with_product!(nil, product, %{shipping_cost_default_amount: 10}) order = Front.get_order(order.id, %{shipping_cost_default_amount: 10}) assert order.line_items |> Enum.count() == 1 assert (order.line_items |> Enum.at(0)).quantity == 1 end test "add_product_to_order!/2 updates the quantity of a line_item if product is already in order" do order = insert(:order) product = (order.line_items |> Enum.at(0)).product order = Front.add_product_to_order!(order, product) order = Front.get_order(order.id, %{shipping_cost_default_amount: 10}) assert order.line_items |> Enum.count() == 1 assert (order.line_items |> Enum.at(0)).quantity == 4 end test "add_product_to_order!/2 creates a line_item with a new product" do order = insert(:order, %{line_items: []}) product = insert(:product) order = Front.add_product_to_order!(order, product) order = Front.get_order(order.id, %{shipping_cost_default_amount: 10}) assert order.line_items |> Enum.count() == 1 assert (order.line_items |> Enum.at(0)).quantity == 1 end end describe "line_items" do test "get_line_item!/2 returns the line item with a specific order_id and line_item_id" do order = insert(:order) line_item = order.line_items |> Enum.at(0) line_item_get = Front.get_line_item!(order.id, line_item.id) assert line_item.id == line_item_get.id end test "get_line_item!/2 raises if no line_item is found with the provided order_id and line_item_id" do assert_raise Ecto.NoResultsError, fn -> Front.get_line_item!(1234, 5432) end end test "order_line_item_decrease!/2 decreases the quantity for a specific order and line_item_id" do order = insert(:order) line_item = order.line_items |> Enum.at(0) line_item = Front.order_line_item_decrease!(order, line_item.id) assert line_item.quantity == 2 end test "order_line_item_increase!/2 increases the quantity for a specific order and line_item_id" do order = insert(:order) line_item = order.line_items |> Enum.at(0) line_item = Front.order_line_item_increase!(order, line_item.id) assert line_item.quantity == 4 end test "order_line_item_delete!/2 deletes the line_item for a specific order and line_item_id" do order = insert(:order) line_item = order.line_items |> Enum.at(0) Front.order_line_item_delete!(order, line_item.id) order = Front.get_order(order.id, %{shipping_cost_default_amount: 10}) assert order.line_items |> Enum.empty?() == true end end end <|start_filename|>priv/repo/migrations/20170826171532_add_instagram_auth_to_admin_users.exs<|end_filename|> defmodule Shopix.Repo.Migrations.AddInstagramAuthToAdminUsers do use Ecto.Migration def change do alter table(:admin_users) do add :instagram_auth, :map, default: "{}" end end end <|start_filename|>lib/shopix_web/controllers/front/checkout_controller.ex<|end_filename|> defmodule ShopixWeb.Front.CheckoutController do use ShopixWeb, :controller alias Shopix.Schema.Order alias Ecto.Changeset alias Shopix.{Front, Mailer} alias ShopixWeb.Email plug ShopixWeb.Plug.Translations def address(conn, _params) do render(conn, "address.html", changeset: Front.change_order(conn.assigns.current_order), countries: Shopix.LocalizedCountries.countries(conn.assigns.current_locale) ) end def validate_address(conn, %{"order" => order_params}) do case Front.order_validate_address(conn.assigns.current_order, order_params) do {:ok, _} -> conn |> redirect(to: checkout_path(conn, :payment, conn.assigns.current_locale)) {:error, %Ecto.Changeset{} = changeset} -> render(conn, "address.html", changeset: changeset, countries: Shopix.LocalizedCountries.countries(conn.assigns.current_locale) ) end end def payment(conn, _params) do render(conn, "payment.html", shipping_cost_amount: Order.shipping_cost_amount( conn.assigns.current_order, conn.assigns.global_config.shipping_cost_default_amount ) ) end def validate_payment(conn, %{"payment" => %{"nonce" => payment_nonce}}) do order = conn.assigns.current_order amount = order.total_price |> Money.to_string(separator: "", delimeter: ".", symbol_space: false, symbol: false) result = Braintree.Transaction.sale( %{ amount: amount, payment_method_nonce: payment_nonce, options: %{ submit_for_settlement: true } }, braintree_options(conn.assigns.global_config) ) with {:ok, _} <- result, {:ok, order} <- Front.order_validate_payment(order, conn.assigns.global_config) do Email.order_complete_email(order, conn.assigns.current_locale, conn.assigns.global_config) |> Mailer.deliver_later() conn |> clear_session() |> redirect(to: checkout_path(conn, :complete, conn.assigns.current_locale)) else {:error, %Changeset{}} -> conn |> put_flash(:error, "Error when saving the order.") |> redirect(to: checkout_path(conn, :payment, conn.assigns.current_locale)) {:error, %Braintree.ErrorResponse{} = error} -> conn |> put_flash(:error, "Payment error: #{error.message}") |> redirect(to: checkout_path(conn, :payment, conn.assigns.current_locale)) end end defp braintree_options(global_config) do [ environment: global_config.payment_gateway["provider_config"]["environment"] |> String.to_atom(), merchant_id: global_config.payment_gateway["provider_config"]["merchant_id"], public_key: global_config.payment_gateway["provider_config"]["public_key"], private_key: global_config.payment_gateway["provider_config"]["private_key"] ] end def complete(conn, _params) do render(conn, "complete.html") end end <|start_filename|>test/createurs_web/controllers/admin/page_controller_test.exs<|end_filename|> defmodule ShopixWeb.Admin.PageControllerTest do use ShopixWeb.ConnCase, async: true @valid_attrs %{ key: "faq", name_fr: "Foire aux questions", name_en: "Frequently asked questions", content_fr: "Comment faire ci, faire ça...", content_en: "How to do this and that..." } @update_attrs %{ key: "new_faq", name_fr: "Foire aux nouvelles questions", name_en: "Frequently asked new questions", content_fr: "Comment faire ci, faire ça, lalala...", content_en: "How to do this and that and this again..." } @invalid_attrs %{"key" => ""} test "index/2 responds with the pages" do insert(:page, key: "foo-bar") conn = guardian_login(insert(:user)) |> get(admin_page_path(build_conn(), :index)) assert html_response(conn, 200) assert conn.resp_body =~ "foo-bar" end test "new/2 responds with a form for a new page" do conn = guardian_login(insert(:user)) |> get(admin_page_path(build_conn(), :new)) assert html_response(conn, 200) assert conn.resp_body =~ "New page" end test "create/2 with valid attributes redirects and sets flash" do conn = guardian_login(insert(:user)) |> post(admin_page_path(build_conn(), :create), %{"page" => @valid_attrs}) assert html_response(conn, 302) assert get_flash(conn, :info) =~ "successfully" end test "create/2 with invalid attributes renders form" do conn = guardian_login(insert(:user)) |> post(admin_page_path(build_conn(), :create), %{"page" => @invalid_attrs}) assert html_response(conn, 200) assert conn.resp_body =~ "New page" end test "edit/2 responds with the edition of the page" do page = insert(:page) conn = guardian_login(insert(:user)) |> get(admin_page_path(build_conn(), :edit, page.id)) assert html_response(conn, 200) assert conn.resp_body =~ "Edit page" end test "update/2 with valid attributes redirects and sets flash" do page = insert(:page) conn = guardian_login(insert(:user)) |> put(admin_page_path(build_conn(), :update, page.id), %{"page" => @update_attrs}) assert html_response(conn, 302) assert get_flash(conn, :info) =~ "successfully" end test "update/2 with invalid attributes renders form" do page = insert(:page) conn = guardian_login(insert(:user)) |> put(admin_page_path(build_conn(), :update, page.id), %{"page" => @invalid_attrs}) assert html_response(conn, 200) assert conn.resp_body =~ "Edit page" end test "delete/2 redirects and sets flash" do page = insert(:page) conn = guardian_login(insert(:user)) |> delete(admin_page_path(build_conn(), :update, page.id)) assert html_response(conn, 302) assert get_flash(conn, :info) =~ "successfully" end end <|start_filename|>lib/shopix_web/plugs/translations.ex<|end_filename|> defmodule ShopixWeb.Plug.Translations do alias Shopix.Front import Plug.Conn def init(opts), do: opts def call(conn, _opts) do translation_key = "#{controller_key(conn)}.#{action_key(conn)}" conn |> assign(:translations, Front.get_translations(translation_key)) |> assign(:translation_key, translation_key) end defp action_key(conn) do conn |> Phoenix.Controller.action_name() |> to_string end defp controller_key(conn) do controller_keys = conn |> Phoenix.Controller.controller_module() |> to_string |> String.split(".") |> Enum.slice(-2..-1) controller_prefix = controller_keys |> Enum.at(0) controller_suffix = controller_keys |> Enum.at(1) |> String.replace("Controller", "") "#{controller_prefix}.#{controller_suffix}" |> String.downcase() end end <|start_filename|>priv/repo/migrations/20170718204419_alter_tables_orders_line_items.exs<|end_filename|> defmodule Shopix.Repo.Migrations.AlterTablesOrdersLineItems do use Ecto.Migration def change do drop constraint(:line_items, "line_items_order_id_fkey") alter table(:line_items) do modify :order_id, references(:orders, on_delete: :delete_all) add :product_price_cache, :integer add :product_name_cache, :string end end end <|start_filename|>priv/repo/migrations/20170710235936_add_key_to_properties.exs<|end_filename|> defmodule Shopix.Repo.Migrations.AddKeyToProperties do use Ecto.Migration def change do alter table(:properties) do add :key, :string end end end <|start_filename|>priv/repo/migrations/20170725100119_add_images_group_url_to_pages.exs<|end_filename|> defmodule Shopix.Repo.Migrations.AddImagesGroupUrlToPages do use Ecto.Migration def change do alter table(:pages) do add :images_group_url, :string end end end <|start_filename|>priv/repo/migrations/20170714014038_orders_add_completed_at.exs<|end_filename|> defmodule Shopix.Repo.Migrations.OrdersAddCompletedAt do use Ecto.Migration def change do alter table(:orders) do add :completed_at, :naive_datetime remove :checkout_begun_at end end end <|start_filename|>priv/repo/migrations/20170712004600_add_unique_indexes_users_translations.exs<|end_filename|> defmodule Shopix.Repo.Migrations.AddUniqueIndexesUsersTranslations do use Ecto.Migration def change do create unique_index(:admin_users, [:email]) create unique_index(:translations, [:key, :locale], name: :translations_key_locale) create unique_index(:properties, [:key]) end end <|start_filename|>lib/shopix/localized_countries/localized_countries.ex<|end_filename|> defmodule Shopix.LocalizedCountries do def countries(locale) do [Application.app_dir(:shopix, "priv"), "locales", "#{locale}.yml"] |> Path.join() |> YamlElixir.read_from_file!() |> Map.fetch!(locale) |> Map.fetch!("countries") |> Enum.sort() |> Enum.map(fn {key, value} -> {String.to_atom(value), key} end) end end <|start_filename|>lib/shopix/schema/page.ex<|end_filename|> defmodule Shopix.Schema.Page do use Ecto.Schema use Shopix.TranslationFields, slug: :name, translated_fields: ~w(name content slug) schema "pages" do field :key, :string field :images_group_url, :string field :edit_html_only, :boolean, default: false schema_translation_fields() timestamps() end end <|start_filename|>test/createurs_web/plugs/current_order_test.exs<|end_filename|> defmodule ShopixWeb.Plug.CurrentOrderTest do use ShopixWeb.ConnCase, async: true alias ShopixWeb.Plug.CurrentOrder alias Shopix.Schema.GlobalConfig test "call/2 when there is no current order sets nil" do conn = build_conn() |> bypass_through(ShopixWeb.Router, [:browser]) |> assign(:global_config, %GlobalConfig{}) |> get("/") |> CurrentOrder.call(%{}) assert conn.assigns.current_order == nil end test "call/2 when there is a current order sets the current_order" do order = insert(:order) conn = build_conn() |> bypass_through(ShopixWeb.Router, [:browser]) |> assign(:global_config, %GlobalConfig{}) |> get("/") |> put_session(:order_id, order.id) |> CurrentOrder.call(%{}) assert conn.assigns.current_order.id == order.id end end <|start_filename|>priv/repo/migrations/20170729164824_alter_translations_remove_old_columns.exs<|end_filename|> defmodule Shopix.Repo.Migrations.AlterTranslationsRemoveOldColumns do use Ecto.Migration def change do drop unique_index(:translations, [:key, :locale], name: :translations_key_locale) create unique_index(:translations, [:key]) alter table(:translations) do remove :locale remove :value end end end
gsarwate/shopix
<|start_filename|>bower.json<|end_filename|> { "name": "Creatures MOB-Engine", "description": "A Mod(pack) for Minetest that provides a MOB-Engine and adds several creatures to the game.\n", "keywords": [ "creatures", "mobs", "MOB", "MOB-Engine", "Creatures MOB-Engine", "cme", "zombies", "sheep", "ghost", "monsters", "hostile" ], "homepage": "https://github.com/BlockMen/cme", "forum": "http://forum.minetest.net/viewtopic.php?f=11&t=8638", "screenshots": [ "https://raw.githubusercontent.com/BlockMen/cme/master/screenshot.png" ], "authors": [ "BlockMen" ] }
clinew/cme
<|start_filename|>FeedParser/Internal/FDPXMLParserProtocol.h<|end_filename|> // // FDPXMLParserProtocol.h // FeedParser // // Created by <NAME> on 4/9/09. // Copyright 2009 <NAME>. All rights reserved. // // 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. /*! @protocol @abstract FDPXMLParserProtocol declares a protocol for a tree of XML parser delegates @discussion Every class that can be a delegate of the NSXMLParser must conform to this protocol. This ensures that each class can pass parser delegation to its parent appropriately. */ @protocol FDPXMLParserProtocol <NSObject, NSXMLParserDelegate> @required /*! @method @abstract Take over the delegate role for the NSXMLParser @param parser The NSXMLParser that is currently parsing the document. @discussion The implementation of this method must call [parser setDelegate:self] after recording the previous delegate of the parser. The previous delegate should be assumed to conform to FDPXMLParserProtocol. */ - (void)acceptParsing:(NSXMLParser *)parser; /*! @method @abstract Abort parsing @param parser The NSXMLParser that is currently parsing the document. @param description A description of the error that occurred. If no description is known, it will be nil. @discussion When an error occurs, whether it's an XML error or a validation error, the parser must call this method. It should do any cleanup necessary, and it must call this same method on its parent parser. If the parent parser does not exist, then it must call [parser abortParsing]. Normally FDPXMLParser is the root parser and will abort the parser. Be aware that the call to super may cause self to be deallocated. */ - (void)abortParsing:(NSXMLParser *)parser withString:(NSString *)description; /*! @method @abstract Resume parsing param parser The NSXMLParser that is currently parsing the document @param child The id<FDPXMLParserProtocol> that was previously the parser delegate @discussion This method must be called when parsing control is returned to a parent parser. It is simply a notification to the parent parser that it should expect to receive delegate methods again. */ - (void)resumeParsing:(NSXMLParser *)parser fromChild:(id<FDPXMLParserProtocol>)child; @end <|start_filename|>FeedParser/FDPErrors.h<|end_filename|> // // FDPErrors.h // FeedParser // // Created by <NAME> on 4/4/09. // Copyright 2009 <NAME>. All rights reserved. // // 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. #import <Foundation/Foundation.h> extern NSString * const FDPParserErrorDomain; extern NSString * const FPParserErrorDomain __attribute__((deprecated("replaced by FPParserErrorDomain", "FDPParserErrorDomain"))); typedef NS_ERROR_ENUM(FDPParserErrorDomain, FDPParserError) { FDPParserErrorInternal = 1, FDPParserErrorInvalidFeed = 2, FDPParserInternalError __attribute__((deprecated("replaced by FDPParserErrorInternal", "FDPParserErrorInternal"))) NS_SWIFT_UNAVAILABLE("Use .internal") = FDPParserErrorInternal, FDPParserInvalidFeedError __attribute__((deprecated("replaced by FDPParserErrorInvalidFeed", "FDPParserErrorInvalidFeed"))) NS_SWIFT_UNAVAILABLE("Use .invalidFeed") = FDPParserErrorInvalidFeed, FPParserInternalError __attribute__((deprecated("replaced by FDPParserErrorInternal", "FDPParserErrorInternal"))) NS_SWIFT_UNAVAILABLE("Use .internal") = FDPParserErrorInternal, FPParserInvalidFeedError __attribute__((deprecated("replaced by FDPParserErrorInvalidFeed", "FDPParserErrorInvalidFeed"))) NS_SWIFT_UNAVAILABLE("Use .invalidFeed") = FDPParserErrorInvalidFeed }; typedef FDPParserError FPParserError __attribute__((deprecated("replaced by FDPParserError", "FDPParserError"))); <|start_filename|>FeedParser/XML Extensions/FDPExtensionNode.h<|end_filename|> // // FDPExtensionNode.h // FeedParser // // Created by <NAME> on 4/9/09. // Copyright 2009 <NAME>. All rights reserved. // // 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. #import <Foundation/Foundation.h> // FDPExtensionNode is used to represent extension elements outside of the RSS/Atom namespaces // conceptually this is an extremely simplified NSXMLNode // it can represent either textual data (FDPExtensionTextNode) or an element (FDPExtensionElementNode) @interface FDPExtensionNode : NSObject <NSSecureCoding> { } @property (nonatomic, readonly) BOOL isElement; @property (nonatomic, readonly) BOOL isTextNode; // stringValue returns a string representing the node // for text nodes, it returns the text associated with the node // for element nodes, it returns a concatenation of the stringValue of all its children // this means that any child element nodes get effectively flattened out and disappear @property (nonatomic, readonly) NSString *stringValue; // The following properties are only valid for element nodes @property (nonatomic, readonly) NSString *name; @property (nonatomic, readonly) NSString *qualifiedName; // returns the name as existed in the XML source @property (nonatomic, readonly) NSString *namespaceURI; @property (nonatomic, readonly) NSDictionary *attributes; @property (nonatomic, readonly) NSArray *children; // an array of FPExtensionNodes @end @compatibility_alias FPExtensionNode FDPExtensionNode;
kballard/feedparser
<|start_filename|>resources/assets/js/store/home.js<|end_filename|> export default { page: 0, NoMoreItems: false, nothingFound: false, submissions: [], loading: null, getSubmissions(sort = 'hot') { return new Promise((resolve, reject) => { this.page++; this.loading = true; // if landed on the home page as guest if (typeof preload != 'undefined' && preload.submissions) { this.submissions = preload.submissions.data; if (!this.submissions.length) this.nothingFound = true; if (preload.submissions.next_page_url == null) this.NoMoreItems = true; this.loading = false; delete preload.submissions; resolve(); return; } axios .get('/feed', { params: { sort, page: this.page, filter: Store.settings.feed.submissionsFilter, exclude_liked_submissions: Store.settings.feed.excludeLikedSubmissions ? 1 : 0, include_nsfw_submissions: Store.settings.feed.include_nsfw_submissions ? 1 : 0, exclude_bookmarked_submissions: Store.settings.feed.excludeBookmarkedSubmissions ? 1 : 0, submissions_type: Store.settings.feed.submissionsType } }) .then(response => { this.submissions = [...this.submissions, ...response.data.data]; if (!this.submissions.length) this.nothingFound = true; if (response.data.links.next == null) this.NoMoreItems = true; this.loading = false; resolve(response); }) .catch(error => { reject(error); }); }); }, clear() { this.page = 0; this.nothingFound = false; this.NoMoreItems = false; this.submissions = []; this.loading = true; } }; <|start_filename|>resources/assets/js/store/settings.js<|end_filename|> export default { font: 'Lato', feed: { include_nsfw_submissions: false, excludeLikedSubmissions: false, excludeBookmarkedSubmissions: false, submissionsFilter: 'subscribed', submissionsType: 'All' }, rightSidebar: { channelsFilter: 'subscribed', channelsLimit: 15, showChannelAvatars: true, color: 'Gray' } }; <|start_filename|>resources/assets/js/store/state.js<|end_filename|> export default { submissions: { likes: [], }, comments: { likes: [], }, bookmarks: { submissions: [], comments: [], channels: [], users: [] }, blocks: { users: [], channels: [] }, moderatingChannels: [], bookmarkedChannels: [], moderatorAt: [], administratorAt: [], moderatingAt: [], // contains both moderator and administrator subscribedAt: [], notifications: [], messages: [], contacts: [], subscribedChannels: [] }; <|start_filename|>resources/assets/js/mixins/FontLoader.js<|end_filename|> export default { computed: { currentFont() { return Store.settings.font; } }, watch: { 'Store.settings.font'() { this.setFont(this.currentFont); } }, mounted() { this.$nextTick(function() { this.setFont(this.currentFont); }); }, methods: { setFont(font) { document.body.style.fontFamily = font; } } }; <|start_filename|>resources/assets/js/vue-codes.js<|end_filename|> import GuestSidebar from './components/GuestSidebar.vue'; import AuthenticationModal from './components/AuthenticationModal.vue'; import GoogleLoginButton from './components/GoogleLoginButton.vue'; import Feedback from './components/Feedback.vue'; import Notifications from './components/Notifications.vue'; import Messages from './components/Messages.vue'; import Preferences from './components/Preferences.vue'; import RightSidebar from './components/auth/RightSidebar.vue'; import NewSubmission from './components/NewSubmission.vue'; import NewChannel from './components/NewChannel.vue'; import ReportSubmission from './components/ReportSubmission.vue'; import ReportComment from './components/ReportComment.vue'; import FeedSettings from './components/FeedSettings.vue'; import SidebarSettings from './components/RightSidebarSettings.vue'; import EmbedViewer from './components/Embed.vue'; import GifPlayer from './components/GifPlayer.vue'; import PhotoViewer from './components/PhotoViewer.vue'; import KeyboardShortcutsGuide from './components/KeyboardShortcutsGuide.vue'; import MarkdownGuide from './components/MarkdownGuide.vue'; import SearchModal from './components/SearchModal.vue'; import NotFound from './components/NotFound.vue'; import StoreStorage from './mixins/StoreStorage'; import LeftSidebar from './components/auth/LeftSidebar.vue'; import Helpers from './mixins/Helpers'; import FontLoader from './mixins/FontLoader'; import router from './routes'; import Announcement from './components/Announcement.vue'; import Tour from './components/Tour'; import MobileVisitorWarning from './components/MobileVisitorWarning'; import BanUserModal from './components/BanUserModal'; /** * This is our event bus, which is used for event dispatching. The base is that we create an empty * Vue instance. First we fire the event by: "this.$eventHub.$emit('eventName', 'data')" * and later we listen for it by: "this.$eventHub.$on('eventName', this.newComment)" * * (which is defined in the created() function of the vue component (or root instance), after catching the * event, passes the data to the defined function. In this example case it's newComment() but notice that * it doesn't require to be actually written as argumans! ) Happy eventing in your awesome components. */ Vue.prototype.$eventHub = new Vue(); /** * The very serious and important vue instance!!! This is what gives power to voten's * front-end. Try to love it, maintain it, appriciate it and maybe even more! This * also plays a role in switching states and maintaining the Store. */ window.app = new Vue({ router, mixins: [Helpers, StoreStorage, FontLoader], components: { KeyboardShortcutsGuide, MobileVisitorWarning, AuthenticationModal, GoogleLoginButton, ReportSubmission, SidebarSettings, MarkdownGuide, FeedSettings, Notifications, ReportComment, NewSubmission, Announcement, RightSidebar, GuestSidebar, PhotoViewer, EmbedViewer, LeftSidebar, BanUserModal, SearchModal, Preferences, NewChannel, GifPlayer, NotFound, Messages, Feedback, Tour }, data: { showSidebars: true, pageTitle: document.title }, computed: { unreadNotifications() { try { return Store.state.notifications.filter( (item) => item.read_at == null ).length; } catch (error) { return 0; } }, unreadMessages() { try { return Store.state.contacts.filter( (item) => !_.isUndefined(item.last_message.author) && item.last_message.author.id != auth.id && item.last_message.read_at == null ).length; } catch (error) { return 0; } } }, watch: { unreadNotifications() { this.updatePageTitle(); }, unreadMessages() { this.updatePageTitle(); }, '$route.query'() { this.setQueries(); } }, created() { this.loadWebFont(); this.fillBasicStore(); window.addEventListener('keydown', this.keydown); window.addEventListener('hashchange', this.setHashes); // Let's hear it for the events, shall we? this.$eventHub.$on('start-conversation', this.startConversation); this.$eventHub.$on('submit', this.showNewSubmission); this.$eventHub.$on('login-modal', this.loginModal); this.$eventHub.$on('markdown-guide', this.openMarkdownGuide); this.$eventHub.$on('push-notification', this.pushNotification); if (this.$route.query.search) { Store.modals.search.show = true; } this.setQueries(); this.setHashes(); this.warnMobileUsers(); }, methods: { warnMobileUsers() { if (this.isMobile) { Store.modals.mobileVisitorWarning.show = true; } }, setHashes() { let hash = window.location.hash; if (!hash) { _.forEach(Store.modals, (item) => { item.show = false; }); } else { let modal = _.find(Store.modals, (item) => { return item.hash == hash.substr(1); }); // if didn't found, means it's supposed to be closed. So leave it be and just unset window.location.hash if (modal == undefined) { window.location.hash = ''; } else { modal.show = true; } } }, setQueries() { // sidebar if (this.$route.query.sidebar == 1) { this.showSidebars = true; } else if (this.$route.query.sidebar == 0) { this.showSidebars = false; } // feedback if (this.$route.query.feedback == 1) { Store.modals.feedback.show = true; } }, loginModal() { Store.modals.authintication.show = true; }, openMarkdownGuide() { Store.modals.markdownGuide.show = true; }, /** * Catches the notification event and passes it in case it should. * * @param {Object} data * @return void */ pushNotification(data) { let self = this; Push.create(data.title, { body: data.body, icon: data.icon ? data.icon : '/imgs/v-logo.png', timeout: 5000, onClick: function() { if (data.url == 'new-message') { Store.modals.messages.show = true; } else { self.$router.push(data.url); } window.focus(); this.close(); } }); }, /** * Opens the messages component and starts the conversation with the sent user. * * @return void */ startConversation(contact) { Store.modals.messages.show = true; this.$eventHub.$emit('conversation', contact); }, /** * show the submit modal. * * @return void */ showNewSubmission() { Store.modals.newSubmission.show = true; }, /** * show the submit modal. * * @return void */ showNewChannel() { Store.modals.newChannel.show = true; }, /** * Updates the <title> by adding the number of notifications and messages * * @return void */ updatePageTitle() { let total = this.unreadMessages + this.unreadNotifications; if (total > 0) { document.title = '(' + total + ') ' + this.pageTitle; } else { document.title = this.pageTitle; } }, /** * Catches the event fired for the pressed key, and runs the neccessary methods. * * @param {keydown} event * @return void */ keydown(event) { // esc if (event.keyCode == 27) { this.$eventHub.$emit('pressed-esc'); } // all shortcuts after this one need to be prevented if user is typing if (this.whileTyping(event)) return; // alt + s == event.altKey && event.keyCode == 83 if (event.altKey && event.keyCode == 83) { // alt + s this.showNewSubmission(); return; } if (event.altKey && event.keyCode == 67) { // alt + c this.showNewChannel(); return; } if (event.shiftKey && event.keyCode == 191) { // shift + / Store.modals.keyboardShortcutsGuide.show = true; return; } if (event.metaKey && event.keyCode == 82) { return; } switch (event.keyCode) { case 78: // "n" if (this.isGuest) break; Store.modals.notifications.show = true; break; case 77: // "m" if (this.isGuest) break; event.preventDefault(); Store.modals.messages.show = true; break; case 191: // "/" event.preventDefault(); Store.modals.search.show = true; break; case 66: // "b" if (this.isGuest) break; this.$router.push('/bookmarks'); break; case 72: // "h" this.$router.push('/'); break; case 80: // "p" if (this.isGuest) break; this.$router.push('/@' + this.auth.username); break; case 82: // "r" if (this.$route.name === 'home') { this.$eventHub.$emit('refresh-home'); } else if (this.$route.name === 'channel-submissions') { this.$eventHub.$emit('refresh-channel-submissions'); } break; default: return; } } } }).$mount('#voten-app'); <|start_filename|>resources/assets/js/mixins/StoreStorage.js<|end_filename|> export default { data() { return { clientsideSettings }; }, methods: { /** * Preloads few Store data using the HTML5 local storage. This'll get more updates in the future. * Let's begin by preloading sidebar channels. * * @return void */ preloadStore() { if (Vue.isSetLS('store-state')) { Store.state = Vue.getLS('store-state'); } }, /** * Filles the Store * * @return void */ fillBasicStore() { if (this.isGuest) return; // preLoad few Store values. This is used to avoid need for loading. Sure it might be fast enough now, // but it's not instant! This makes it instant. Also, we need to make sure the preloaded data is // fresh, and that's why we're still doing the ajax request to update it. Performance baby! // this.preloadStore(); axios.get('/users/store').then(response => { Store.state.submissions.likes = response.data.data.submissions.likeds; Store.state.comments.likes = response.data.data.comments.likeds; Store.state.bookmarks.submissions = response.data.data.submissions.bookmarkeds; Store.state.bookmarks.comments = response.data.data.comments.bookmarkeds; Store.state.bookmarks.channels = response.data.data.channels.bookmarkeds; Store.state.bookmarks.users = response.data.data.users.bookmarkeds; Store.state.subscribedChannels = response.data.data.channels.subscribeds; Store.state.moderatingChannels = response.data.data.channels.moderatings; Store.state.bookmarkedChannels = response.data.data.channels.bookmarkeds_records; Store.state.blocks.users = response.data.data.users.blockeds_conversations; response.data.data.channels.moderatings.forEach((element, index) => { Store.state.moderatingAt.push(element.id); }); response.data.data.channels.subscribeds.forEach((element, index) => { Store.state.subscribedAt.push(element.id); }); response.data.data.channels.moderatings_records.forEach((element, index) => { if (element.role == 'administrator') { Store.state.administratorAt.push(element.channel_id); } else if (element.role == 'moderator') { Store.state.moderatorAt.push(element.channel_id); } }); Store.initialFilled = true; }); }, /** * Pulls 'store-state' from LocalStorage and put it in the Store.state. * In other words, loads the Store from the LocalStorage. * * @return void */ pullStore() { Store.state = Vue.getLS('store-state'); }, /** * Pushes Store.state into LocalStorage's 'store-state'. * In other words, saves the Store into the LocalStorage. * * @return void */ pushStore(delay = false) { if (delay === false) { this.pushStoreNow(); return; } this.optimizedPushStore(); }, pushSettingsToServer() { axios.post('/users/clientside-settings', { platform: 'Web', json: JSON.stringify(Store.settings) }); }, pushStoreNow() { Vue.putLS('store-state', Store.state); }, optimizedPushStore: _.debounce(function() { Vue.putLS('store-state', Store.state); }, 1000) }, created() { if (this.isGuest) return; this.$eventHub.$on('push-store', this.pushStore); this.$eventHub.$on('pull-store', this.pullStore); this.$eventHub.$on('push-settings', this.pushSettingsToServer); document.addEventListener('visibilitychange', function() { // Just opened (or clicked on) the window if (document.visibilityState == 'visible') { let tempState = Vue.getLS('store-state', true); if (tempState != null) { Store.state = tempState; } } }); }, watch: { 'Store.state': { handler() { if (this.isGuest) return; if (!Store.initialFilled) return; this.$eventHub.$emit('push-store'); }, deep: true }, 'Store.settings': { handler() { if (this.isGuest) return; if (!Store.initialFilled) return; this.$eventHub.$emit('push-settings'); }, deep: true } } }; <|start_filename|>resources/assets/js/store/tour.js<|end_filename|> export default { show: false, step: 1, items: [ { id: 'left-sidebar', title: 'Workbench:', body: `<p>On your left sidebar, you find handy links and tools that you use all the time. Just hover over each icon to see what it does. There's also a keyboard shortcut for each of them.</p> <p>The question mark at the end of it links to our help center which holds answers to most of your questions.</p>` }, { id: 'feed', title: 'Feed:', body: `<p>Your feed/homepage is your best friend on Voten. It is where you find all the cool stuff posted to Voten.</p> <p>By default it displays posts only from channels you have already subscribed to; but you can adjust it to your needs via many filters tailored to your very needs. Just click on the "gear" icon to open the config page. </p>` }, { id: 'right-sidebar-channels', title: 'Channels:', body: `<p>On your right sidebar, you find all the channels you have subscribed. You can use the instant search to filter through them.</p> <p>You can even customize the sidebar entirely with various colors and filters tailored for your very personal taste.</p>` }, { id: 'right-sidebar-menu', title: 'Menu:', body: `<p>Every other link that you do not use all the time is located on the menu. To toggle the menu, click on the arrow icon or your profile picture.</p>` }, { id: 'os-notifications', title: 'Push Notifications:', body: `<p>Last but not least, click on "Allow" to turn on web push notifications for Voten to receive notifications in your OS when Voten is not the active tab in your browser. (like when you have minimized the browser to watch Game of Thrones!)</p> <p><strong>Note:</strong> Unlike other websites, we do not bother you. We only send push notifications when Voten is present in your browser. </p>` } ] }; <|start_filename|>resources/assets/js/mixins/Helpers.js<|end_filename|> import WebFont from 'webfontloader'; export default { data() { return { Store, meta, auth, Laravel, csrf: window.Laravel.csrfToken }; }, computed: { activeTour() { return Store.tour.items[Store.tour.step - 1]; }, showTour() { return Store.tour.show; }, /** * Is the user a guest * * @return bool */ isGuest() { return meta.isGuest; }, /** * Is the user an authinticated user * * @return bool */ isLoggedIn() { return !meta.isGuest; }, /** * Is visitor browsing via a mobile device * * @return bool */ isMobile() { return meta.isMobileDevice; }, /** * Is visitor browsing via a desktop device * * @return bool */ isDesktop() { return !meta.isMobileDevice; }, /** * is user a moderator? * * @return bool */ isModerating() { return Store.state.moderatingAt.length > 0; }, isVotenAdministrator() { return meta.isVotenAdministrator; } }, methods: { /** * Loads the web-font. * * @param string font * @return void */ loadWebFont() { WebFont.load({ google: { families: [Store.settings.font] } }); }, /** * sets the page title * * @param string title * @param bool explicit * @return void */ setPageTitle(title, explicit = false) { if (explicit == true) { document.title = title; return; } document.title = title; }, /** * the user must be login other wise rais a warning * * @return void */ mustBeLogin() { if (!this.isGuest) return; this.$eventHub.$emit('login-modal'); }, /** * simulates Laravel's str_limit in JS * * @param string str * @param integer length * @return string */ str_limit(str, length) { if (typeof str == typeof null) { return null; } if (str.length > length) return (str = str.substring(0, length) + '...'); return str; }, /** * Slugifies the string. * * @param string str * @return string */ str_slug(str) { return str .toString() .toLowerCase() .trim() .replace(/\s+/g, '-') .replace(/&/g, '-and-') .replace(/[^\w\-]+/g, '') .replace(/\-\-+/g, '-'); }, /** * determines if the user is typing in either an input or textarea * * @return boolean */ whileTyping(event) { return event.target.tagName.toLowerCase() === 'textarea' || event.target.tagName.toLowerCase() === 'input'; }, /** * determines if the timestamp is for today's date * * @param string timestamp * @return boolean */ isItToday(timestamp) { if (typeof timestamp != 'string') { timestamp = timestamp.date; } return moment(timestamp).format('DD/MM/YYYY') == moment(new Date()).format('DD/MM/YYYY'); }, /** * parses the date in a neat and user-friendly format for today * * @param string timestamp * @param string timezone * @return string */ parseDateForToday(timestamp, timezone) { if (typeof timestamp != 'string') { timestamp = timestamp.date; } if (!timezone) { timezone = moment.tz.guess(); } return moment(timestamp) .tz(timezone) .format('LT'); }, /** * parses the date in a neat and user-friendly format * * @param string timestamp * @param string timezone * @return string */ parseDate(timestamp, timezone) { if (typeof timestamp != 'string') { timestamp = timestamp.date; } if (!timezone) { timezone = moment.tz.guess(); } return moment(timestamp) .tz(timezone) .format('MMM Do'); }, /** * Parses the date in a in full format. * * @param string timestamp * @param string timezone * @return string */ parseFullDate(timestamp, timezone) { if (typeof timestamp != 'string') { timestamp = timestamp.date; } if (!timezone) { timezone = moment.tz.guess(); } return moment(timestamp) .tz(timezone) .format('LLL'); }, /** * Parses the date in "n days ago" format. * * @param string timestamp * @param string timezone * @return string */ parsDiffForHumans(timestamp, timezone) { if (typeof timestamp != 'string') { timestamp = timestamp.date; } if (!timezone) { timezone = moment.tz.guess(); } return moment(timestamp) .tz(timezone) .fromNow(true); }, /** * Parses a timestamp for current moment. * * @return string */ now() { return moment() .utc() .format('YYYY-MM-DD HH:mm:ss'); }, /** * prefixes the route with /auth if it's for authenticated users * * @param string route * @return string */ authUrl(route) { return !this.isGuest ? '/auth/' + route : '/' + route; }, /** * Catches the scroll event and fires the neccessary ones for componenets. (Such as Inifinite Scrolling) * * @return void */ scrolled: _.throttle( function(event) { this.$eventHub.$emit('scrolled'); console.log('scrolled'); let box = event.target; if (box.scrollHeight - box.scrollTop < box.clientHeight + 100) { this.$eventHub.$emit('scrolled-to-bottom'); console.log('scrolled-to-bottom'); } if (box.scrollTop < 100) { this.$eventHub.$emit('scrolled-to-top'); console.log('scrolled-to-top'); } else if (box.scrollTop < 1500) { this.$eventHub.$emit('scrolled-a-bit'); console.log('scrolled-a-bit'); } else { this.$eventHub.$emit('scrolled-a-lot'); console.log('scrolled-a-bit'); } }, 200, { leading: true, trailing: true } ), /** * Scroll the page to the top of the element with the passed ID. * * @param string scrollable */ scrollToTop(scrollable) { document.getElementById(scrollable).scrollTop = 0; }, /** * Scroll the page to the bottom of the element with the passed ID. * * @param string scrollable */ scrollToBottom(scrollable) { let el = document.getElementById(scrollable); el.scrollTop = el.scrollHeight; }, /** * Generates a valid URL to channel route. * * @param {string} name */ channelUrl(name) { return `/c/${name}`; }, /** * Generates a valid URL to user profile route. * * @param {string} username */ userUrl(username) { return `/@${username}`; }, /** * Generates a valid URL to submission route. * * @param {SubmissionResource} submission */ submissionUrl(submission) { return `/c/${submission.channel_name}/${submission.slug}`; } } }; <|start_filename|>resources/assets/js/store/submission.js<|end_filename|> export default { submission: [], loadingSubmission: null, getSubmission(slug) { return new Promise((resolve, reject) => { // if landed on a submission page if (preload.submission && preload.channel) { this.submission = preload.submission; Store.page.channel.temp = preload.channel; this.loadingSubmission = false; delete preload.submission; delete preload.channel; resolve(); return; } axios .get('/submissions', { params: { slug, with_channel: 1 } }) .then((response) => { this.submission = response.data.data; Store.page.channel.temp = response.data.data.channel; this.loadingSubmission = false; resolve(response.data); }) .catch((error) => { this.loadingSubmission = false; reject(error); }); }); }, clearSubmission() { this.submission = []; this.loadingSubmission = null; } }; <|start_filename|>resources/assets/js/plugins/local-storage.js<|end_filename|> const LocalStorage = { install(Vue, options) { /** * put the data into the localStorage * * @param string key * @param mixed value * @return void */ (Vue.putLS = function(key, value) { localStorage.setItem(key, JSON.stringify(value)); }), /** * fetches the data from the localStorage * * @param string key * @return object */ (Vue.getLS = function(key) { let result = JSON.parse(localStorage.getItem(key)); if (result === null) { return []; } return result; }), /** * is the value set into the local storage * * @param string key * @return boolean */ (Vue.isSetLS = function(key) { return key in localStorage ? true : false; }), /** * Clear all the data in LocalStorage. * * @return void */ (Vue.clearLS = function() { localStorage.clear(); }), (Vue.forgetLS = function(key) { localStorage.removeItem(key); }); } }; export default LocalStorage; <|start_filename|>resources/assets/js/routes.js<|end_filename|> // for administrators only import AdminPanel from './components/AdminPanel.vue'; import AdminPanelSuggestedChannels from './components/AdminPanelSuggestedChannels.vue'; import AdminPanelInactiveChannels from './components/AdminPanelInactiveChannels.vue'; import AdminPanelSubmissions from './components/AdminPanelSubmissions.vue'; import AdminPanelComments from './components/AdminPanelComments.vue'; import AdminPanelDashboard from './components/AdminPanelDashboard.vue'; import AdminPanelStatistics from './components/AdminPanelStatistics.vue'; import AdminPanelUsers from './components/AdminPanelUsers.vue'; // For moderators only import ModeratorPanel from './components/ModeratorPanel.vue'; import ModeratorPanelRules from './components/ModeratorPanelRules.vue'; import ModeratorPanelModerators from './components/ModeratorPanelModerators.vue'; import ModeratorPanelBlockDomains from './components/ModeratorPanelBlockDomains.vue'; import ModeratorPanelBanUsers from './components/ModeratorPanelBanUsers.vue'; import ModeratorPanelReportedComments from './components/ModeratorPanelReportedComments.vue'; import ModeratorPanelReportedSubmissions from './components/ModeratorPanelReportedSubmissions.vue'; import ChannelSettings from './components/ChannelSettings.vue'; // static pages import TermsOfService from './components/pages/TermsOfService.vue'; import PrivacyPolicy from './components/pages/PrivacyPolicy.vue'; import About from './components/pages/About.vue'; import Credits from './components/pages/Credits.vue'; import BookmarkedChannels from './components/BookmarkedChannels.vue'; import SubmissionRedirector from './components/SubmissionRedirector.vue'; import ChannelSubmissions from './components/ChannelSubmissions.vue'; import BookmarkedComments from './components/BookmarkedComments.vue'; import BookmarkedUsers from './components/BookmarkedUsers.vue'; import UserSubmissions from './components/UserSubmissions.vue'; import FindChannels from './components/FindChannels.vue'; import SubmissionPage from './components/SubmissionPage.vue'; import UserComments from './components/UserComments.vue'; import Bookmarks from './components/Bookmarks.vue'; import NotFound from './components/NotFound.vue'; import Home from './components/Home.vue'; import Channel from './components/Channel.vue'; import UserPage from './components/UserPage.vue'; import DeletedSubmissionPage from './components/DeletedSubmissionPage.vue'; import BookmarkedSubmissions from './components/BookmarkedSubmissions.vue'; import UserLikedSubmissions from './components/UserLikedSubmissions.vue'; import SubscribedChannels from './components/SubscribedChannels.vue'; const routes = [ { name: 'home', path: '/', component: Home }, { path: '/tos', component: TermsOfService, meta: { title: 'Terms Of Service' } }, { path: '/privacy-policy', component: PrivacyPolicy, meta: { title: 'Privacy Policy' } }, { path: '/about', component: About, meta: { title: 'About' } }, { path: '/credits', component: Credits, meta: { title: 'Credits' } }, { path: '/subscriptions', component: SubscribedChannels, name: 'subscriptions', meta: { title: 'My Subscriptions' } }, { path: '/big-daddy', component: AdminPanel, children: [ { path: '', component: AdminPanelDashboard, name: 'admin-panel-dashboard' }, { path: 'statistics', component: AdminPanelStatistics, name: 'admin-panel-statistics' }, { path: 'users', component: AdminPanelUsers, name: 'admin-panel-users' }, { path: 'submissions', component: AdminPanelSubmissions, name: 'admin-panel-submissions' }, { path: 'comments', component: AdminPanelComments, name: 'admin-panel-comments' }, { path: 'channels/suggested', component: AdminPanelSuggestedChannels, name: 'admin-panel-suggested-channels' }, { path: 'channels/inactive', component: AdminPanelInactiveChannels, name: 'admin-panel-inactive-channels' } ] }, { path: '/@:username', component: UserPage, children: [ { path: '', component: UserSubmissions, name: 'user-submissions' }, { path: 'comments', component: UserComments, name: 'user-comments' }, { path: 'liked-submissions', component: UserLikedSubmissions, name: 'user-likes' } ] }, { path: '/c/:name/mod/reports', redirect: '/c/:name/mod/reports/submissions' }, { path: '/c/:name/mod', redirect: '/c/:name/mod/reports/submissions' }, { path: '/c/:name', component: Channel, children: [ { path: '', component: ChannelSubmissions, name: 'channel-submissions' }, { path: 'mod', component: ModeratorPanel, children: [ { path: 'reports/submissions', name: 'moderator-panel-reported-submissions', component: ModeratorPanelReportedSubmissions, meta: { title: 'Reports | Submissions' } }, { path: 'reports/comments', name: 'moderator-panel-reported-comments', component: ModeratorPanelReportedComments, meta: { title: 'Reports | Comments' } }, { path: 'ban-users', name: 'moderator-panel-ban-users', component: ModeratorPanelBanUsers, meta: { title: 'Ban Users | Moderator Panel' } }, { path: 'block-domains', name: 'moderator-panel-block-domains', component: ModeratorPanelBlockDomains, meta: { title: 'Block Domains | Moderator Panel' } }, { path: 'rules', name: 'moderator-panel-rules', component: ModeratorPanelRules, meta: { title: 'Rules | Moderator Panel' } }, { path: 'manage-moderators', name: 'moderator-panel-manage-moderators', component: ModeratorPanelModerators, meta: { title: 'Manage Moderators | Moderator Panel' } }, { path: 'settings', name: 'channel-settings', component: ChannelSettings, meta: { title: 'Settings | Moderator Panel' } } ] } ] }, { path: '/deleted-submission', component: DeletedSubmissionPage }, { path: '/submission/:id', component: SubmissionRedirector }, { path: '/discover-channels', component: FindChannels, name: 'discover-channels', meta: { title: 'Discover Channels' } }, { path: '/404', component: NotFound, name: 'not-found', meta: { title: 'Not Found' } }, { path: '/c/:name/:slug', component: SubmissionPage, name: 'submission-page' }, { path: '/bookmarks', redirect: '/bookmarks/submissions' }, { name: 'bookmarks', path: '/bookmarks', component: Bookmarks, children: [ { path: 'submissions', component: BookmarkedSubmissions, name: 'bookmarked-submissions', meta: { title: 'Submissions | Bookmarks' } }, { path: 'comments', component: BookmarkedComments, name: 'bookmarked-comments', meta: { title: 'Comments | Bookmarks' } }, { path: 'channels', component: BookmarkedChannels, name: 'bookmarked-channels', meta: { title: 'Channels | Bookmarks' } }, { path: 'users', component: BookmarkedUsers, name: 'bookmarked-users', meta: { title: 'Users | Bookmarks' } } ] }, { path: '/home', redirect: '/' }, { path: '*', component: NotFound, meta: { title: 'Not Found' } } ]; import VueRouter from 'vue-router'; Vue.use(VueRouter); var router = new VueRouter({ mode: 'history', routes }); // scroll behavior const scrollableElementId = 'submissions'; const scrollPositions = Object.create(null); /** * Fills the <title> tag with the right value before navigating to the * new route.First it checks the title in the meta, if it exists it * sets it to that, otherwise sets it to the default (voten). */ router.beforeEach((to, from, next) => { // scroll behavior let element = document.getElementById(scrollableElementId); if (element !== null) { scrollPositions[from.name] = element.scrollTop; } // page title if (to.meta.title) { document.title = to.meta.title; } else { if ( to.name != 'submission-page' && to.name != 'channel' && to.name != 'home' && to.name != 'user-submissions' && to.name != 'user-comments' ) { document.title = 'Voten'; } } next(); }); // scroll behavior window.addEventListener('popstate', () => { let currentRouteName = router.history.current.name; let element = document.getElementById(scrollableElementId); if (element !== null && currentRouteName in scrollPositions) { setTimeout( () => (element.scrollTop = scrollPositions[currentRouteName]), 50 ); } }); /** * Since Google Analytics's default tracking code doesn't play nice with * single-page-applications, we're gonna use this one. What it does * is simply running after navigating to each new route. */ router.afterEach((to, from) => { if (Laravel.env == 'production') { (function(i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; (i[r] = i[r] || function() { (i[r].q = i[r].q || []).push(arguments); }), (i[r].l = 1 * new Date()); (a = s.createElement(o)), (m = s.getElementsByTagName(o)[0]); a.async = 1; a.src = g; m.parentNode.insertBefore(a, m); })( window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga' ); ga('create', 'UA-89431807-1', 'auto'); ga('set', 'page', to.path); ga('send', 'pageview'); } }); export default router; <|start_filename|>resources/assets/js/store/user.js<|end_filename|> export default { temp: [], getUser(username, set = true) { return new Promise((resolve, reject) => { // If a guest has landed on the user page if (preload.user) { this.setUser(preload.user); delete preload.user; resolve(); return; } axios .get('/users', { params: { username, with_info: 1, with_stats: 1 } }) .then((response) => { if (response.data.data.id == auth.id) auth.stats = this.temp.stats; if (set == true) { this.setUser(response.data.data); resolve(response); } resolve(response.data.data); }) .catch((error) => { reject(error); }); }); }, setUser(data) { this.temp = data; }, submissions: { NoMoreItems: false, submissions: [], loading: null, page: 0, nothingFound: false, getSubmissions(username) { return new Promise((resolve, reject) => { this.page++; this.loading = true; // if a guest has landed on the user page if (preload.submissions && this.page == 1) { this.submissions = preload.submissions.data; if (!this.submissions.length) this.nothingFound = true; if (preload.submissions.next_page_url == null) this.NoMoreItems = true; this.loading = false; delete preload.submissions; resolve(); return; } axios .get('/user-submissions', { params: { page: this.page, username: username } }) .then((response) => { this.submissions = [ ...this.submissions, ...response.data.data ]; if (this.submissions.length < 1) this.nothingFound = true; if (response.data.links.next == null) this.NoMoreItems = true; this.loading = false; resolve(response); }) .catch((error) => { this.loading = false; reject(error); }); }); }, clear() { this.NoMoreItems = false; this.submissions = []; this.loading = null; this.page = 0; this.nothingFound = false; } }, likedSubmissions: { NoMoreItems: false, submissions: [], loading: null, page: 0, nothingFound: false, getSubmissions() { return new Promise((resolve, reject) => { this.page++; this.loading = true; axios .get('/auth/submissions/liked', { params: { page: this.page } }) .then((response) => { this.submissions = [ ...this.submissions, ...response.data.data ]; if (response.data.links.next == null) this.NoMoreItems = true; if (this.submissions.length < 1) this.nothingFound = true; this.loading = false; resolve(response); }) .catch((error) => { this.loading = false; reject(error); }); }); }, clear() { this.NoMoreItems = false; this.submissions = []; this.loading = null; this.page = 0; this.nothingFound = false; } }, comments: { NoMoreItems: false, comments: [], loading: null, page: 0, nothingFound: false, getComments(username) { return new Promise((resolve, reject) => { this.page++; this.loading = true; // if a guest has landed on the user page if (preload.comments && this.page == 1) { this.comments = preload.comments.data; if (!this.comments.length) this.nothingFound = true; if (preload.comments.next_page_url == null) this.NoMoreItems = true; this.loading = false; delete preload.comments; resolve(); return; } axios .get('/user-comments', { params: { page: this.page, username: username } }) .then((response) => { this.comments = [ ...this.comments, ...response.data.data ]; if (response.data.links.next == null) this.NoMoreItems = true; if (this.comments.length < 1) this.nothingFound = true; this.loading = false; resolve(response); }) .catch((error) => { this.loading = false; reject(error); }); }); }, clear() { this.NoMoreItems = false; this.comments = []; this.loading = null; this.page = 0; this.nothingFound = false; } } }; <|start_filename|>resources/assets/js/store/methods.js<|end_filename|> export default { // Mark all notifications as seen. seenAllNotifications() { axios.post('/notifications').then(() => { Store.state.notifications.forEach((element, index) => { if (!element.read_at) { element.read_at = moment() .utc() .format('YYYY-MM-DD HH:mm:ss'); } }); }); } }; <|start_filename|>resources/assets/js/store/modals.js<|end_filename|> // Set a hash for each modal to make it searchable to see which modal the // window.location.hash is pointing to. export default { preferences: { show: false, hash: 'preferences' }, notifications: { show: false, hash: 'notifications' }, newChannel: { show: false, hash: 'newChannel' }, feedback: { show: false, hash: 'feedback' }, newSubmission: { show: false, hash: 'newSubmission' }, keyboardShortcutsGuide: { show: false, hash: 'keyboardShortcutsGuide' }, markdownGuide: { show: false, hash: 'markdownGuide' }, authintication: { show: false, hash: 'authintication' }, reportSubmission: { show: false, hash: 'reportSubmission', submission: [] }, reportComment: { show: false, hash: 'reportComment', comment: [] }, feedSettings: { show: false, hash: 'feedSettings' }, sidebarSettings: { show: false, hash: 'sidebarSettings' }, photoViewer: { show: false, hash: 'photoViewer', image: [], submission: [] }, gifPlayer: { show: false, hash: 'gifPlayer', gif: [], submission: [] }, embedViewer: { show: false, hash: 'embedViewer', submission: [] }, messages: { show: false, hash: 'messages' }, search: { show: false, hash: 'search' }, mobileVisitorWarning: { show: false, hash: 'mobileVisitorWarning' }, banUser: { show: false, hash: 'banUser', user: [], } }; <|start_filename|>resources/assets/sass/icons/css/fontello.css<|end_filename|> @font-face { font-family: 'fontello'; src: url('../font/fontello.eot?95334205'); src: url('../font/fontello.eot?95334205#iefix') format('embedded-opentype'), url('../font/fontello.woff2?95334205') format('woff2'), url('../font/fontello.woff?95334205') format('woff'), url('../font/fontello.ttf?95334205') format('truetype'), url('../font/fontello.svg?95334205#fontello') format('svg'); font-weight: normal; font-style: normal; } /* Chrome hack: SVG is rendered more smooth in Windozze. 100% magic, uncomment if you need it. */ /* Note, that will break hinting! In other OS-es font will be not as sharp as it could be */ /* @media screen and (-webkit-min-device-pixel-ratio:0) { @font-face { font-family: 'fontello'; src: url('../font/fontello.svg?95334205#fontello') format('svg'); } } */ [class^="v-"]:before, [class*=" v-"]:before { font-family: "fontello"; font-style: normal; font-weight: normal; speak: none; display: inline-block; text-decoration: inherit; width: 1em; margin-right: .2em; text-align: center; /* opacity: .8; */ /* For safety - reset parent styles, that can break glyph codes*/ font-variant: normal; text-transform: none; /* fix buttons height, for twitter bootstrap */ line-height: 1em; /* Animation center compensation - margins should be symmetric */ /* remove if not needed */ margin-left: .2em; /* you can be more comfortable with increased icons size */ /* font-size: 120%; */ /* Font smoothing. That was taken from TWBS */ -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; /* Uncomment for 3D effect */ /* text-shadow: 1px 1px 1px rgba(127, 127, 127, 0.3); */ } .v-send-1:before { content: '\e800'; } /* '' */ .v-letter:before { content: '\e801'; } /* '' */ .v-seen:before { content: '\e802'; } /* '' */ .v-chat:before { content: '\e803'; } /* '' */ .v-comment:before { content: '\e804'; } /* '' */ .v-cancel:before { content: '\e806'; } /* '' */ .v-cancel-small:before { content: '\e807'; } /* '' */ .v-link:before { content: '\e808'; } /* '' */ .v-add-content:before { content: '\e809'; } /* '' */ .v-tools:before { content: '\e80a'; } /* '' */ .v-calendar:before { content: '\e80c'; } /* '' */ .v-picture:before { content: '\e80e'; } /* '' */ .v-heart-filled:before { content: '\e810'; } /* '' */ .v-bell-on:before { content: '\e812'; } /* '' */ .v-image:before { content: '\e813'; } /* '' */ .v-dot-3:before { content: '\e814'; } /* '' */ .v-left:before { content: '\e815'; } /* '' */ .v-attention-alt:before { content: '\e816'; } /* '' */ .v-upload:before { content: '\e817'; } /* '' */ .v-hide:before { content: '\e818'; } /* '' */ .v-photo:before { content: '\e819'; } /* '' */ .v-submit:before { content: '\e81a'; } /* '' */ .v-more:before { content: '\e81b'; } /* '' */ .v-video:before { content: '\e81e'; } /* '' */ .v-atsign:before { content: '\e81f'; } /* '' */ .v-submissions:before { content: '\e820'; } /* '' */ .v-reply:before { content: '\e821'; } /* '' */ .v-send:before { content: '\e822'; } /* '' */ .v-logout:before { content: '\e824'; } /* '' */ .v-plus:before { content: '\e827'; } /* '' */ .v-refetch:before { content: '\e82d'; } /* '' */ .v-channel:before { content: '\e82e'; } /* '' */ .v-ok:before { content: '\e830'; } /* '' */ .v-success:before { content: '\e833'; } /* '' */ .v-trash:before { content: '\e834'; } /* '' */ .v-text:before { content: '\e835'; } /* '' */ .v-attention:before { content: '\e836'; } /* '' */ .v-gif:before { content: '\e837'; } /* '' */ .v-location:before { content: '\e838'; } /* '' */ .v-config:before { content: '\e83c'; } /* '' */ .v-scroll-up:before { content: '\e83d'; } /* '' */ .v-sad:before { content: '\e840'; } /* '' */ .v-doc-add:before { content: '\e845'; } /* '' */ .v-minus:before { content: '\e846'; } /* '' */ .v-shocked:before { content: '\e848'; } /* '' */ .v-right-fat:before { content: '\e849'; } /* '' */ .v-left-fat:before { content: '\e84a'; } /* '' */ .v-people:before { content: '\e84b'; } /* '' */ .v-edit:before { content: '\e84c'; } /* '' */ .v-load-more:before { content: '\e84d'; } /* '' */ .v-book:before { content: '\e84f'; } /* '' */ .v-heart:before { content: '\e851'; } /* '' */ .v-clock:before { content: '\e852'; } /* '' */ .v-block:before { content: '\e853'; } /* '' */ .v-calendar-1:before { content: '\e854'; } /* '' */ .v-delete:before { content: '\e855'; } /* '' */ .v-approve:before { content: '\e856'; } /* '' */ .v-left-hand:before { content: '\e857'; } /* '' */ .v-child:before { content: '\e858'; } /* '' */ .v-up-fat:before { content: '\e859'; } /* '' */ .v-down-fat:before { content: '\e85a'; } /* '' */ .v-next:before { content: '\e85b'; } /* '' */ .v-previous:before { content: '\e85c'; } /* '' */ .v-unbookmark:before { content: '\e85d'; } /* '' */ .v-gif-1:before { content: '\e85f'; } /* '' */ .v-play:before { content: '\e860'; } /* '' */ .v-down-dir:before { content: '\e861'; } /* '' */ .v-play-outline:before { content: '\e862'; } /* '' */ .v-exchange:before { content: '\e863'; } /* '' */ .v-more-vertical:before { content: '\e864'; } /* '' */ .v-home:before { content: '\e865'; } /* '' */ .v-dashboard:before { content: '\e866'; } /* '' */ .v-inbox:before { content: '\e867'; } /* '' */ .v-hash:before { content: '\f029'; } /* '' */ .v-bell-1:before { content: '\f03f'; } /* '' */ .v-users:before { content: '\f064'; } /* '' */ .v-checked:before { content: '\f06d'; } /* '' */ .v-bookmark:before { content: '\f097'; } /* '' */ .v-twitter:before { content: '\f099'; } /* '' */ .v-menu:before { content: '\f0c9'; } /* '' */ .v-keyboard:before { content: '\f11c'; } /* '' */ .v-flag-empty:before { content: '\f11d'; } /* '' */ .v-down:before { content: '\f175'; } /* '' */ .v-up:before { content: '\f176'; } /* '' */ .v-night:before { content: '\f186'; } /* '' */ .v-credits:before { content: '\f1c9'; } /* '' */ .v-help:before { content: '\f1cd'; } /* '' */ .v-unchecked:before { content: '\f1db'; } /* '' */ .v-sliders:before { content: '\f1de'; } /* '' */ .v-press:before { content: '\f1ea'; } /* '' */ .v-bell-off:before { content: '\f1f7'; } /* '' */ .v-chart-pie:before { content: '\f200'; } /* '' */ .v-toggle-off:before { content: '\f204'; } /* '' */ .v-toggle-on:before { content: '\f205'; } /* '' */ .v-profile:before { content: '\f2c0'; } /* '' */ .v-blog:before { content: '\f314'; } /* '' */ <|start_filename|>resources/assets/js/mixins/InputHelpers.js<|end_filename|> export default { methods: { /** * wether or not the input contains only spaces/line-breakers. * * @return boolean **/ isEmpty(input) { return input.trim().length == 0; }, insertPickedItem(textAreaId, pickedStr, starterIndex, typedLength) { let textArea = document.getElementById(textAreaId); let cursorPosition = this.getCursorPosition(textArea); this.replaceBetween( textArea, pickedStr, starterIndex, starterIndex + typedLength ); this.updateCursorPosition( textArea, starterIndex + pickedStr.length ); }, replaceBetween(textArea, replaceWith, start, end) { let before = textArea.value.substring(0, start); let after = textArea.value.substring( end + 1, textArea.value.length ); textArea.value = before + replaceWith + after; // to make vue's reactivity work: this.message = textArea.value; }, updateCursorPosition(textArea, position) { textArea.selectionStart = position; textArea.selectionEnd = position; textArea.focus(); }, getCursorPosition(textArea) { return textArea.selectionStart; }, getCursorPositionById(id) { let textArea = document.getElementById(id); return textArea.selectionStart; }, lastTypedCharacter(id) { let cursorPosition = this.getCursorPosition( document.getElementById(id) ); return cursorPosition - 1; } } }; <|start_filename|>resources/assets/js/mixins/Submission.js<|end_filename|> import TextSubmission from '../components/submission/TextSubmission.vue'; import LinkSubmission from '../components/submission/LinkSubmission.vue'; import ImgSubmission from '../components/submission/ImgSubmission.vue'; import GifSubmission from '../components/submission/GifSubmission.vue'; export default { components: { TextSubmission, LinkSubmission, ImgSubmission, GifSubmission }, data() { return { hidden: false }; }, props: ['list', 'full'], computed: { type() { return this.list.type; }, liked: { get() { try { return Store.state.submissions.likes.indexOf(this.list.id) !== -1 ? true : false; } catch (error) { return false; } }, set() { if (this.liked) { this.list.likes_count--; let index = Store.state.submissions.likes.indexOf(this.list.id); Store.state.submissions.likes.splice(index, 1); return; } this.list.likes_count++; Store.state.submissions.likes.push(this.list.id); } }, bookmarked: { get() { try { return Store.state.bookmarks.submissions.indexOf(this.list.id) !== -1 ? true : false; } catch (error) { return false; } }, set() { if (Store.state.bookmarks.submissions.indexOf(this.list.id) !== -1) { let index = Store.state.bookmarks.submissions.indexOf(this.list.id); Store.state.bookmarks.submissions.splice(index, 1); return; } Store.state.bookmarks.submissions.push(this.list.id); } }, points() { return this.list.likes_count; }, /** * Does the auth user own the submission * * @return Boolean */ owns() { return auth.id == this.list.author.id; }, date() { return moment(this.list.created_at) .utc(moment().format('Z')) .fromNow(); }, /** * Whether or not user wants to see NSFW content's image * * (Hint: The base idea is that we don't display NSFW content) * If the user wants to see NSFW media then return false, like it's not NSFW at all * Otherwise return true which means the media must not be displayed. * (false: the media will be displayed) * * @return boolean */ nsfw() { return this.list.nsfw && !Store.settings.feed.include_nsfw_submissions; }, owns() { return auth.id === this.list.author.id; }, showApprove() { return ( !this.list.approved_at && (Store.state.moderatingAt.indexOf(this.list.channel_id) != -1 || meta.isVotenAdministrator) && !this.owns ); }, showDisapprove() { return !this.list.disapproved_at && (Store.state.moderatingAt.indexOf(this.list.channel_id) != -1 || meta.isVotenAdministrator) && !this.owns; }, showNSFW() { return ( (this.owns || Store.state.moderatingAt.indexOf(this.list.channel_id) != -1 || meta.isVotenAdministrator) && !this.list.nsfw ); }, showSFW() { return ( (this.owns || Store.state.moderatingAt.indexOf(this.list.channel_id) != -1 || meta.isVotenAdministrator) && this.list.nsfw ); }, showRemoveTumbnail() { return this.owns && this.list.content.thumbnail ? true : false; } }, methods: { /** * Approves the submission. Only the moderators of channel are allowed to do this. * * @return void */ approve() { this.list.approved_at = this.now(); axios .post(`/submissions/${this.list.id}/approve`) .catch(() => { this.list.approved_at = null; }); }, removeThumbnail() { this.list.content.thumbnail = null; this.list.content.img = null; axios.delete(`/submissions/${this.list.id}/thumbnail`); }, /** * marks the submission as NSFW (not safe for work) * * @return void */ markAsSFW() { this.list.nsfw = false; axios.delete(`/submissions/${this.list.id}/nsfw`).catch(() => { this.list.nsfw = true; }); }, /** * marks the submission as NSFW (not safe for work) * * @return void */ markAsNSFW() { this.list.nsfw = true; axios.post(`/submissions/${this.list.id}/nsfw`).catch(() => { this.list.nsfw = false; }); }, like: _.debounce( function() { if (this.isGuest) { this.mustBeLogin(); return; } this.liked =! this.liked; axios.post(`/submissions/${this.list.id}/like`).catch(error => { this.liked =! this.liked; }); }, 200, { leading: true, trailing: false } ), bookmark: _.debounce( function() { if (this.isGuest) { this.mustBeLogin(); return; } this.bookmarked = !this.bookmarked; axios.post(`/submissions/${this.list.id}/bookmark`).catch(() => { this.bookmarked = !this.bookmarked; }); }, 200, { leading: true, trailing: false } ), report() { if (this.isGuest) { this.mustBeLogin(); return; } Store.modals.reportSubmission.show = true; Store.modals.reportSubmission.submission = this.list; }, hide() { if (this.isGuest) { this.mustBeLogin(); return; } this.hidden = true; axios.post(`/submissions/${this.list.id}/hide`).catch(() => { this.hidden = false; }); }, showPhotoViewer(image) { Store.modals.photoViewer.image = image; Store.modals.photoViewer.submission = this.list; Store.modals.photoViewer.show = true; }, showEmbed() { Store.modals.embedViewer.submission = this.list; Store.modals.embedViewer.show = true; }, showGifPlayer(gif) { Store.modals.gifPlayer.gif = gif; Store.modals.gifPlayer.submission = this.list; Store.modals.gifPlayer.show = true; } } }; <|start_filename|>resources/assets/js/app.js<|end_filename|> // All the installation codes import './bootstrap'; // A general Store that holds all the global data (no, we're not using Vuex, because we're not sold on it!) import './store'; // Vue instance import './vue-codes'; <|start_filename|>resources/assets/js/bootstrap.js<|end_filename|> import Raven from 'raven-js'; import RavenVue from 'raven-js/plugins/vue'; if (Laravel.env !== 'local') { Raven.config(Laravel.sentry) .addPlugin(RavenVue, Vue) .install(); } window.moment = require('moment-timezone'); window.moment.tz.setDefault('UTC'); import ElementUI from 'element-ui'; import locale from 'element-ui/lib/locale/lang/en'; Vue.use(ElementUI, { locale }); import LocalStorage from './plugins/local-storage'; Vue.use(LocalStorage); import VueProgressBar from 'vue-progressbar'; const VueProgressBarOptions = { color: '#5587d7', failedColor: '#db6e6e', thickness: '3px' }; Vue.use(VueProgressBar, VueProgressBarOptions); import infiniteScroll from 'vue-infinite-scroll'; Vue.use(infiniteScroll); window.Push = require('push.js'); /** * We'll load the axios HTTP library which allows us to easily issue requests * to our Laravel back-end. This library automatically handles sending the * CSRF token as a header based on the value of the "XSRF" token cookie. */ window.axios = require('axios'); window.axios.defaults.headers.common['X-CSRF-TOKEN'] = window.Laravel.csrfToken; window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; if (meta.isGuest === true) { window.axios.defaults.baseURL = Laravel.url + '/api/guest/'; } else { window.axios.defaults.baseURL = Laravel.url + '/api/'; } axios.interceptors.response.use( function(response) { return response; }, function(error) { app.$Progress.fail(); if (error.response.status !== 422) { try { let errorMessage = typeof error.response.data.errors.more_info == 'undefined' ? error.response.data.message : error.response.data.errors.more_info; app.$message({ message: errorMessage, type: 'error' }); } catch (error) { app.$message({ message: 'Oops, something went wrong.', type: 'error', showClose: true }); } } return Promise.reject(error); } ); /** * Echo exposes an expressive API for subscribing to channels and listening * for events that are broadcast by Laravel. Echo and event broadcasting * allows your team to easily build robust real-time web applications. */ import Echo from 'laravel-echo'; window.io = require('socket.io-client'); if (Laravel.broadcasting.service == 'pusher' && Laravel.broadcasting.pusher.key.trim()) { window.Echo = new Echo({ broadcaster: 'pusher', key: Laravel.broadcasting.pusher.key, cluster: Laravel.broadcasting.pusher.cluster, encrypted: true }); } else if (Laravel.broadcasting.service == 'echo' && Laravel.broadcasting.echo.key.trim()) { window.Echo = new Echo({ broadcaster: 'socket.io', key: Laravel.broadcasting.echo.key, host: Laravel.broadcasting.echo.host + ':' + Laravel.broadcasting.echo.port }); } /** * A small lirary that helps us with supporting Emojis in Voten's * Great Markdown editor. */ window.emojione = require('./libs/emojione.min'); <|start_filename|>resources/assets/js/store.js<|end_filename|> import home from './store/home'; import tour from './store/tour'; import channel from './store/channel'; import user from './store/user'; import modals from './store/modals'; import state from './store/state'; import settings from './store/settings'; import methods from './store/methods'; import submission from './store/submission'; import bookmarkedSubmissions from './store/bookmarkedSubmissions'; import bookmarkedComments from './store/bookmarkedComments'; import bookmarkedChannels from './store/bookmarkedChannels'; import subscribedChannels from './store/subscribedChannels'; import bookmarkedUsers from './store/bookmarkedUsers'; window.Store = { // state: data stored in the Store.state gets synced via the LocalStorage; // which means it's the same accross all the open windows. state, // general settings that aren't limited to one componenet methods, page: { channel, submission, user, home, bookmarkedSubmissions, bookmarkedComments, bookmarkedChannels, bookmarkedUsers, subscribedChannels }, // client-side settings: There's not need to save these settings in the server-side. // However, we do sync them to the cloud. settings: _.merge(settings, window.clientsideSettings), // Set a hash for each modal to make it searchable to see which modal the // window.location.hash is pointing to. modals, // the tour for new new registered users tour, // is the Store initial filled yet? (it gets filled right after a page reload) initialFilled: false }; <|start_filename|>resources/assets/js/store/channel.js<|end_filename|> export default { temp: [], page: 0, NoMoreItems: false, nothingFound: false, submissions: [], loading: null, getChannel(channel_name, set = true) { return new Promise((resolve, reject) => { // if a guest has landed on a submission page if (preload.channel) { this.setChannel(preload.channel); delete preload.channel; resolve(); return; } if ( typeof this.temp.name == 'undefined' || this.temp.name != channel_name ) { axios .get('/channels', { params: { name: channel_name } }) .then((response) => { if (set == true) { this.setChannel(response.data.data); resolve(response); } resolve(response.data.data); }) .catch((error) => { reject(error); }); } else { resolve(this.temp); } }); }, setChannel(data) { this.temp = data; }, getSubmissions(sort = 'hot', channelName) { return new Promise((resolve, reject) => { this.page++; this.loading = true; // if a guest has landed on a channel page if (preload.submissions && this.page == 1) { this.submissions = preload.submissions.data; if (!this.submissions.length) this.nothingFound = true; if (preload.submissions.next_page_url == null) this.NoMoreItems = true; this.loading = false; delete preload.submissions; resolve(); return; } axios .get('/channels/submissions', { params: { sort: sort, page: this.page, channel_name: channelName } }) .then((response) => { this.submissions = [ ...this.submissions, ...response.data.data ]; if (!this.submissions.length) this.nothingFound = true; if (response.data.links.next == null) this.NoMoreItems = true; this.loading = false; resolve(response); }) .catch((error) => { this.loading = false; reject(error); }); }); }, clear() { this.submissions = []; this.loading = true; this.nothingFound = false; this.NoMoreItems = false; this.page = 0; } }; <|start_filename|>webpack.mix.js<|end_filename|> const { mix } = require('laravel-mix'); mix .js('resources/assets/js/app.js', 'public/js') // .js('resources/assets/js/bootstrap4.js', 'public/js') .sass('resources/assets/sass/app.scss', 'public/css') .sass('resources/assets/sass/admin.scss', 'public/css') .sourceMaps() .extract([ 'vue', 'axios', 'lodash', 'vue-ua', 'vue-router', 'laravel-echo', 'pusher-js', 'element-ui', 'moment-timezone', 'vue-template-compiler' ]) .autoload({ vue: 'Vue', lodash: '_', 'pusher-js': 'Pusher', }); // run versioning on production only if (mix.inProduction()) { mix.version(); } <|start_filename|>resources/assets/js/store/bookmarkedChannels.js<|end_filename|> export default { NoMoreItems: false, loading: null, nothingFound: false, page: 0, channels: [], getChannels() { return new Promise((resolve, reject) => { this.page++; this.loading = true; axios .get('/channels/bookmarked', { params: { page: this.page } }) .then(response => { this.channels = [...this.channels, ...response.data.data]; if (response.data.links.next == null) this.NoMoreItems = true; if (this.channels.length == 0) this.nothingFound = true; this.loading = false; resolve(response); }) .catch(error => { reject(error); }); }); }, clear() { this.NoMoreItems = false; this.loading = null; this.nothingFound = false; this.page = 0; this.channels = []; } }; <|start_filename|>resources/assets/js/mixins/SubmitFormUpload.js<|end_filename|> export default { methods: { //////////////////////////////////////////// /////////// Photo Upload Methods ////////// //////////////////////////////////////////// beforePhotoUploadCheckings(file) { const isInCorrectFormat = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png'; const doesNotExceedFileSize = file.size / 1024 / 1024 < this.photosSizeLimit; if (!isInCorrectFormat) { this.$message.error( 'Only files with jpg/png formats are allowed! ' ); } if (!doesNotExceedFileSize) { this.$message.error( `Uplaoded photo size can not exceed ${ this.photosSizeLimit }mb!` ); } return isInCorrectFormat && doesNotExceedFileSize; }, exceededPhotoFileCount(files, fileList) { this.$message.error( `The limit is ${this.photosNumberLimit}, you selected ${ files.length } files this time. You may add up to ${this.photosNumberLimit - fileList.length} more files for this post. ` ); }, failedPhotoUpload(err, file, fileList) { this.$message.error(err.message); this.photos = fileList; }, removePhoto(file, fileList) { this.photos = fileList; }, photoPreview(file) { this.previewPhotoImage = file.url; this.previewPhotoFileName = file.name; this.previewPhotoModal = true; }, successfulPhotoUpload(response, file, fileList) { file.id = response.data.id; this.photos.push(file); }, ///////////////////////////////////////////// /////////// GIF Upload Methods ///////////// ///////////////////////////////////////////// // beforeGifUploadCheckings(file) { // const isInCorrectFormat = file.type === 'image/gif'; // const doesNotExceedFileSize = // file.size / 1024 / 1024 < this.gifSizeLimit; // if (!isInCorrectFormat) { // this.$message.error( // 'Only animated GIF files with .gif format are allowed! ' // ); // } // if (!doesNotExceedFileSize) { // this.$message.error( // `Uplaoded GIF size can not exceed ${this.gifSizeLimit}mb!` // ); // } // return isInCorrectFormat && doesNotExceedFileSize; // }, // exceededGifFileCount(files, fileList) { // this.$message.error( // `You can only Upload one GIF file per submission.` // ); // }, // failedGifUpload(err, file, fileList) { // this.$message.error(err.message); // this.gif_id = null; // }, // removeGif(file, fileList) { // this.gif_id = null; // }, // gifPreview(file) { // this.previewGifImage = file.url; // this.previewGifFileName = file.name; // this.previewGifModal = true; // }, // successfulGifUpload(response, file, fileList) { // this.gif_id = response.data.id; // } } };
AhGhanima/voten
<|start_filename|>lib/index.js<|end_filename|> 'use strict'; const rules = { 'use-inclusive-words': require('./rules/use-inclusive-words') }; module.exports = { configs: { all: { plugins: ['inclusive-language'], rules: { 'inclusive-language/use-inclusive-words': 'error' } } }, rules }; <|start_filename|>tests/lib/rules/use-inclusive-words-lint-strings.test.js<|end_filename|> 'use strict'; const rule = require('../../../lib/rules/use-inclusive-words'); const customConfigDefault = { words: [ { word: 'guys', suggestion: 'people', explanation: "Instead of '{{word}}', you can use '{{suggestion}}'." } ], allowedTerms: [ 'masterfoo', 'foomaster', 'bazmasterbar', { term: 'blob/master', allowPartialMatches: true }, { term: 'definitiely-partial-guys', allowPartialMatches: true }, { term: 'not-partial-guys', allowPartialMatches: false }, { term: 'notslugpartialguys', allowPartialMatches: true } ], lintStrings: true }; const RuleTester = require('eslint').RuleTester; const ruleTester = new RuleTester({ parserOptions: { ecmaFeatures: { jsx: true } } }); ruleTester.run('use-inclusive-words', rule, { valid: [ { code: 'var whoWeAre = "We are allies."' }, { code: 'var message = "This is a group of people."', options: [customConfigDefault] }, { code: 'var ccType = "MasterFoo"', options: [customConfigDefault] }, { code: 'var fooMaster = 1', options: [customConfigDefault] }, { code: 'var BazMasterBar = function () {}', options: [customConfigDefault] }, { code: '/* This is an example of non-partial matching (not-partial-guys) */', options: [customConfigDefault] }, { code: '/* This is an example of partial matching (extra-definitiely-partial-guys) */', options: [customConfigDefault] }, { code: '// A comment with a a url https://myvcs.com/someAccount/blob/master/README.md', options: [customConfigDefault] }, { code: 'var something_notslugpartialguys = 323', options: [customConfigDefault] } ], invalid: [ { code: 'var isBlacklisted = true', errors: [ { message: "To convey the same idea, consider 'blocklist' instead of 'blacklist'." } ], output: 'var isBlacklisted = true' }, { code: 'function rulesUpdate(whitelist) {}', errors: [ { message: "To convey the same idea, consider 'allowlist' instead of 'whitelist'." } ], output: 'function rulesUpdate(whitelist) {}' }, { code: '// This updates the master branch of the repository.', errors: [ { message: "Instead of 'master', you can use 'primary'." } ], output: '// This updates the master branch of the repository.' }, { code: 'var sendUpdate = isMasterConnected ? true : isSlaveConnected', errors: [ { message: "Instead of 'master', you can use 'primary'." }, { message: "Instead of 'slave', you really should consider an alternative like 'secondary'." } ], output: 'var sendUpdate = isMasterConnected ? true : isSlaveConnected' }, { code: 'var message = "This is a group of guys."', options: [customConfigDefault], errors: [ { message: "Instead of 'guys', you can use 'people'." } ], output: 'var message = "This is a group of guys."' }, { code: 'var fooMasters = 1', options: [customConfigDefault], errors: [ { message: "Instead of 'master', you can use 'primary'." } ], output: 'var fooMasters = 1' }, { code: 'var message = "made-it-partial-not-partial-guys"', options: [customConfigDefault], errors: [ { message: "Instead of 'guys', you can use 'people'." } ], output: 'var message = "made-it-partial-not-partial-guys"' }, { code: 'var classname = "master-bar"', options: [customConfigDefault], errors: [ { message: "Instead of 'master', you can use 'primary'.", suggestions: [ { desc: "Replace word 'master' with 'primary.'" }, { desc: "Replace word 'master' with 'main.'" } ] } ], output: 'var classname = "master-bar"' }, { code: '<MasterClass />', errors: [ { message: "Instead of 'master', you can use 'primary'." } ], output: '<MasterClass />' }, { code: '<Foo blacklist={blacklist} />', errors: [ { message: "To convey the same idea, consider 'blocklist' instead of 'blacklist'." }, { message: "To convey the same idea, consider 'blocklist' instead of 'blacklist'." } ], output: '<Foo blacklist={blacklist} />' } ] }); <|start_filename|>lib/utils/custom-rule-config.js<|end_filename|> const { existsSync, readFileSync } = require('fs'); const { resolve } = require('path'); function getCustomRuleConfigFromOptions(options) { if (typeof options === 'string') { const customPath = resolve(process.cwd(), options); if (existsSync(customPath)) { return JSON.parse(readFileSync(customPath), 'utf8'); } } else if (typeof options === 'object') { return options; } return; } /** * Get the custom rule config if any. * * @param {object} context The ESLint context * @returns {object|null} The resolved custom rule config or null if none exists. */ exports.getCustomRuleConfig = function getCustomRuleConfig(context) { if (!context.options || context.options.length === 0) { // no custom configuration path was given return null; } const customConfig = getCustomRuleConfigFromOptions(context.options[0]); // massage allowedTerms for backwards compat const allowedTerms = (customConfig.allowedTerms || []).map( (allowedTerm) => { switch (typeof allowedTerm) { case 'string': { // if it's a string, the correct default for backwards compat is to only match whole words // so `allowPartialMatches` must default to false return { term: allowedTerm, allowPartialMatch: false }; } case 'object': { // if it's already an object, just return it return allowedTerm; } default: { throw new Error( `'allowedTerms' must be an array of strings or objects. Received '${typeof allowedTerm}'` ); } } } ); return { // give everything safe defaults words: customConfig.words || [], allowedTerms: allowedTerms, autofix: customConfig.autofix, lintStrings: customConfig.lintStrings }; };
Shinigami92/eslint-plugin-inclusive-language